OSDN Git Service

gcc/ada
[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, 2006, 2007, 2008 Free Software Foundation,
121 Inc.
122
123 Permission is granted to copy, distribute and/or modify this document
124 under the terms of the GNU Free Documentation License, Version 1.2
125 or any later version published by the Free Software Foundation;
126 with the Invariant Sections being ``GNU Free Documentation License'', with the
127 Front-Cover Texts being
128 ``@value{EDITION} User's Guide'',
129 and with no Back-Cover Texts.
130 A copy of the license is included in the section entitled
131 ``GNU Free Documentation License''.
132 @end copying
133
134 @titlepage
135 @title @value{EDITION} User's Guide
136 @ifset vms
137 @sp 1
138 @flushright
139 @titlefont{@i{@value{PLATFORM}}}
140 @end flushright
141 @end ifset
142
143 @sp 2
144
145 @subtitle GNAT, The GNU Ada Compiler
146 @versionsubtitle
147 @author AdaCore
148
149 @page
150 @vskip 0pt plus 1filll
151
152 @insertcopying
153
154 @end titlepage
155
156 @ifnottex
157 @node Top, About This Guide, (dir), (dir)
158 @top @value{EDITION} User's Guide
159
160 @noindent
161 @value{EDITION} User's Guide @value{PLATFORM}
162
163 @noindent
164 GNAT, The GNU Ada Compiler@*
165 GCC version @value{version-GCC}@*
166
167 @noindent
168 AdaCore@*
169
170 @menu
171 * About This Guide::
172 * Getting Started with GNAT::
173 * The GNAT Compilation Model::
174 * Compiling Using gcc::
175 * Binding Using gnatbind::
176 * Linking Using gnatlink::
177 * The GNAT Make Program gnatmake::
178 * Improving Performance::
179 * Renaming Files Using gnatchop::
180 * Configuration Pragmas::
181 * Handling Arbitrary File Naming Conventions Using gnatname::
182 * GNAT Project Manager::
183 * The Cross-Referencing Tools gnatxref and gnatfind::
184 * The GNAT Pretty-Printer gnatpp::
185 * The GNAT Metric Tool gnatmetric::
186 * File Name Krunching Using gnatkr::
187 * Preprocessing Using gnatprep::
188 @ifset vms
189 * The GNAT Run-Time Library Builder gnatlbr::
190 @end ifset
191 * The GNAT Library Browser gnatls::
192 * Cleaning Up Using gnatclean::
193 @ifclear vms
194 * GNAT and Libraries::
195 * Using the GNU make Utility::
196 @end ifclear
197 * Memory Management Issues::
198 * Stack Related Facilities::
199 * Verifying Properties Using gnatcheck::
200 * Creating Sample Bodies Using gnatstub::
201 * Other Utility Programs::
202 * Running and Debugging Ada Programs::
203 @ifset vms
204 * Compatibility with HP Ada::
205 @end ifset
206 * Platform-Specific Information for the Run-Time Libraries::
207 * Example of Binder Output File::
208 * Elaboration Order Handling in GNAT::
209 * Conditional Compilation::
210 * Inline Assembler::
211 * Compatibility and Porting Guide::
212 @ifset unw
213 * Microsoft Windows Topics::
214 @end ifset
215 * GNU Free Documentation License::
216 * Index::
217
218  --- The Detailed Node Listing ---
219
220 About This Guide
221
222 * What This Guide Contains::
223 * What You Should Know before Reading This Guide::
224 * Related Information::
225 * Conventions::
226
227 Getting Started with GNAT
228
229 * Running GNAT::
230 * Running a Simple Ada Program::
231 * Running a Program with Multiple Units::
232 * Using the gnatmake Utility::
233 @ifset vms
234 * Editing with Emacs::
235 @end ifset
236 @ifclear vms
237 * Introduction to GPS::
238 @end ifclear
239
240 The GNAT Compilation Model
241
242 * Source Representation::
243 * Foreign Language Representation::
244 * File Naming Rules::
245 * Using Other File Names::
246 * Alternative File Naming Schemes::
247 * Generating Object Files::
248 * Source Dependencies::
249 * The Ada Library Information Files::
250 * Binding an Ada Program::
251 * Mixed Language Programming::
252 @ifclear vms
253 * Building Mixed Ada & C++ Programs::
254 * Comparison between GNAT and C/C++ Compilation Models::
255 @end ifclear
256 * Comparison between GNAT and Conventional Ada Library Models::
257 @ifset vms
258 * Placement of temporary files::
259 @end ifset
260
261 Foreign Language Representation
262
263 * Latin-1::
264 * Other 8-Bit Codes::
265 * Wide Character Encodings::
266
267 Compiling Ada Programs With gcc
268
269 * Compiling Programs::
270 * Switches for gcc::
271 * Search Paths and the Run-Time Library (RTL)::
272 * Order of Compilation Issues::
273 * Examples::
274
275 Switches for gcc
276
277 * Output and Error Message Control::
278 * Warning Message Control::
279 * Debugging and Assertion Control::
280 * Validity Checking::
281 * Style Checking::
282 * Run-Time Checks::
283 * Using gcc for Syntax Checking::
284 * Using gcc for Semantic Checking::
285 * Compiling Different Versions of Ada::
286 * Character Set Control::
287 * File Naming Control::
288 * Subprogram Inlining Control::
289 * Auxiliary Output Control::
290 * Debugging Control::
291 * Exception Handling Control::
292 * Units to Sources Mapping Files::
293 * Integrated Preprocessing::
294 @ifset vms
295 * Return Codes::
296 @end ifset
297
298 Binding Ada Programs With gnatbind
299
300 * Running gnatbind::
301 * Switches for gnatbind::
302 * Command-Line Access::
303 * Search Paths for gnatbind::
304 * Examples of gnatbind Usage::
305
306 Switches for gnatbind
307
308 * Consistency-Checking Modes::
309 * Binder Error Message Control::
310 * Elaboration Control::
311 * Output Control::
312 * Binding with Non-Ada Main Programs::
313 * Binding Programs with No Main Subprogram::
314
315 Linking Using gnatlink
316
317 * Running gnatlink::
318 * Switches for gnatlink::
319
320 The GNAT Make Program gnatmake
321
322 * Running gnatmake::
323 * Switches for gnatmake::
324 * Mode Switches for gnatmake::
325 * Notes on the Command Line::
326 * How gnatmake Works::
327 * Examples of gnatmake Usage::
328
329 Improving Performance
330 * Performance Considerations::
331 * Reducing Size of Ada Executables with gnatelim::
332 * Reducing Size of Executables with unused subprogram/data elimination::
333
334 Performance Considerations
335 * Controlling Run-Time Checks::
336 * Use of Restrictions::
337 * Optimization Levels::
338 * Debugging Optimized Code::
339 * Inlining of Subprograms::
340 * Other Optimization Switches::
341 * Optimization and Strict Aliasing::
342 @ifset vms
343 * Coverage Analysis::
344 @end ifset
345
346 Reducing Size of Ada Executables with gnatelim
347 * About gnatelim::
348 * Running gnatelim::
349 * Correcting the List of Eliminate Pragmas::
350 * Making Your Executables Smaller::
351 * Summary of the gnatelim Usage Cycle::
352
353 Reducing Size of Executables with unused subprogram/data elimination
354 * About unused subprogram/data elimination::
355 * Compilation options::
356
357 Renaming Files Using gnatchop
358
359 * Handling Files with Multiple Units::
360 * Operating gnatchop in Compilation Mode::
361 * Command Line for gnatchop::
362 * Switches for gnatchop::
363 * Examples of gnatchop Usage::
364
365 Configuration Pragmas
366
367 * Handling of Configuration Pragmas::
368 * The Configuration Pragmas Files::
369
370 Handling Arbitrary File Naming Conventions Using gnatname
371
372 * Arbitrary File Naming Conventions::
373 * Running gnatname::
374 * Switches for gnatname::
375 * Examples of gnatname Usage::
376
377 GNAT Project Manager
378
379 * Introduction::
380 * Examples of Project Files::
381 * Project File Syntax::
382 * Objects and Sources in Project Files::
383 * Importing Projects::
384 * Project Extension::
385 * Project Hierarchy Extension::
386 * External References in Project Files::
387 * Packages in Project Files::
388 * Variables from Imported Projects::
389 * Naming Schemes::
390 * Library Projects::
391 * Stand-alone Library Projects::
392 * Switches Related to Project Files::
393 * Tools Supporting Project Files::
394 * An Extended Example::
395 * Project File Complete Syntax::
396
397 The Cross-Referencing Tools gnatxref and gnatfind
398
399 * gnatxref Switches::
400 * gnatfind Switches::
401 * Project Files for gnatxref and gnatfind::
402 * Regular Expressions in gnatfind and gnatxref::
403 * Examples of gnatxref Usage::
404 * Examples of gnatfind Usage::
405
406 The GNAT Pretty-Printer gnatpp
407
408 * Switches for gnatpp::
409 * Formatting Rules::
410
411 The GNAT Metrics Tool gnatmetric
412
413 * Switches for gnatmetric::
414
415 File Name Krunching Using gnatkr
416
417 * About gnatkr::
418 * Using gnatkr::
419 * Krunching Method::
420 * Examples of gnatkr Usage::
421
422 Preprocessing Using gnatprep
423 * Using gnatprep::
424 * Switches for gnatprep::
425 * Form of Definitions File::
426 * Form of Input Text for gnatprep::
427
428 @ifset vms
429 The GNAT Run-Time Library Builder gnatlbr
430
431 * Running gnatlbr::
432 * Switches for gnatlbr::
433 * Examples of gnatlbr Usage::
434 @end ifset
435
436 The GNAT Library Browser gnatls
437
438 * Running gnatls::
439 * Switches for gnatls::
440 * Examples of gnatls Usage::
441
442 Cleaning Up Using gnatclean
443
444 * Running gnatclean::
445 * Switches for gnatclean::
446 @c * Examples of gnatclean Usage::
447
448 @ifclear vms
449
450 GNAT and Libraries
451
452 * Introduction to Libraries in GNAT::
453 * General Ada Libraries::
454 * Stand-alone Ada Libraries::
455 * Rebuilding the GNAT Run-Time Library::
456
457 Using the GNU make Utility
458
459 * Using gnatmake in a Makefile::
460 * Automatically Creating a List of Directories::
461 * Generating the Command Line Switches::
462 * Overcoming Command Line Length Limits::
463 @end ifclear
464
465 Memory Management Issues
466
467 * Some Useful Memory Pools::
468 * The GNAT Debug Pool Facility::
469 @ifclear vms
470 * The gnatmem Tool::
471 @end ifclear
472
473 Stack Related Facilities
474
475 * Stack Overflow Checking::
476 * Static Stack Usage Analysis::
477 * Dynamic Stack Usage Analysis::
478
479 Some Useful Memory Pools
480
481 The GNAT Debug Pool Facility
482
483 @ifclear vms
484 The gnatmem Tool
485
486 * Running gnatmem::
487 * Switches for gnatmem::
488 * Example of gnatmem Usage::
489 @end ifclear
490
491 Verifying Properties Using gnatcheck
492
493 * Format of the Report File::
494 * General gnatcheck Switches::
495 * gnatcheck Rule Options::
496 * Adding the Results of Compiler Checks to gnatcheck Output::
497 * Project-Wide Checks::
498 * Predefined Rules::
499
500 Sample Bodies Using gnatstub
501
502 * Running gnatstub::
503 * Switches for gnatstub::
504
505 Other Utility Programs
506
507 * Using Other Utility Programs with GNAT::
508 * The External Symbol Naming Scheme of GNAT::
509 * Converting Ada Files to html with gnathtml::
510
511 Running and Debugging Ada Programs
512
513 * The GNAT Debugger GDB::
514 * Running GDB::
515 * Introduction to GDB Commands::
516 * Using Ada Expressions::
517 * Calling User-Defined Subprograms::
518 * Using the Next Command in a Function::
519 * Ada Exceptions::
520 * Ada Tasks::
521 * Debugging Generic Units::
522 * GNAT Abnormal Termination or Failure to Terminate::
523 * Naming Conventions for GNAT Source Files::
524 * Getting Internal Debugging Information::
525 * Stack Traceback::
526
527 @ifset vms
528 * LSE::
529 @end ifset
530
531 @ifset vms
532 Compatibility with HP Ada
533
534 * Ada Language Compatibility::
535 * Differences in the Definition of Package System::
536 * Language-Related Features::
537 * The Package STANDARD::
538 * The Package SYSTEM::
539 * Tasking and Task-Related Features::
540 * Pragmas and Pragma-Related Features::
541 * Library of Predefined Units::
542 * Bindings::
543 * Main Program Definition::
544 * Implementation-Defined Attributes::
545 * Compiler and Run-Time Interfacing::
546 * Program Compilation and Library Management::
547 * Input-Output::
548 * Implementation Limits::
549 * Tools and Utilities::
550
551 Language-Related Features
552
553 * Integer Types and Representations::
554 * Floating-Point Types and Representations::
555 * Pragmas Float_Representation and Long_Float::
556 * Fixed-Point Types and Representations::
557 * Record and Array Component Alignment::
558 * Address Clauses::
559 * Other Representation Clauses::
560
561 Tasking and Task-Related Features
562
563 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
564 * Assigning Task IDs::
565 * Task IDs and Delays::
566 * Task-Related Pragmas::
567 * Scheduling and Task Priority::
568 * The Task Stack::
569 * External Interrupts::
570
571 Pragmas and Pragma-Related Features
572
573 * Restrictions on the Pragma INLINE::
574 * Restrictions on the Pragma INTERFACE::
575 * Restrictions on the Pragma SYSTEM_NAME::
576
577 Library of Predefined Units
578
579 * Changes to DECLIB::
580
581 Bindings
582
583 * Shared Libraries and Options Files::
584 * Interfaces to C::
585 @end ifset
586
587 Platform-Specific Information for the Run-Time Libraries
588
589 * Summary of Run-Time Configurations::
590 * Specifying a Run-Time Library::
591 * Choosing the Scheduling Policy::
592 * Solaris-Specific Considerations::
593 * Linux-Specific Considerations::
594 * AIX-Specific Considerations::
595
596 Example of Binder Output File
597
598 Elaboration Order Handling in GNAT
599
600 * Elaboration Code::
601 * Checking the Elaboration Order::
602 * Controlling the Elaboration Order::
603 * Controlling Elaboration in GNAT - Internal Calls::
604 * Controlling Elaboration in GNAT - External Calls::
605 * Default Behavior in GNAT - Ensuring Safety::
606 * Treatment of Pragma Elaborate::
607 * Elaboration Issues for Library Tasks::
608 * Mixing Elaboration Models::
609 * What to Do If the Default Elaboration Behavior Fails::
610 * Elaboration for Access-to-Subprogram Values::
611 * Summary of Procedures for Elaboration Control::
612 * Other Elaboration Order Considerations::
613
614 Conditional Compilation
615 * Use of Boolean Constants::
616 * Debugging - A Special Case::
617 * Conditionalizing Declarations::
618 * Use of Alternative Implementations::
619 * Preprocessing::
620
621 Inline Assembler
622
623 * Basic Assembler Syntax::
624 * A Simple Example of Inline Assembler::
625 * Output Variables in Inline Assembler::
626 * Input Variables in Inline Assembler::
627 * Inlining Inline Assembler Code::
628 * Other Asm Functionality::
629
630 Compatibility and Porting Guide
631
632 * Compatibility with Ada 83::
633 * Compatibility between Ada 95 and Ada 2005::
634 * Implementation-dependent characteristics::
635 @ifclear vms
636 @c This brief section is only in the non-VMS version
637 @c The complete chapter on HP Ada issues is in the VMS version
638 * Compatibility with HP Ada 83::
639 @end ifclear
640 * Compatibility with Other Ada Systems::
641 * Representation Clauses::
642 @ifset vms
643 * Transitioning to 64-Bit GNAT for OpenVMS::
644 @end ifset
645
646 @ifset unw
647 Microsoft Windows Topics
648
649 * Using GNAT on Windows::
650 * CONSOLE and WINDOWS subsystems::
651 * Temporary Files::
652 * Mixed-Language Programming on Windows::
653 * Windows Calling Conventions::
654 * Introduction to Dynamic Link Libraries (DLLs)::
655 * Using DLLs with GNAT::
656 * Building DLLs with GNAT::
657 * GNAT and Windows Resources::
658 * Debugging a DLL::
659 * Setting Stack Size from gnatlink::
660 * Setting Heap Size from gnatlink::
661 @end ifset
662
663 * Index::
664 @end menu
665 @end ifnottex
666
667 @node About This Guide
668 @unnumbered About This Guide
669
670 @noindent
671 @ifset vms
672 This guide describes the use of @value{EDITION},
673 a compiler and software development toolset for the full Ada
674 programming language, implemented on OpenVMS for HP's Alpha and
675 Integrity server (I64) platforms.
676 @end ifset
677 @ifclear vms
678 This guide describes the use of @value{EDITION},
679 a compiler and software development
680 toolset for the full Ada programming language.
681 @end ifclear
682 It documents the features of the compiler and tools, and explains
683 how to use them to build Ada applications.
684
685 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
686 Ada 83 compatibility mode.
687 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
688 but you can override with a compiler switch
689 (@pxref{Compiling Different Versions of Ada})
690 to explicitly specify the language version.
691 Throughout this manual, references to ``Ada'' without a year suffix
692 apply to both the Ada 95 and Ada 2005 versions of the language.
693
694
695 @ifclear FSFEDITION
696 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
697 ``GNAT'' in the remainder of this document.
698 @end ifclear
699
700
701
702
703 @menu
704 * What This Guide Contains::
705 * What You Should Know before Reading This Guide::
706 * Related Information::
707 * Conventions::
708 @end menu
709
710 @node What This Guide Contains
711 @unnumberedsec What This Guide Contains
712
713 @noindent
714 This guide contains the following chapters:
715 @itemize @bullet
716
717 @item
718 @ref{Getting Started with GNAT}, describes how to get started compiling
719 and running Ada programs with the GNAT Ada programming environment.
720 @item
721 @ref{The GNAT Compilation Model}, describes the compilation model used
722 by GNAT.
723
724 @item
725 @ref{Compiling Using gcc}, describes how to compile
726 Ada programs with @command{gcc}, the Ada compiler.
727
728 @item
729 @ref{Binding Using gnatbind}, describes how to
730 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
731 utility.
732
733 @item
734 @ref{Linking Using gnatlink},
735 describes @command{gnatlink}, a
736 program that provides for linking using the GNAT run-time library to
737 construct a program. @command{gnatlink} can also incorporate foreign language
738 object units into the executable.
739
740 @item
741 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
742 utility that automatically determines the set of sources
743 needed by an Ada compilation unit, and executes the necessary compilations
744 binding and link.
745
746 @item
747 @ref{Improving Performance}, shows various techniques for making your
748 Ada program run faster or take less space.
749 It discusses the effect of the compiler's optimization switch and
750 also describes the @command{gnatelim} tool and unused subprogram/data
751 elimination.
752
753 @item
754 @ref{Renaming Files Using gnatchop}, describes
755 @code{gnatchop}, a utility that allows you to preprocess a file that
756 contains Ada source code, and split it into one or more new files, one
757 for each compilation unit.
758
759 @item
760 @ref{Configuration Pragmas}, describes the configuration pragmas
761 handled by GNAT.
762
763 @item
764 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
765 shows how to override the default GNAT file naming conventions,
766 either for an individual unit or globally.
767
768 @item
769 @ref{GNAT Project Manager}, describes how to use project files
770 to organize large projects.
771
772 @item
773 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
774 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
775 way to navigate through sources.
776
777 @item
778 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
779 version of an Ada source file with control over casing, indentation,
780 comment placement, and other elements of program presentation style.
781
782 @item
783 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
784 metrics for an Ada source file, such as the number of types and subprograms,
785 and assorted complexity measures.
786
787 @item
788 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
789 file name krunching utility, used to handle shortened
790 file names on operating systems with a limit on the length of names.
791
792 @item
793 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
794 preprocessor utility that allows a single source file to be used to
795 generate multiple or parameterized source files by means of macro
796 substitution.
797
798 @ifset vms
799 @item
800 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
801 a tool for rebuilding the GNAT run time with user-supplied
802 configuration pragmas.
803 @end ifset
804
805 @item
806 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
807 utility that displays information about compiled units, including dependences
808 on the corresponding sources files, and consistency of compilations.
809
810 @item
811 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
812 to delete files that are produced by the compiler, binder and linker.
813
814 @ifclear vms
815 @item
816 @ref{GNAT and Libraries}, describes the process of creating and using
817 Libraries with GNAT. It also describes how to recompile the GNAT run-time
818 library.
819
820 @item
821 @ref{Using the GNU make Utility}, describes some techniques for using
822 the GNAT toolset in Makefiles.
823 @end ifclear
824
825 @item
826 @ref{Memory Management Issues}, describes some useful predefined storage pools
827 and in particular the GNAT Debug Pool facility, which helps detect incorrect
828 memory references.
829 @ifclear vms
830 It also describes @command{gnatmem}, a utility that monitors dynamic
831 allocation and deallocation and helps detect ``memory leaks''.
832 @end ifclear
833
834 @item
835 @ref{Stack Related Facilities}, describes some useful tools associated with
836 stack checking and analysis.
837
838 @item
839 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
840 a utility that checks Ada code against a set of rules.
841
842 @item
843 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
844 a utility that generates empty but compilable bodies for library units.
845
846 @item
847 @ref{Other Utility Programs}, discusses several other GNAT utilities,
848 including @code{gnathtml}.
849
850 @item
851 @ref{Running and Debugging Ada Programs}, describes how to run and debug
852 Ada programs.
853
854 @ifset vms
855 @item
856 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
857 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
858 developed by Digital Equipment Corporation and currently supported by HP.}
859 for OpenVMS Alpha. This product was formerly known as DEC Ada,
860 @cindex DEC Ada
861 and for
862 historical compatibility reasons, the relevant libraries still use the
863 DEC prefix.
864 @end ifset
865
866 @item
867 @ref{Platform-Specific Information for the Run-Time Libraries},
868 describes the various run-time
869 libraries supported by GNAT on various platforms and explains how to
870 choose a particular library.
871
872 @item
873 @ref{Example of Binder Output File}, shows the source code for the binder
874 output file for a sample program.
875
876 @item
877 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
878 you deal with elaboration order issues.
879
880 @item
881 @ref{Conditional Compilation}, describes how to model conditional compilation,
882 both with Ada in general and with GNAT facilities in particular.
883
884 @item
885 @ref{Inline Assembler}, shows how to use the inline assembly facility
886 in an Ada program.
887
888 @item
889 @ref{Compatibility and Porting Guide}, contains sections on compatibility
890 of GNAT with other Ada development environments (including Ada 83 systems),
891 to assist in porting code from those environments.
892
893 @ifset unw
894 @item
895 @ref{Microsoft Windows Topics}, presents information relevant to the
896 Microsoft Windows platform.
897 @end ifset
898 @end itemize
899
900 @c *************************************************
901 @node What You Should Know before Reading This Guide
902 @c *************************************************
903 @unnumberedsec What You Should Know before Reading This Guide
904
905 @cindex Ada 95 Language Reference Manual
906 @cindex Ada 2005 Language Reference Manual
907 @noindent
908 This guide assumes a basic familiarity with the Ada 95 language, as
909 described in the International Standard ANSI/ISO/IEC-8652:1995, January
910 1995.
911 It does not require knowledge of the new features introduced by Ada 2005,
912 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
913 and Amendment 1).
914 Both reference manuals are included in the GNAT documentation
915 package.
916
917 @node Related Information
918 @unnumberedsec Related Information
919
920 @noindent
921 For further information about related tools, refer to the following
922 documents:
923
924 @itemize @bullet
925 @item
926 @cite{GNAT Reference Manual}, which contains all reference
927 material for the GNAT implementation of Ada.
928
929 @ifset unw
930 @item
931 @cite{Using the GNAT Programming Studio}, which describes the GPS
932 Integrated Development Environment.
933
934 @item
935 @cite{GNAT Programming Studio Tutorial}, which introduces the
936 main GPS features through examples.
937 @end ifset
938
939 @item
940 @cite{Ada 95 Reference Manual}, which contains reference
941 material for the Ada 95 programming language.
942
943 @item
944 @cite{Ada 2005 Reference Manual}, which contains reference
945 material for the Ada 2005 programming language.
946
947 @item
948 @cite{Debugging with GDB}
949 @ifset vms
950 , located in the GNU:[DOCS] directory,
951 @end ifset
952 contains all details on the use of the GNU source-level debugger.
953
954 @item
955 @cite{GNU Emacs Manual}
956 @ifset vms
957 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
958 @end ifset
959 contains full information on the extensible editor and programming
960 environment Emacs.
961
962 @end itemize
963
964 @c **************
965 @node Conventions
966 @unnumberedsec Conventions
967 @cindex Conventions
968 @cindex Typographical conventions
969
970 @noindent
971 Following are examples of the typographical and graphic conventions used
972 in this guide:
973
974 @itemize @bullet
975 @item
976 @code{Functions}, @command{utility program names}, @code{standard names},
977 and @code{classes}.
978
979 @item
980 @option{Option flags}
981
982 @item
983 @file{File names}, @samp{button names}, and @samp{field names}.
984
985 @item
986 @code{Variables}, @env{environment variables}, and @var{metasyntactic
987 variables}.
988
989 @item
990 @emph{Emphasis}.
991
992 @item
993 [optional information or parameters]
994
995 @item
996 Examples are described by text
997 @smallexample
998 and then shown this way.
999 @end smallexample
1000 @end itemize
1001
1002 @noindent
1003 Commands that are entered by the user are preceded in this manual by the
1004 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1005 uses this sequence as a prompt, then the commands will appear exactly as
1006 you see them in the manual. If your system uses some other prompt, then
1007 the command will appear with the @code{$} replaced by whatever prompt
1008 character you are using.
1009
1010 @ifset unw
1011 Full file names are shown with the ``@code{/}'' character
1012 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1013 If you are using GNAT on a Windows platform, please note that
1014 the ``@code{\}'' character should be used instead.
1015 @end ifset
1016
1017 @c ****************************
1018 @node Getting Started with GNAT
1019 @chapter Getting Started with GNAT
1020
1021 @noindent
1022 This chapter describes some simple ways of using GNAT to build
1023 executable Ada programs.
1024 @ifset unw
1025 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1026 show how to use the command line environment.
1027 @ref{Introduction to GPS}, provides a brief
1028 introduction to the GNAT Programming Studio, a visually-oriented
1029 Integrated Development Environment for GNAT.
1030 GPS offers a graphical ``look and feel'', support for development in
1031 other programming languages, comprehensive browsing features, and
1032 many other capabilities.
1033 For information on GPS please refer to
1034 @cite{Using the GNAT Programming Studio}.
1035 @end ifset
1036
1037 @menu
1038 * Running GNAT::
1039 * Running a Simple Ada Program::
1040 * Running a Program with Multiple Units::
1041 * Using the gnatmake Utility::
1042 @ifset vms
1043 * Editing with Emacs::
1044 @end ifset
1045 @ifclear vms
1046 * Introduction to GPS::
1047 @end ifclear
1048 @end menu
1049
1050 @node Running GNAT
1051 @section Running GNAT
1052
1053 @noindent
1054 Three steps are needed to create an executable file from an Ada source
1055 file:
1056
1057 @enumerate
1058 @item
1059 The source file(s) must be compiled.
1060 @item
1061 The file(s) must be bound using the GNAT binder.
1062 @item
1063 All appropriate object files must be linked to produce an executable.
1064 @end enumerate
1065
1066 @noindent
1067 All three steps are most commonly handled by using the @command{gnatmake}
1068 utility program that, given the name of the main program, automatically
1069 performs the necessary compilation, binding and linking steps.
1070
1071 @node Running a Simple Ada Program
1072 @section Running a Simple Ada Program
1073
1074 @noindent
1075 Any text editor may be used to prepare an Ada program.
1076 (If @code{Emacs} is
1077 used, the optional Ada mode may be helpful in laying out the program.)
1078 The
1079 program text is a normal text file. We will assume in our initial
1080 example that you have used your editor to prepare the following
1081 standard format text file:
1082
1083 @smallexample @c ada
1084 @cartouche
1085 with Ada.Text_IO; use Ada.Text_IO;
1086 procedure Hello is
1087 begin
1088    Put_Line ("Hello WORLD!");
1089 end Hello;
1090 @end cartouche
1091 @end smallexample
1092
1093 @noindent
1094 This file should be named @file{hello.adb}.
1095 With the normal default file naming conventions, GNAT requires
1096 that each file
1097 contain a single compilation unit whose file name is the
1098 unit name,
1099 with periods replaced by hyphens; the
1100 extension is @file{ads} for a
1101 spec and @file{adb} for a body.
1102 You can override this default file naming convention by use of the
1103 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1104 Alternatively, if you want to rename your files according to this default
1105 convention, which is probably more convenient if you will be using GNAT
1106 for all your compilations, then the @code{gnatchop} utility
1107 can be used to generate correctly-named source files
1108 (@pxref{Renaming Files Using gnatchop}).
1109
1110 You can compile the program using the following command (@code{$} is used
1111 as the command prompt in the examples in this document):
1112
1113 @smallexample
1114 $ gcc -c hello.adb
1115 @end smallexample
1116
1117 @noindent
1118 @command{gcc} is the command used to run the compiler. This compiler is
1119 capable of compiling programs in several languages, including Ada and
1120 C. It assumes that you have given it an Ada program if the file extension is
1121 either @file{.ads} or @file{.adb}, and it will then call
1122 the GNAT compiler to compile the specified file.
1123
1124 @ifclear vms
1125 The @option{-c} switch is required. It tells @command{gcc} to only do a
1126 compilation. (For C programs, @command{gcc} can also do linking, but this
1127 capability is not used directly for Ada programs, so the @option{-c}
1128 switch must always be present.)
1129 @end ifclear
1130
1131 This compile command generates a file
1132 @file{hello.o}, which is the object
1133 file corresponding to your Ada program. It also generates
1134 an ``Ada Library Information'' file @file{hello.ali},
1135 which contains additional information used to check
1136 that an Ada program is consistent.
1137 To build an executable file,
1138 use @code{gnatbind} to bind the program
1139 and @command{gnatlink} to link it. The
1140 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1141 @file{ALI} file, but the default extension of @file{.ali} can
1142 be omitted. This means that in the most common case, the argument
1143 is simply the name of the main program:
1144
1145 @smallexample
1146 $ gnatbind hello
1147 $ gnatlink hello
1148 @end smallexample
1149
1150 @noindent
1151 A simpler method of carrying out these steps is to use
1152 @command{gnatmake},
1153 a master program that invokes all the required
1154 compilation, binding and linking tools in the correct order. In particular,
1155 @command{gnatmake} automatically recompiles any sources that have been
1156 modified since they were last compiled, or sources that depend
1157 on such modified sources, so that ``version skew'' is avoided.
1158 @cindex Version skew (avoided by @command{gnatmake})
1159
1160 @smallexample
1161 $ gnatmake hello.adb
1162 @end smallexample
1163
1164 @noindent
1165 The result is an executable program called @file{hello}, which can be
1166 run by entering:
1167
1168 @smallexample
1169 $ ^hello^RUN HELLO^
1170 @end smallexample
1171
1172 @noindent
1173 assuming that the current directory is on the search path
1174 for executable programs.
1175
1176 @noindent
1177 and, if all has gone well, you will see
1178
1179 @smallexample
1180 Hello WORLD!
1181 @end smallexample
1182
1183 @noindent
1184 appear in response to this command.
1185
1186 @c ****************************************
1187 @node Running a Program with Multiple Units
1188 @section Running a Program with Multiple Units
1189
1190 @noindent
1191 Consider a slightly more complicated example that has three files: a
1192 main program, and the spec and body of a package:
1193
1194 @smallexample @c ada
1195 @cartouche
1196 @group
1197 package Greetings is
1198    procedure Hello;
1199    procedure Goodbye;
1200 end Greetings;
1201
1202 with Ada.Text_IO; use Ada.Text_IO;
1203 package body Greetings is
1204    procedure Hello is
1205    begin
1206       Put_Line ("Hello WORLD!");
1207    end Hello;
1208
1209    procedure Goodbye is
1210    begin
1211       Put_Line ("Goodbye WORLD!");
1212    end Goodbye;
1213 end Greetings;
1214 @end group
1215
1216 @group
1217 with Greetings;
1218 procedure Gmain is
1219 begin
1220    Greetings.Hello;
1221    Greetings.Goodbye;
1222 end Gmain;
1223 @end group
1224 @end cartouche
1225 @end smallexample
1226
1227 @noindent
1228 Following the one-unit-per-file rule, place this program in the
1229 following three separate files:
1230
1231 @table @file
1232 @item greetings.ads
1233 spec of package @code{Greetings}
1234
1235 @item greetings.adb
1236 body of package @code{Greetings}
1237
1238 @item gmain.adb
1239 body of main program
1240 @end table
1241
1242 @noindent
1243 To build an executable version of
1244 this program, we could use four separate steps to compile, bind, and link
1245 the program, as follows:
1246
1247 @smallexample
1248 $ gcc -c gmain.adb
1249 $ gcc -c greetings.adb
1250 $ gnatbind gmain
1251 $ gnatlink gmain
1252 @end smallexample
1253
1254 @noindent
1255 Note that there is no required order of compilation when using GNAT.
1256 In particular it is perfectly fine to compile the main program first.
1257 Also, it is not necessary to compile package specs in the case where
1258 there is an accompanying body; you only need to compile the body. If you want
1259 to submit these files to the compiler for semantic checking and not code
1260 generation, then use the
1261 @option{-gnatc} switch:
1262
1263 @smallexample
1264 $ gcc -c greetings.ads -gnatc
1265 @end smallexample
1266
1267 @noindent
1268 Although the compilation can be done in separate steps as in the
1269 above example, in practice it is almost always more convenient
1270 to use the @command{gnatmake} tool. All you need to know in this case
1271 is the name of the main program's source file. The effect of the above four
1272 commands can be achieved with a single one:
1273
1274 @smallexample
1275 $ gnatmake gmain.adb
1276 @end smallexample
1277
1278 @noindent
1279 In the next section we discuss the advantages of using @command{gnatmake} in
1280 more detail.
1281
1282 @c *****************************
1283 @node Using the gnatmake Utility
1284 @section Using the @command{gnatmake} Utility
1285
1286 @noindent
1287 If you work on a program by compiling single components at a time using
1288 @command{gcc}, you typically keep track of the units you modify. In order to
1289 build a consistent system, you compile not only these units, but also any
1290 units that depend on the units you have modified.
1291 For example, in the preceding case,
1292 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1293 you edit @file{greetings.ads}, you must recompile both
1294 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1295 units that depend on @file{greetings.ads}.
1296
1297 @code{gnatbind} will warn you if you forget one of these compilation
1298 steps, so that it is impossible to generate an inconsistent program as a
1299 result of forgetting to do a compilation. Nevertheless it is tedious and
1300 error-prone to keep track of dependencies among units.
1301 One approach to handle the dependency-bookkeeping is to use a
1302 makefile. However, makefiles present maintenance problems of their own:
1303 if the dependencies change as you change the program, you must make
1304 sure that the makefile is kept up-to-date manually, which is also an
1305 error-prone process.
1306
1307 The @command{gnatmake} utility takes care of these details automatically.
1308 Invoke it using either one of the following forms:
1309
1310 @smallexample
1311 $ gnatmake gmain.adb
1312 $ gnatmake ^gmain^GMAIN^
1313 @end smallexample
1314
1315 @noindent
1316 The argument is the name of the file containing the main program;
1317 you may omit the extension. @command{gnatmake}
1318 examines the environment, automatically recompiles any files that need
1319 recompiling, and binds and links the resulting set of object files,
1320 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1321 In a large program, it
1322 can be extremely helpful to use @command{gnatmake}, because working out by hand
1323 what needs to be recompiled can be difficult.
1324
1325 Note that @command{gnatmake}
1326 takes into account all the Ada rules that
1327 establish dependencies among units. These include dependencies that result
1328 from inlining subprogram bodies, and from
1329 generic instantiation. Unlike some other
1330 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1331 found by the compiler on a previous compilation, which may possibly
1332 be wrong when sources change. @command{gnatmake} determines the exact set of
1333 dependencies from scratch each time it is run.
1334
1335 @ifset vms
1336 @node Editing with Emacs
1337 @section Editing with Emacs
1338 @cindex Emacs
1339
1340 @noindent
1341 Emacs is an extensible self-documenting text editor that is available in a
1342 separate VMSINSTAL kit.
1343
1344 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1345 click on the Emacs Help menu and run the Emacs Tutorial.
1346 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1347 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1348
1349 Documentation on Emacs and other tools is available in Emacs under the
1350 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1351 use the middle mouse button to select a topic (e.g.@: Emacs).
1352
1353 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1354 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1355 get to the Emacs manual.
1356 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1357 prompt.
1358
1359 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1360 which is sufficiently extensible to provide for a complete programming
1361 environment and shell for the sophisticated user.
1362 @end ifset
1363
1364 @ifclear vms
1365 @node Introduction to GPS
1366 @section Introduction to GPS
1367 @cindex GPS (GNAT Programming Studio)
1368 @cindex GNAT Programming Studio (GPS)
1369 @noindent
1370 Although the command line interface (@command{gnatmake}, etc.) alone
1371 is sufficient, a graphical Interactive Development
1372 Environment can make it easier for you to compose, navigate, and debug
1373 programs.  This section describes the main features of GPS
1374 (``GNAT Programming Studio''), the GNAT graphical IDE.
1375 You will see how to use GPS to build and debug an executable, and
1376 you will also learn some of the basics of the GNAT ``project'' facility.
1377
1378 GPS enables you to do much more than is presented here;
1379 e.g., you can produce a call graph, interface to a third-party
1380 Version Control System, and inspect the generated assembly language
1381 for a program.
1382 Indeed, GPS also supports languages other than Ada.
1383 Such additional information, and an explanation of all of the GPS menu
1384 items. may be found in the on-line help, which includes
1385 a user's guide and a tutorial (these are also accessible from the GNAT
1386 startup menu).
1387
1388 @menu
1389 * Building a New Program with GPS::
1390 * Simple Debugging with GPS::
1391 @end menu
1392
1393 @node Building a New Program with GPS
1394 @subsection Building a New Program with GPS
1395 @noindent
1396 GPS invokes the GNAT compilation tools using information
1397 contained in a @emph{project} (also known as a @emph{project file}):
1398 a collection of properties such
1399 as source directories, identities of main subprograms, tool switches, etc.,
1400 and their associated values.
1401 See @ref{GNAT Project Manager} for details.
1402 In order to run GPS, you will need to either create a new project
1403 or else open an existing one.
1404
1405 This section will explain how you can use GPS to create a project,
1406 to associate Ada source files with a project, and to build and run
1407 programs.
1408
1409 @enumerate
1410 @item @emph{Creating a project}
1411
1412 Invoke GPS, either from the command line or the platform's IDE.
1413 After it starts, GPS will display a ``Welcome'' screen with three
1414 radio buttons:
1415
1416 @itemize @bullet
1417 @item
1418 @code{Start with default project in directory}
1419
1420 @item
1421 @code{Create new project with wizard}
1422
1423 @item
1424 @code{Open existing project}
1425 @end itemize
1426
1427 @noindent
1428 Select @code{Create new project with wizard} and press @code{OK}.
1429 A new window will appear.  In the text box labeled with
1430 @code{Enter the name of the project to create}, type @file{sample}
1431 as the project name.
1432 In the next box, browse to choose the directory in which you
1433 would like to create the project file.
1434 After selecting an appropriate directory, press @code{Forward}.
1435
1436 A window will appear with the title
1437 @code{Version Control System Configuration}.
1438 Simply press @code{Forward}.
1439
1440 A window will appear with the title
1441 @code{Please select the source directories for this project}.
1442 The directory that you specified for the project file will be selected
1443 by default as the one to use for sources; simply press @code{Forward}.
1444
1445 A window will appear with the title
1446 @code{Please select the build directory for this project}.
1447 The directory that you specified for the project file will be selected
1448 by default for object files and executables;
1449 simply press @code{Forward}.
1450
1451 A window will appear with the title
1452 @code{Please select the main units for this project}.
1453 You will supply this information later, after creating the source file.
1454 Simply press @code{Forward} for now.
1455
1456 A window will appear with the title
1457 @code{Please select the switches to build the project}.
1458 Press @code{Apply}.  This will create a project file named
1459 @file{sample.prj} in the directory that you had specified.
1460
1461 @item @emph{Creating and saving the source file}
1462
1463 After you create the new project, a GPS window will appear, which is
1464 partitioned into two main sections:
1465
1466 @itemize @bullet
1467 @item
1468 A @emph{Workspace area}, initially greyed out, which you will use for
1469 creating and editing source files
1470
1471 @item
1472 Directly below, a @emph{Messages area}, which initially displays a
1473 ``Welcome'' message.
1474 (If the Messages area is not visible, drag its border upward to expand it.)
1475 @end itemize
1476
1477 @noindent
1478 Select @code{File} on the menu bar, and then the @code{New} command.
1479 The Workspace area will become white, and you can now
1480 enter the source program explicitly.
1481 Type the following text
1482
1483 @smallexample @c ada
1484 @group
1485 with Ada.Text_IO; use Ada.Text_IO;
1486 procedure Hello is
1487 begin
1488   Put_Line("Hello from GPS!");
1489 end Hello;
1490 @end group
1491 @end smallexample
1492
1493 @noindent
1494 Select @code{File}, then @code{Save As}, and enter the source file name
1495 @file{hello.adb}.
1496 The file will be saved in the same directory you specified as the
1497 location of the default project file.
1498
1499 @item @emph{Updating the project file}
1500
1501 You need to add the new source file to the project.
1502 To do this, select
1503 the @code{Project} menu and then @code{Edit project properties}.
1504 Click the @code{Main files} tab on the left, and then the
1505 @code{Add} button.
1506 Choose @file{hello.adb} from the list, and press @code{Open}.
1507 The project settings window will reflect this action.
1508 Click @code{OK}.
1509
1510 @item @emph{Building and running the program}
1511
1512 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1513 and select @file{hello.adb}.
1514 The Messages window will display the resulting invocations of @command{gcc},
1515 @command{gnatbind}, and @command{gnatlink}
1516 (reflecting the default switch settings from the
1517 project file that you created) and then a ``successful compilation/build''
1518 message.
1519
1520 To run the program, choose the @code{Build} menu, then @code{Run}, and
1521 select @command{hello}.
1522 An @emph{Arguments Selection} window will appear.
1523 There are no command line arguments, so just click @code{OK}.
1524
1525 The Messages window will now display the program's output (the string
1526 @code{Hello from GPS}), and at the bottom of the GPS window a status
1527 update is displayed (@code{Run: hello}).
1528 Close the GPS window (or select @code{File}, then @code{Exit}) to
1529 terminate this GPS session.
1530 @end enumerate
1531
1532 @node Simple Debugging with GPS
1533 @subsection Simple Debugging with GPS
1534 @noindent
1535 This section illustrates basic debugging techniques (setting breakpoints,
1536 examining/modifying variables, single stepping).
1537
1538 @enumerate
1539 @item @emph{Opening a project}
1540
1541 Start GPS and select @code{Open existing project}; browse to
1542 specify the project file @file{sample.prj} that you had created in the
1543 earlier example.
1544
1545 @item @emph{Creating a source file}
1546
1547 Select @code{File}, then @code{New}, and type in the following program:
1548
1549 @smallexample @c ada
1550 @group
1551 with Ada.Text_IO; use Ada.Text_IO;
1552 procedure Example is
1553    Line : String (1..80);
1554    N    : Natural;
1555 begin
1556    Put_Line("Type a line of text at each prompt; an empty line to exit");
1557    loop
1558       Put(": ");
1559       Get_Line (Line, N);
1560       Put_Line (Line (1..N) );
1561       exit when N=0;
1562    end loop;
1563 end Example;
1564 @end group
1565 @end smallexample
1566
1567 @noindent
1568 Select @code{File}, then @code{Save as}, and enter the file name
1569 @file{example.adb}.
1570
1571 @item @emph{Updating the project file}
1572
1573 Add @code{Example} as a new main unit for the project:
1574 @enumerate a
1575 @item
1576 Select @code{Project}, then @code{Edit Project Properties}.
1577
1578 @item
1579 Select the @code{Main files} tab, click @code{Add}, then
1580 select the file @file{example.adb} from the list, and
1581 click @code{Open}.
1582 You will see the file name appear in the list of main units
1583
1584 @item
1585 Click @code{OK}
1586 @end enumerate
1587
1588 @item @emph{Building/running the executable}
1589
1590 To build the executable
1591 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1592
1593 Run the program to see its effect (in the Messages area).
1594 Each line that you enter is displayed; an empty line will
1595 cause the loop to exit and the program to terminate.
1596
1597 @item @emph{Debugging the program}
1598
1599 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1600 which are required for debugging, are on by default when you create
1601 a new project.
1602 Thus unless you intentionally remove these settings, you will be able
1603 to debug any program that you develop using GPS.
1604
1605 @enumerate a
1606 @item @emph{Initializing}
1607
1608 Select @code{Debug}, then @code{Initialize}, then @file{example}
1609
1610 @item @emph{Setting a breakpoint}
1611
1612 After performing the initialization step, you will observe a small
1613 icon to the right of each line number.
1614 This serves as a toggle for breakpoints; clicking the icon will
1615 set a breakpoint at the corresponding line (the icon will change to
1616 a red circle with an ``x''), and clicking it again
1617 will remove the breakpoint / reset the icon.
1618
1619 For purposes of this example, set a breakpoint at line 10 (the
1620 statement @code{Put_Line@ (Line@ (1..N));}
1621
1622 @item @emph{Starting program execution}
1623
1624 Select @code{Debug}, then @code{Run}.  When the
1625 @code{Program Arguments} window appears, click @code{OK}.
1626 A console window will appear; enter some line of text,
1627 e.g.@: @code{abcde}, at the prompt.
1628 The program will pause execution when it gets to the
1629 breakpoint, and the corresponding line is highlighted.
1630
1631 @item @emph{Examining a variable}
1632
1633 Move the mouse over one of the occurrences of the variable @code{N}.
1634 You will see the value (5) displayed, in ``tool tip'' fashion.
1635 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1636 You will see information about @code{N} appear in the @code{Debugger Data}
1637 pane, showing the value as 5.
1638
1639 @item @emph{Assigning a new value to a variable}
1640
1641 Right click on the @code{N} in the @code{Debugger Data} pane, and
1642 select @code{Set value of N}.
1643 When the input window appears, enter the value @code{4} and click
1644 @code{OK}.
1645 This value does not automatically appear in the @code{Debugger Data}
1646 pane; to see it, right click again on the @code{N} in the
1647 @code{Debugger Data} pane and select @code{Update value}.
1648 The new value, 4, will appear in red.
1649
1650 @item @emph{Single stepping}
1651
1652 Select @code{Debug}, then @code{Next}.
1653 This will cause the next statement to be executed, in this case the
1654 call of @code{Put_Line} with the string slice.
1655 Notice in the console window that the displayed string is simply
1656 @code{abcd} and not @code{abcde} which you had entered.
1657 This is because the upper bound of the slice is now 4 rather than 5.
1658
1659 @item @emph{Removing a breakpoint}
1660
1661 Toggle the breakpoint icon at line 10.
1662
1663 @item @emph{Resuming execution from a breakpoint}
1664
1665 Select @code{Debug}, then @code{Continue}.
1666 The program will reach the next iteration of the loop, and
1667 wait for input after displaying the prompt.
1668 This time, just hit the @kbd{Enter} key.
1669 The value of @code{N} will be 0, and the program will terminate.
1670 The console window will disappear.
1671 @end enumerate
1672 @end enumerate
1673 @end ifclear
1674
1675 @node The GNAT Compilation Model
1676 @chapter The GNAT Compilation Model
1677 @cindex GNAT compilation model
1678 @cindex Compilation model
1679
1680 @menu
1681 * Source Representation::
1682 * Foreign Language Representation::
1683 * File Naming Rules::
1684 * Using Other File Names::
1685 * Alternative File Naming Schemes::
1686 * Generating Object Files::
1687 * Source Dependencies::
1688 * The Ada Library Information Files::
1689 * Binding an Ada Program::
1690 * Mixed Language Programming::
1691 @ifclear vms
1692 * Building Mixed Ada & C++ Programs::
1693 * Comparison between GNAT and C/C++ Compilation Models::
1694 @end ifclear
1695 * Comparison between GNAT and Conventional Ada Library Models::
1696 @ifset vms
1697 * Placement of temporary files::
1698 @end ifset
1699 @end menu
1700
1701 @noindent
1702 This chapter describes the compilation model used by GNAT. Although
1703 similar to that used by other languages, such as C and C++, this model
1704 is substantially different from the traditional Ada compilation models,
1705 which are based on a library. The model is initially described without
1706 reference to the library-based model. If you have not previously used an
1707 Ada compiler, you need only read the first part of this chapter. The
1708 last section describes and discusses the differences between the GNAT
1709 model and the traditional Ada compiler models. If you have used other
1710 Ada compilers, this section will help you to understand those
1711 differences, and the advantages of the GNAT model.
1712
1713 @node Source Representation
1714 @section Source Representation
1715 @cindex Latin-1
1716
1717 @noindent
1718 Ada source programs are represented in standard text files, using
1719 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1720 7-bit ASCII set, plus additional characters used for
1721 representing foreign languages (@pxref{Foreign Language Representation}
1722 for support of non-USA character sets). The format effector characters
1723 are represented using their standard ASCII encodings, as follows:
1724
1725 @table @code
1726 @item VT
1727 @findex VT
1728 Vertical tab, @code{16#0B#}
1729
1730 @item HT
1731 @findex HT
1732 Horizontal tab, @code{16#09#}
1733
1734 @item CR
1735 @findex CR
1736 Carriage return, @code{16#0D#}
1737
1738 @item LF
1739 @findex LF
1740 Line feed, @code{16#0A#}
1741
1742 @item FF
1743 @findex FF
1744 Form feed, @code{16#0C#}
1745 @end table
1746
1747 @noindent
1748 Source files are in standard text file format. In addition, GNAT will
1749 recognize a wide variety of stream formats, in which the end of
1750 physical lines is marked by any of the following sequences:
1751 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1752 in accommodating files that are imported from other operating systems.
1753
1754 @cindex End of source file
1755 @cindex Source file, end
1756 @findex SUB
1757 The end of a source file is normally represented by the physical end of
1758 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1759 recognized as signalling the end of the source file. Again, this is
1760 provided for compatibility with other operating systems where this
1761 code is used to represent the end of file.
1762
1763 Each file contains a single Ada compilation unit, including any pragmas
1764 associated with the unit. For example, this means you must place a
1765 package declaration (a package @dfn{spec}) and the corresponding body in
1766 separate files. An Ada @dfn{compilation} (which is a sequence of
1767 compilation units) is represented using a sequence of files. Similarly,
1768 you will place each subunit or child unit in a separate file.
1769
1770 @node Foreign Language Representation
1771 @section Foreign Language Representation
1772
1773 @noindent
1774 GNAT supports the standard character sets defined in Ada as well as
1775 several other non-standard character sets for use in localized versions
1776 of the compiler (@pxref{Character Set Control}).
1777 @menu
1778 * Latin-1::
1779 * Other 8-Bit Codes::
1780 * Wide Character Encodings::
1781 @end menu
1782
1783 @node Latin-1
1784 @subsection Latin-1
1785 @cindex Latin-1
1786
1787 @noindent
1788 The basic character set is Latin-1. This character set is defined by ISO
1789 standard 8859, part 1. The lower half (character codes @code{16#00#}
1790 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1791 is used to represent additional characters. These include extended letters
1792 used by European languages, such as French accents, the vowels with umlauts
1793 used in German, and the extra letter A-ring used in Swedish.
1794
1795 @findex Ada.Characters.Latin_1
1796 For a complete list of Latin-1 codes and their encodings, see the source
1797 file of library unit @code{Ada.Characters.Latin_1} in file
1798 @file{a-chlat1.ads}.
1799 You may use any of these extended characters freely in character or
1800 string literals. In addition, the extended characters that represent
1801 letters can be used in identifiers.
1802
1803 @node Other 8-Bit Codes
1804 @subsection Other 8-Bit Codes
1805
1806 @noindent
1807 GNAT also supports several other 8-bit coding schemes:
1808
1809 @table @asis
1810 @item ISO 8859-2 (Latin-2)
1811 @cindex Latin-2
1812 @cindex ISO 8859-2
1813 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1814 equivalence.
1815
1816 @item ISO 8859-3 (Latin-3)
1817 @cindex Latin-3
1818 @cindex ISO 8859-3
1819 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1820 equivalence.
1821
1822 @item ISO 8859-4 (Latin-4)
1823 @cindex Latin-4
1824 @cindex ISO 8859-4
1825 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1826 equivalence.
1827
1828 @item ISO 8859-5 (Cyrillic)
1829 @cindex ISO 8859-5
1830 @cindex Cyrillic
1831 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1832 lowercase equivalence.
1833
1834 @item ISO 8859-15 (Latin-9)
1835 @cindex ISO 8859-15
1836 @cindex Latin-9
1837 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1838 lowercase equivalence
1839
1840 @item IBM PC (code page 437)
1841 @cindex code page 437
1842 This code page is the normal default for PCs in the U.S. It corresponds
1843 to the original IBM PC character set. This set has some, but not all, of
1844 the extended Latin-1 letters, but these letters do not have the same
1845 encoding as Latin-1. In this mode, these letters are allowed in
1846 identifiers with uppercase and lowercase equivalence.
1847
1848 @item IBM PC (code page 850)
1849 @cindex code page 850
1850 This code page is a modification of 437 extended to include all the
1851 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1852 mode, all these letters are allowed in identifiers with uppercase and
1853 lowercase equivalence.
1854
1855 @item Full Upper 8-bit
1856 Any character in the range 80-FF allowed in identifiers, and all are
1857 considered distinct. In other words, there are no uppercase and lowercase
1858 equivalences in this range. This is useful in conjunction with
1859 certain encoding schemes used for some foreign character sets (e.g.,
1860 the typical method of representing Chinese characters on the PC).
1861
1862 @item No Upper-Half
1863 No upper-half characters in the range 80-FF are allowed in identifiers.
1864 This gives Ada 83 compatibility for identifier names.
1865 @end table
1866
1867 @noindent
1868 For precise data on the encodings permitted, and the uppercase and lowercase
1869 equivalences that are recognized, see the file @file{csets.adb} in
1870 the GNAT compiler sources. You will need to obtain a full source release
1871 of GNAT to obtain this file.
1872
1873 @node Wide Character Encodings
1874 @subsection Wide Character Encodings
1875
1876 @noindent
1877 GNAT allows wide character codes to appear in character and string
1878 literals, and also optionally in identifiers, by means of the following
1879 possible encoding schemes:
1880
1881 @table @asis
1882
1883 @item Hex Coding
1884 In this encoding, a wide character is represented by the following five
1885 character sequence:
1886
1887 @smallexample
1888 ESC a b c d
1889 @end smallexample
1890
1891 @noindent
1892 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1893 characters (using uppercase letters) of the wide character code. For
1894 example, ESC A345 is used to represent the wide character with code
1895 @code{16#A345#}.
1896 This scheme is compatible with use of the full Wide_Character set.
1897
1898 @item Upper-Half Coding
1899 @cindex Upper-Half Coding
1900 The wide character with encoding @code{16#abcd#} where the upper bit is on
1901 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1902 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1903 character, but is not required to be in the upper half. This method can
1904 be also used for shift-JIS or EUC, where the internal coding matches the
1905 external coding.
1906
1907 @item Shift JIS Coding
1908 @cindex Shift JIS Coding
1909 A wide character is represented by a two-character sequence,
1910 @code{16#ab#} and
1911 @code{16#cd#}, with the restrictions described for upper-half encoding as
1912 described above. The internal character code is the corresponding JIS
1913 character according to the standard algorithm for Shift-JIS
1914 conversion. Only characters defined in the JIS code set table can be
1915 used with this encoding method.
1916
1917 @item EUC Coding
1918 @cindex EUC Coding
1919 A wide character is represented by a two-character sequence
1920 @code{16#ab#} and
1921 @code{16#cd#}, with both characters being in the upper half. The internal
1922 character code is the corresponding JIS character according to the EUC
1923 encoding algorithm. Only characters defined in the JIS code set table
1924 can be used with this encoding method.
1925
1926 @item UTF-8 Coding
1927 A wide character is represented using
1928 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1929 10646-1/Am.2. Depending on the character value, the representation
1930 is a one, two, or three byte sequence:
1931 @smallexample
1932 @iftex
1933 @leftskip=.7cm
1934 @end iftex
1935 16#0000#-16#007f#: 2#0xxxxxxx#
1936 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1937 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1938
1939 @end smallexample
1940
1941 @noindent
1942 where the xxx bits correspond to the left-padded bits of the
1943 16-bit character value. Note that all lower half ASCII characters
1944 are represented as ASCII bytes and all upper half characters and
1945 other wide characters are represented as sequences of upper-half
1946 (The full UTF-8 scheme allows for encoding 31-bit characters as
1947 6-byte sequences, but in this implementation, all UTF-8 sequences
1948 of four or more bytes length will be treated as illegal).
1949 @item Brackets Coding
1950 In this encoding, a wide character is represented by the following eight
1951 character sequence:
1952
1953 @smallexample
1954 [ " a b c d " ]
1955 @end smallexample
1956
1957 @noindent
1958 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1959 characters (using uppercase letters) of the wide character code. For
1960 example, [``A345''] is used to represent the wide character with code
1961 @code{16#A345#}. It is also possible (though not required) to use the
1962 Brackets coding for upper half characters. For example, the code
1963 @code{16#A3#} can be represented as @code{[``A3'']}.
1964
1965 This scheme is compatible with use of the full Wide_Character set,
1966 and is also the method used for wide character encoding in the standard
1967 ACVC (Ada Compiler Validation Capability) test suite distributions.
1968
1969 @end table
1970
1971 @noindent
1972 Note: Some of these coding schemes do not permit the full use of the
1973 Ada character set. For example, neither Shift JIS, nor EUC allow the
1974 use of the upper half of the Latin-1 set.
1975
1976 @node File Naming Rules
1977 @section File Naming Rules
1978
1979 @noindent
1980 The default file name is determined by the name of the unit that the
1981 file contains. The name is formed by taking the full expanded name of
1982 the unit and replacing the separating dots with hyphens and using
1983 ^lowercase^uppercase^ for all letters.
1984
1985 An exception arises if the file name generated by the above rules starts
1986 with one of the characters
1987 @ifset vms
1988 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1989 @end ifset
1990 @ifclear vms
1991 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1992 @end ifclear
1993 and the second character is a
1994 minus. In this case, the character ^tilde^dollar sign^ is used in place
1995 of the minus. The reason for this special rule is to avoid clashes with
1996 the standard names for child units of the packages System, Ada,
1997 Interfaces, and GNAT, which use the prefixes
1998 @ifset vms
1999 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2000 @end ifset
2001 @ifclear vms
2002 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2003 @end ifclear
2004 respectively.
2005
2006 The file extension is @file{.ads} for a spec and
2007 @file{.adb} for a body. The following list shows some
2008 examples of these rules.
2009
2010 @table @file
2011 @item main.ads
2012 Main (spec)
2013 @item main.adb
2014 Main (body)
2015 @item arith_functions.ads
2016 Arith_Functions (package spec)
2017 @item arith_functions.adb
2018 Arith_Functions (package body)
2019 @item func-spec.ads
2020 Func.Spec (child package spec)
2021 @item func-spec.adb
2022 Func.Spec (child package body)
2023 @item main-sub.adb
2024 Sub (subunit of Main)
2025 @item ^a~bad.adb^A$BAD.ADB^
2026 A.Bad (child package body)
2027 @end table
2028
2029 @noindent
2030 Following these rules can result in excessively long
2031 file names if corresponding
2032 unit names are long (for example, if child units or subunits are
2033 heavily nested). An option is available to shorten such long file names
2034 (called file name ``krunching''). This may be particularly useful when
2035 programs being developed with GNAT are to be used on operating systems
2036 with limited file name lengths. @xref{Using gnatkr}.
2037
2038 Of course, no file shortening algorithm can guarantee uniqueness over
2039 all possible unit names; if file name krunching is used, it is your
2040 responsibility to ensure no name clashes occur. Alternatively you
2041 can specify the exact file names that you want used, as described
2042 in the next section. Finally, if your Ada programs are migrating from a
2043 compiler with a different naming convention, you can use the gnatchop
2044 utility to produce source files that follow the GNAT naming conventions.
2045 (For details @pxref{Renaming Files Using gnatchop}.)
2046
2047 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2048 systems, case is not significant. So for example on @code{Windows XP}
2049 if the canonical name is @code{main-sub.adb}, you can use the file name
2050 @code{Main-Sub.adb} instead. However, case is significant for other
2051 operating systems, so for example, if you want to use other than
2052 canonically cased file names on a Unix system, you need to follow
2053 the procedures described in the next section.
2054
2055 @node Using Other File Names
2056 @section Using Other File Names
2057 @cindex File names
2058
2059 @noindent
2060 In the previous section, we have described the default rules used by
2061 GNAT to determine the file name in which a given unit resides. It is
2062 often convenient to follow these default rules, and if you follow them,
2063 the compiler knows without being explicitly told where to find all
2064 the files it needs.
2065
2066 However, in some cases, particularly when a program is imported from
2067 another Ada compiler environment, it may be more convenient for the
2068 programmer to specify which file names contain which units. GNAT allows
2069 arbitrary file names to be used by means of the Source_File_Name pragma.
2070 The form of this pragma is as shown in the following examples:
2071 @cindex Source_File_Name pragma
2072
2073 @smallexample @c ada
2074 @cartouche
2075 pragma Source_File_Name (My_Utilities.Stacks,
2076   Spec_File_Name => "myutilst_a.ada");
2077 pragma Source_File_name (My_Utilities.Stacks,
2078   Body_File_Name => "myutilst.ada");
2079 @end cartouche
2080 @end smallexample
2081
2082 @noindent
2083 As shown in this example, the first argument for the pragma is the unit
2084 name (in this example a child unit). The second argument has the form
2085 of a named association. The identifier
2086 indicates whether the file name is for a spec or a body;
2087 the file name itself is given by a string literal.
2088
2089 The source file name pragma is a configuration pragma, which means that
2090 normally it will be placed in the @file{gnat.adc}
2091 file used to hold configuration
2092 pragmas that apply to a complete compilation environment.
2093 For more details on how the @file{gnat.adc} file is created and used
2094 see @ref{Handling of Configuration Pragmas}.
2095 @cindex @file{gnat.adc}
2096
2097 @ifclear vms
2098 GNAT allows completely arbitrary file names to be specified using the
2099 source file name pragma. However, if the file name specified has an
2100 extension other than @file{.ads} or @file{.adb} it is necessary to use
2101 a special syntax when compiling the file. The name in this case must be
2102 preceded by the special sequence @option{-x} followed by a space and the name
2103 of the language, here @code{ada}, as in:
2104
2105 @smallexample
2106 $ gcc -c -x ada peculiar_file_name.sim
2107 @end smallexample
2108 @end ifclear
2109
2110 @noindent
2111 @command{gnatmake} handles non-standard file names in the usual manner (the
2112 non-standard file name for the main program is simply used as the
2113 argument to gnatmake). Note that if the extension is also non-standard,
2114 then it must be included in the @command{gnatmake} command, it may not
2115 be omitted.
2116
2117 @node Alternative File Naming Schemes
2118 @section Alternative File Naming Schemes
2119 @cindex File naming schemes, alternative
2120 @cindex File names
2121
2122 In the previous section, we described the use of the @code{Source_File_Name}
2123 pragma to allow arbitrary names to be assigned to individual source files.
2124 However, this approach requires one pragma for each file, and especially in
2125 large systems can result in very long @file{gnat.adc} files, and also create
2126 a maintenance problem.
2127
2128 GNAT also provides a facility for specifying systematic file naming schemes
2129 other than the standard default naming scheme previously described. An
2130 alternative scheme for naming is specified by the use of
2131 @code{Source_File_Name} pragmas having the following format:
2132 @cindex Source_File_Name pragma
2133
2134 @smallexample @c ada
2135 pragma Source_File_Name (
2136    Spec_File_Name  => FILE_NAME_PATTERN
2137  [,Casing          => CASING_SPEC]
2138  [,Dot_Replacement => STRING_LITERAL]);
2139
2140 pragma Source_File_Name (
2141    Body_File_Name  => FILE_NAME_PATTERN
2142  [,Casing          => CASING_SPEC]
2143  [,Dot_Replacement => STRING_LITERAL]);
2144
2145 pragma Source_File_Name (
2146    Subunit_File_Name  => FILE_NAME_PATTERN
2147  [,Casing             => CASING_SPEC]
2148  [,Dot_Replacement    => STRING_LITERAL]);
2149
2150 FILE_NAME_PATTERN ::= STRING_LITERAL
2151 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2152 @end smallexample
2153
2154 @noindent
2155 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2156 It contains a single asterisk character, and the unit name is substituted
2157 systematically for this asterisk. The optional parameter
2158 @code{Casing} indicates
2159 whether the unit name is to be all upper-case letters, all lower-case letters,
2160 or mixed-case. If no
2161 @code{Casing} parameter is used, then the default is all
2162 ^lower-case^upper-case^.
2163
2164 The optional @code{Dot_Replacement} string is used to replace any periods
2165 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2166 argument is used then separating dots appear unchanged in the resulting
2167 file name.
2168 Although the above syntax indicates that the
2169 @code{Casing} argument must appear
2170 before the @code{Dot_Replacement} argument, but it
2171 is also permissible to write these arguments in the opposite order.
2172
2173 As indicated, it is possible to specify different naming schemes for
2174 bodies, specs, and subunits. Quite often the rule for subunits is the
2175 same as the rule for bodies, in which case, there is no need to give
2176 a separate @code{Subunit_File_Name} rule, and in this case the
2177 @code{Body_File_name} rule is used for subunits as well.
2178
2179 The separate rule for subunits can also be used to implement the rather
2180 unusual case of a compilation environment (e.g.@: a single directory) which
2181 contains a subunit and a child unit with the same unit name. Although
2182 both units cannot appear in the same partition, the Ada Reference Manual
2183 allows (but does not require) the possibility of the two units coexisting
2184 in the same environment.
2185
2186 The file name translation works in the following steps:
2187
2188 @itemize @bullet
2189
2190 @item
2191 If there is a specific @code{Source_File_Name} pragma for the given unit,
2192 then this is always used, and any general pattern rules are ignored.
2193
2194 @item
2195 If there is a pattern type @code{Source_File_Name} pragma that applies to
2196 the unit, then the resulting file name will be used if the file exists. If
2197 more than one pattern matches, the latest one will be tried first, and the
2198 first attempt resulting in a reference to a file that exists will be used.
2199
2200 @item
2201 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2202 for which the corresponding file exists, then the standard GNAT default
2203 naming rules are used.
2204
2205 @end itemize
2206
2207 @noindent
2208 As an example of the use of this mechanism, consider a commonly used scheme
2209 in which file names are all lower case, with separating periods copied
2210 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2211 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2212 two pragmas appear:
2213
2214 @smallexample @c ada
2215 pragma Source_File_Name
2216   (Spec_File_Name => "*.1.ada");
2217 pragma Source_File_Name
2218   (Body_File_Name => "*.2.ada");
2219 @end smallexample
2220
2221 @noindent
2222 The default GNAT scheme is actually implemented by providing the following
2223 default pragmas internally:
2224
2225 @smallexample @c ada
2226 pragma Source_File_Name
2227   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2228 pragma Source_File_Name
2229   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2230 @end smallexample
2231
2232 @noindent
2233 Our final example implements a scheme typically used with one of the
2234 Ada 83 compilers, where the separator character for subunits was ``__''
2235 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2236 by adding @file{.ADA}, and subunits by
2237 adding @file{.SEP}. All file names were
2238 upper case. Child units were not present of course since this was an
2239 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2240 the same double underscore separator for child units.
2241
2242 @smallexample @c ada
2243 pragma Source_File_Name
2244   (Spec_File_Name => "*_.ADA",
2245    Dot_Replacement => "__",
2246    Casing = Uppercase);
2247 pragma Source_File_Name
2248   (Body_File_Name => "*.ADA",
2249    Dot_Replacement => "__",
2250    Casing = Uppercase);
2251 pragma Source_File_Name
2252   (Subunit_File_Name => "*.SEP",
2253    Dot_Replacement => "__",
2254    Casing = Uppercase);
2255 @end smallexample
2256
2257 @node Generating Object Files
2258 @section Generating Object Files
2259
2260 @noindent
2261 An Ada program consists of a set of source files, and the first step in
2262 compiling the program is to generate the corresponding object files.
2263 These are generated by compiling a subset of these source files.
2264 The files you need to compile are the following:
2265
2266 @itemize @bullet
2267 @item
2268 If a package spec has no body, compile the package spec to produce the
2269 object file for the package.
2270
2271 @item
2272 If a package has both a spec and a body, compile the body to produce the
2273 object file for the package. The source file for the package spec need
2274 not be compiled in this case because there is only one object file, which
2275 contains the code for both the spec and body of the package.
2276
2277 @item
2278 For a subprogram, compile the subprogram body to produce the object file
2279 for the subprogram. The spec, if one is present, is as usual in a
2280 separate file, and need not be compiled.
2281
2282 @item
2283 @cindex Subunits
2284 In the case of subunits, only compile the parent unit. A single object
2285 file is generated for the entire subunit tree, which includes all the
2286 subunits.
2287
2288 @item
2289 Compile child units independently of their parent units
2290 (though, of course, the spec of all the ancestor unit must be present in order
2291 to compile a child unit).
2292
2293 @item
2294 @cindex Generics
2295 Compile generic units in the same manner as any other units. The object
2296 files in this case are small dummy files that contain at most the
2297 flag used for elaboration checking. This is because GNAT always handles generic
2298 instantiation by means of macro expansion. However, it is still necessary to
2299 compile generic units, for dependency checking and elaboration purposes.
2300 @end itemize
2301
2302 @noindent
2303 The preceding rules describe the set of files that must be compiled to
2304 generate the object files for a program. Each object file has the same
2305 name as the corresponding source file, except that the extension is
2306 @file{.o} as usual.
2307
2308 You may wish to compile other files for the purpose of checking their
2309 syntactic and semantic correctness. For example, in the case where a
2310 package has a separate spec and body, you would not normally compile the
2311 spec. However, it is convenient in practice to compile the spec to make
2312 sure it is error-free before compiling clients of this spec, because such
2313 compilations will fail if there is an error in the spec.
2314
2315 GNAT provides an option for compiling such files purely for the
2316 purposes of checking correctness; such compilations are not required as
2317 part of the process of building a program. To compile a file in this
2318 checking mode, use the @option{-gnatc} switch.
2319
2320 @node Source Dependencies
2321 @section Source Dependencies
2322
2323 @noindent
2324 A given object file clearly depends on the source file which is compiled
2325 to produce it. Here we are using @dfn{depends} in the sense of a typical
2326 @code{make} utility; in other words, an object file depends on a source
2327 file if changes to the source file require the object file to be
2328 recompiled.
2329 In addition to this basic dependency, a given object may depend on
2330 additional source files as follows:
2331
2332 @itemize @bullet
2333 @item
2334 If a file being compiled @code{with}'s a unit @var{X}, the object file
2335 depends on the file containing the spec of unit @var{X}. This includes
2336 files that are @code{with}'ed implicitly either because they are parents
2337 of @code{with}'ed child units or they are run-time units required by the
2338 language constructs used in a particular unit.
2339
2340 @item
2341 If a file being compiled instantiates a library level generic unit, the
2342 object file depends on both the spec and body files for this generic
2343 unit.
2344
2345 @item
2346 If a file being compiled instantiates a generic unit defined within a
2347 package, the object file depends on the body file for the package as
2348 well as the spec file.
2349
2350 @item
2351 @findex Inline
2352 @cindex @option{-gnatn} switch
2353 If a file being compiled contains a call to a subprogram for which
2354 pragma @code{Inline} applies and inlining is activated with the
2355 @option{-gnatn} switch, the object file depends on the file containing the
2356 body of this subprogram as well as on the file containing the spec. Note
2357 that for inlining to actually occur as a result of the use of this switch,
2358 it is necessary to compile in optimizing mode.
2359
2360 @cindex @option{-gnatN} switch
2361 The use of @option{-gnatN} activates a more extensive inlining optimization
2362 that is performed by the front end of the compiler. This inlining does
2363 not require that the code generation be optimized. Like @option{-gnatn},
2364 the use of this switch generates additional dependencies.
2365 Note that
2366 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2367 to specify both options.
2368
2369 @item
2370 If an object file @file{O} depends on the proper body of a subunit through
2371 inlining or instantiation, it depends on the parent unit of the subunit.
2372 This means that any modification of the parent unit or one of its subunits
2373 affects the compilation of @file{O}.
2374
2375 @item
2376 The object file for a parent unit depends on all its subunit body files.
2377
2378 @item
2379 The previous two rules meant that for purposes of computing dependencies and
2380 recompilation, a body and all its subunits are treated as an indivisible whole.
2381
2382 @noindent
2383 These rules are applied transitively: if unit @code{A} @code{with}'s
2384 unit @code{B}, whose elaboration calls an inlined procedure in package
2385 @code{C}, the object file for unit @code{A} will depend on the body of
2386 @code{C}, in file @file{c.adb}.
2387
2388 The set of dependent files described by these rules includes all the
2389 files on which the unit is semantically dependent, as dictated by the
2390 Ada language standard. However, it is a superset of what the
2391 standard describes, because it includes generic, inline, and subunit
2392 dependencies.
2393
2394 An object file must be recreated by recompiling the corresponding source
2395 file if any of the source files on which it depends are modified. For
2396 example, if the @code{make} utility is used to control compilation,
2397 the rule for an Ada object file must mention all the source files on
2398 which the object file depends, according to the above definition.
2399 The determination of the necessary
2400 recompilations is done automatically when one uses @command{gnatmake}.
2401 @end itemize
2402
2403 @node The Ada Library Information Files
2404 @section The Ada Library Information Files
2405 @cindex Ada Library Information files
2406 @cindex @file{ALI} files
2407
2408 @noindent
2409 Each compilation actually generates two output files. The first of these
2410 is the normal object file that has a @file{.o} extension. The second is a
2411 text file containing full dependency information. It has the same
2412 name as the source file, but an @file{.ali} extension.
2413 This file is known as the Ada Library Information (@file{ALI}) file.
2414 The following information is contained in the @file{ALI} file.
2415
2416 @itemize @bullet
2417 @item
2418 Version information (indicates which version of GNAT was used to compile
2419 the unit(s) in question)
2420
2421 @item
2422 Main program information (including priority and time slice settings,
2423 as well as the wide character encoding used during compilation).
2424
2425 @item
2426 List of arguments used in the @command{gcc} command for the compilation
2427
2428 @item
2429 Attributes of the unit, including configuration pragmas used, an indication
2430 of whether the compilation was successful, exception model used etc.
2431
2432 @item
2433 A list of relevant restrictions applying to the unit (used for consistency)
2434 checking.
2435
2436 @item
2437 Categorization information (e.g.@: use of pragma @code{Pure}).
2438
2439 @item
2440 Information on all @code{with}'ed units, including presence of
2441 @code{Elaborate} or @code{Elaborate_All} pragmas.
2442
2443 @item
2444 Information from any @code{Linker_Options} pragmas used in the unit
2445
2446 @item
2447 Information on the use of @code{Body_Version} or @code{Version}
2448 attributes in the unit.
2449
2450 @item
2451 Dependency information. This is a list of files, together with
2452 time stamp and checksum information. These are files on which
2453 the unit depends in the sense that recompilation is required
2454 if any of these units are modified.
2455
2456 @item
2457 Cross-reference data. Contains information on all entities referenced
2458 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2459 provide cross-reference information.
2460
2461 @end itemize
2462
2463 @noindent
2464 For a full detailed description of the format of the @file{ALI} file,
2465 see the source of the body of unit @code{Lib.Writ}, contained in file
2466 @file{lib-writ.adb} in the GNAT compiler sources.
2467
2468 @node Binding an Ada Program
2469 @section Binding an Ada Program
2470
2471 @noindent
2472 When using languages such as C and C++, once the source files have been
2473 compiled the only remaining step in building an executable program
2474 is linking the object modules together. This means that it is possible to
2475 link an inconsistent version of a program, in which two units have
2476 included different versions of the same header.
2477
2478 The rules of Ada do not permit such an inconsistent program to be built.
2479 For example, if two clients have different versions of the same package,
2480 it is illegal to build a program containing these two clients.
2481 These rules are enforced by the GNAT binder, which also determines an
2482 elaboration order consistent with the Ada rules.
2483
2484 The GNAT binder is run after all the object files for a program have
2485 been created. It is given the name of the main program unit, and from
2486 this it determines the set of units required by the program, by reading the
2487 corresponding ALI files. It generates error messages if the program is
2488 inconsistent or if no valid order of elaboration exists.
2489
2490 If no errors are detected, the binder produces a main program, in Ada by
2491 default, that contains calls to the elaboration procedures of those
2492 compilation unit that require them, followed by
2493 a call to the main program. This Ada program is compiled to generate the
2494 object file for the main program. The name of
2495 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2496 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2497 main program unit.
2498
2499 Finally, the linker is used to build the resulting executable program,
2500 using the object from the main program from the bind step as well as the
2501 object files for the Ada units of the program.
2502
2503 @node Mixed Language Programming
2504 @section Mixed Language Programming
2505 @cindex Mixed Language Programming
2506
2507 @noindent
2508 This section describes how to develop a mixed-language program,
2509 specifically one that comprises units in both Ada and C.
2510
2511 @menu
2512 * Interfacing to C::
2513 * Calling Conventions::
2514 @end menu
2515
2516 @node Interfacing to C
2517 @subsection Interfacing to C
2518 @noindent
2519 Interfacing Ada with a foreign language such as C involves using
2520 compiler directives to import and/or export entity definitions in each
2521 language---using @code{extern} statements in C, for instance, and the
2522 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2523 A full treatment of these topics is provided in Appendix B, section 1
2524 of the Ada Reference Manual.
2525
2526 There are two ways to build a program using GNAT that contains some Ada
2527 sources and some foreign language sources, depending on whether or not
2528 the main subprogram is written in Ada.  Here is a source example with
2529 the main subprogram in Ada:
2530
2531 @smallexample
2532 /* file1.c */
2533 #include <stdio.h>
2534
2535 void print_num (int num)
2536 @{
2537   printf ("num is %d.\n", num);
2538   return;
2539 @}
2540
2541 /* file2.c */
2542
2543 /* num_from_Ada is declared in my_main.adb */
2544 extern int num_from_Ada;
2545
2546 int get_num (void)
2547 @{
2548   return num_from_Ada;
2549 @}
2550 @end smallexample
2551
2552 @smallexample @c ada
2553 --  my_main.adb
2554 procedure My_Main is
2555
2556    --  Declare then export an Integer entity called num_from_Ada
2557    My_Num : Integer := 10;
2558    pragma Export (C, My_Num, "num_from_Ada");
2559
2560    --  Declare an Ada function spec for Get_Num, then use
2561    --  C function get_num for the implementation.
2562    function Get_Num return Integer;
2563    pragma Import (C, Get_Num, "get_num");
2564
2565    --  Declare an Ada procedure spec for Print_Num, then use
2566    --  C function print_num for the implementation.
2567    procedure Print_Num (Num : Integer);
2568    pragma Import (C, Print_Num, "print_num");
2569
2570 begin
2571    Print_Num (Get_Num);
2572 end My_Main;
2573 @end smallexample
2574
2575 @enumerate
2576 @item
2577 To build this example, first compile the foreign language files to
2578 generate object files:
2579 @smallexample
2580 ^gcc -c file1.c^gcc -c FILE1.C^
2581 ^gcc -c file2.c^gcc -c FILE2.C^
2582 @end smallexample
2583
2584 @item
2585 Then, compile the Ada units to produce a set of object files and ALI
2586 files:
2587 @smallexample
2588 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2589 @end smallexample
2590
2591 @item
2592 Run the Ada binder on the Ada main program:
2593 @smallexample
2594 gnatbind my_main.ali
2595 @end smallexample
2596
2597 @item
2598 Link the Ada main program, the Ada objects and the other language
2599 objects:
2600 @smallexample
2601 gnatlink my_main.ali file1.o file2.o
2602 @end smallexample
2603 @end enumerate
2604
2605 The last three steps can be grouped in a single command:
2606 @smallexample
2607 gnatmake my_main.adb -largs file1.o file2.o
2608 @end smallexample
2609
2610 @cindex Binder output file
2611 @noindent
2612 If the main program is in a language other than Ada, then you may have
2613 more than one entry point into the Ada subsystem. You must use a special
2614 binder option to generate callable routines that initialize and
2615 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2616 Calls to the initialization and finalization routines must be inserted
2617 in the main program, or some other appropriate point in the code. The
2618 call to initialize the Ada units must occur before the first Ada
2619 subprogram is called, and the call to finalize the Ada units must occur
2620 after the last Ada subprogram returns. The binder will place the
2621 initialization and finalization subprograms into the
2622 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2623 sources.  To illustrate, we have the following example:
2624
2625 @smallexample
2626 /* main.c */
2627 extern void adainit (void);
2628 extern void adafinal (void);
2629 extern int add (int, int);
2630 extern int sub (int, int);
2631
2632 int main (int argc, char *argv[])
2633 @{
2634   int a = 21, b = 7;
2635
2636   adainit();
2637
2638   /* Should print "21 + 7 = 28" */
2639   printf ("%d + %d = %d\n", a, b, add (a, b));
2640   /* Should print "21 - 7 = 14" */
2641   printf ("%d - %d = %d\n", a, b, sub (a, b));
2642
2643   adafinal();
2644 @}
2645 @end smallexample
2646
2647 @smallexample @c ada
2648 --  unit1.ads
2649 package Unit1 is
2650    function Add (A, B : Integer) return Integer;
2651    pragma Export (C, Add, "add");
2652 end Unit1;
2653
2654 --  unit1.adb
2655 package body Unit1 is
2656    function Add (A, B : Integer) return Integer is
2657    begin
2658       return A + B;
2659    end Add;
2660 end Unit1;
2661
2662 --  unit2.ads
2663 package Unit2 is
2664    function Sub (A, B : Integer) return Integer;
2665    pragma Export (C, Sub, "sub");
2666 end Unit2;
2667
2668 --  unit2.adb
2669 package body Unit2 is
2670    function Sub (A, B : Integer) return Integer is
2671    begin
2672       return A - B;
2673    end Sub;
2674 end Unit2;
2675 @end smallexample
2676
2677 @enumerate
2678 @item
2679 The build procedure for this application is similar to the last
2680 example's.  First, compile the foreign language files to generate object
2681 files:
2682 @smallexample
2683 ^gcc -c main.c^gcc -c main.c^
2684 @end smallexample
2685
2686 @item
2687 Next, compile the Ada units to produce a set of object files and ALI
2688 files:
2689 @smallexample
2690 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2691 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2692 @end smallexample
2693
2694 @item
2695 Run the Ada binder on every generated ALI file.  Make sure to use the
2696 @option{-n} option to specify a foreign main program:
2697 @smallexample
2698 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2699 @end smallexample
2700
2701 @item
2702 Link the Ada main program, the Ada objects and the foreign language
2703 objects. You need only list the last ALI file here:
2704 @smallexample
2705 gnatlink unit2.ali main.o -o exec_file
2706 @end smallexample
2707
2708 This procedure yields a binary executable called @file{exec_file}.
2709 @end enumerate
2710
2711 @noindent
2712 Depending on the circumstances (for example when your non-Ada main object
2713 does not provide symbol @code{main}), you may also need to instruct the
2714 GNAT linker not to include the standard startup objects by passing the
2715 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2716
2717 @node Calling Conventions
2718 @subsection Calling Conventions
2719 @cindex Foreign Languages
2720 @cindex Calling Conventions
2721 GNAT follows standard calling sequence conventions and will thus interface
2722 to any other language that also follows these conventions. The following
2723 Convention identifiers are recognized by GNAT:
2724
2725 @table @code
2726 @cindex Interfacing to Ada
2727 @cindex Other Ada compilers
2728 @cindex Convention Ada
2729 @item Ada
2730 This indicates that the standard Ada calling sequence will be
2731 used and all Ada data items may be passed without any limitations in the
2732 case where GNAT is used to generate both the caller and callee. It is also
2733 possible to mix GNAT generated code and code generated by another Ada
2734 compiler. In this case, the data types should be restricted to simple
2735 cases, including primitive types. Whether complex data types can be passed
2736 depends on the situation. Probably it is safe to pass simple arrays, such
2737 as arrays of integers or floats. Records may or may not work, depending
2738 on whether both compilers lay them out identically. Complex structures
2739 involving variant records, access parameters, tasks, or protected types,
2740 are unlikely to be able to be passed.
2741
2742 Note that in the case of GNAT running
2743 on a platform that supports HP Ada 83, a higher degree of compatibility
2744 can be guaranteed, and in particular records are layed out in an identical
2745 manner in the two compilers. Note also that if output from two different
2746 compilers is mixed, the program is responsible for dealing with elaboration
2747 issues. Probably the safest approach is to write the main program in the
2748 version of Ada other than GNAT, so that it takes care of its own elaboration
2749 requirements, and then call the GNAT-generated adainit procedure to ensure
2750 elaboration of the GNAT components. Consult the documentation of the other
2751 Ada compiler for further details on elaboration.
2752
2753 However, it is not possible to mix the tasking run time of GNAT and
2754 HP Ada 83, All the tasking operations must either be entirely within
2755 GNAT compiled sections of the program, or entirely within HP Ada 83
2756 compiled sections of the program.
2757
2758 @cindex Interfacing to Assembly
2759 @cindex Convention Assembler
2760 @item Assembler
2761 Specifies assembler as the convention. In practice this has the
2762 same effect as convention Ada (but is not equivalent in the sense of being
2763 considered the same convention).
2764
2765 @cindex Convention Asm
2766 @findex Asm
2767 @item Asm
2768 Equivalent to Assembler.
2769
2770 @cindex Interfacing to COBOL
2771 @cindex Convention COBOL
2772 @findex COBOL
2773 @item COBOL
2774 Data will be passed according to the conventions described
2775 in section B.4 of the Ada Reference Manual.
2776
2777 @findex C
2778 @cindex Interfacing to C
2779 @cindex Convention C
2780 @item C
2781 Data will be passed according to the conventions described
2782 in section B.3 of the Ada Reference Manual.
2783
2784 A note on interfacing to a C ``varargs'' function:
2785 @findex C varargs function
2786 @cindex Interfacing to C varargs function
2787 @cindex varargs function interfaces
2788
2789 @itemize @bullet
2790 @item
2791 In C, @code{varargs} allows a function to take a variable number of
2792 arguments. There is no direct equivalent in this to Ada. One
2793 approach that can be used is to create a C wrapper for each
2794 different profile and then interface to this C wrapper. For
2795 example, to print an @code{int} value using @code{printf},
2796 create a C function @code{printfi} that takes two arguments, a
2797 pointer to a string and an int, and calls @code{printf}.
2798 Then in the Ada program, use pragma @code{Import} to
2799 interface to @code{printfi}.
2800
2801 @item
2802 It may work on some platforms to directly interface to
2803 a @code{varargs} function by providing a specific Ada profile
2804 for a particular call. However, this does not work on
2805 all platforms, since there is no guarantee that the
2806 calling sequence for a two argument normal C function
2807 is the same as for calling a @code{varargs} C function with
2808 the same two arguments.
2809 @end itemize
2810
2811 @cindex Convention Default
2812 @findex Default
2813 @item Default
2814 Equivalent to C.
2815
2816 @cindex Convention External
2817 @findex External
2818 @item External
2819 Equivalent to C.
2820
2821 @ifclear vms
2822 @findex C++
2823 @cindex Interfacing to C++
2824 @cindex Convention C++
2825 @item C_Plus_Plus (or CPP)
2826 This stands for C++. For most purposes this is identical to C.
2827 See the separate description of the specialized GNAT pragmas relating to
2828 C++ interfacing for further details.
2829 @end ifclear
2830
2831 @findex Fortran
2832 @cindex Interfacing to Fortran
2833 @cindex Convention Fortran
2834 @item Fortran
2835 Data will be passed according to the conventions described
2836 in section B.5 of the Ada Reference Manual.
2837
2838 @item Intrinsic
2839 This applies to an intrinsic operation, as defined in the Ada
2840 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2841 this means that the body of the subprogram is provided by the compiler itself,
2842 usually by means of an efficient code sequence, and that the user does not
2843 supply an explicit body for it. In an application program, the pragma can
2844 only be applied to the following two sets of names, which the GNAT compiler
2845 recognizes.
2846
2847 @itemize @bullet
2848 @item
2849 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2850 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2851 two formal parameters. The
2852 first one must be a signed integer type or a modular type with a binary
2853 modulus, and the second parameter must be of type Natural.
2854 The return type must be the same as the type of the first argument. The size
2855 of this type can only be 8, 16, 32, or 64.
2856 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2857 The corresponding operator declaration must have parameters and result type
2858 that have the same root numeric type (for example, all three are long_float
2859 types). This simplifies the definition of operations that use type checking
2860 to perform dimensional checks:
2861
2862 @smallexample @c ada
2863 type Distance is new Long_Float;
2864 type Time     is new Long_Float;
2865 type Velocity is new Long_Float;
2866 function "/" (D : Distance; T : Time)
2867   return Velocity;
2868 pragma Import (Intrinsic, "/");
2869 @end smallexample
2870
2871 @noindent
2872 This common idiom is often programmed with a generic definition and an
2873 explicit body. The pragma makes it simpler to introduce such declarations.
2874 It incurs no overhead in compilation time or code size, because it is
2875 implemented as a single machine instruction.
2876 @end itemize
2877 @noindent
2878
2879 @ifset unw
2880 @findex Stdcall
2881 @cindex Convention Stdcall
2882 @item Stdcall
2883 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2884 and specifies that the @code{Stdcall} calling sequence will be used,
2885 as defined by the NT API. Nevertheless, to ease building
2886 cross-platform bindings this convention will be handled as a @code{C} calling
2887 convention on non-Windows platforms.
2888
2889 @findex DLL
2890 @cindex Convention DLL
2891 @item DLL
2892 This is equivalent to @code{Stdcall}.
2893
2894 @findex Win32
2895 @cindex Convention Win32
2896 @item Win32
2897 This is equivalent to @code{Stdcall}.
2898 @end ifset
2899
2900 @findex Stubbed
2901 @cindex Convention Stubbed
2902 @item Stubbed
2903 This is a special convention that indicates that the compiler
2904 should provide a stub body that raises @code{Program_Error}.
2905 @end table
2906
2907 @noindent
2908 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2909 that can be used to parametrize conventions and allow additional synonyms
2910 to be specified. For example if you have legacy code in which the convention
2911 identifier Fortran77 was used for Fortran, you can use the configuration
2912 pragma:
2913
2914 @smallexample @c ada
2915 pragma Convention_Identifier (Fortran77, Fortran);
2916 @end smallexample
2917
2918 @noindent
2919 And from now on the identifier Fortran77 may be used as a convention
2920 identifier (for example in an @code{Import} pragma) with the same
2921 meaning as Fortran.
2922
2923 @ifclear vms
2924 @node Building Mixed Ada & C++ Programs
2925 @section Building Mixed Ada and C++ Programs
2926
2927 @noindent
2928 A programmer inexperienced with mixed-language development may find that
2929 building an application containing both Ada and C++ code can be a
2930 challenge.  This section gives a few
2931 hints that should make this task easier. The first section addresses
2932 the differences between interfacing with C and interfacing with C++.
2933 The second section
2934 looks into the delicate problem of linking the complete application from
2935 its Ada and C++ parts. The last section gives some hints on how the GNAT
2936 run-time library can be adapted in order to allow inter-language dispatching
2937 with a new C++ compiler.
2938
2939 @menu
2940 * Interfacing to C++::
2941 * Linking a Mixed C++ & Ada Program::
2942 * A Simple Example::
2943 * Interfacing with C++ at the Class Level::
2944 @end menu
2945
2946 @node Interfacing to C++
2947 @subsection Interfacing to C++
2948
2949 @noindent
2950 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2951 generating code that is compatible with the G++ Application Binary
2952 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2953
2954 @noindent
2955 Interfacing can be done at 3 levels: simple data, subprograms, and
2956 classes. In the first two cases, GNAT offers a specific @code{Convention
2957 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2958 Usually, C++ mangles the names of subprograms, and currently, GNAT does
2959 not provide any help to solve the demangling problem. This problem can be
2960 addressed in two ways:
2961 @itemize @bullet
2962 @item
2963 by modifying the C++ code in order to force a C convention using
2964 the @code{extern "C"} syntax.
2965
2966 @item
2967 by figuring out the mangled name and use it as the Link_Name argument of
2968 the pragma import.
2969 @end itemize
2970
2971 @noindent
2972 Interfacing at the class level can be achieved by using the GNAT specific
2973 pragmas such as @code{CPP_Constructor}. See the GNAT Reference Manual for
2974 additional information.
2975
2976 @node Linking a Mixed C++ & Ada Program
2977 @subsection Linking a Mixed C++ & Ada Program
2978
2979 @noindent
2980 Usually the linker of the C++ development system must be used to link
2981 mixed applications because most C++ systems will resolve elaboration
2982 issues (such as calling constructors on global class instances)
2983 transparently during the link phase. GNAT has been adapted to ease the
2984 use of a foreign linker for the last phase. Three cases can be
2985 considered:
2986 @enumerate
2987
2988 @item
2989 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2990 The C++ linker can simply be called by using the C++ specific driver
2991 called @code{c++}. Note that this setup is not very common because it
2992 may involve recompiling the whole GCC tree from sources, which makes it
2993 harder to upgrade the compilation system for one language without
2994 destabilizing the other.
2995
2996 @smallexample
2997 $ c++ -c file1.C
2998 $ c++ -c file2.C
2999 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3000 @end smallexample
3001
3002 @item
3003 Using GNAT and G++ from two different GCC installations: If both
3004 compilers are on the @env{PATH}, the previous method may be used. It is
3005 important to note that environment variables such as
3006 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3007 @env{GCC_ROOT} will affect both compilers
3008 at the same time and may make one of the two compilers operate
3009 improperly if set during invocation of the wrong compiler.  It is also
3010 very important that the linker uses the proper @file{libgcc.a} GCC
3011 library -- that is, the one from the C++ compiler installation. The
3012 implicit link command as suggested in the @command{gnatmake} command
3013 from the former example can be replaced by an explicit link command with
3014 the full-verbosity option in order to verify which library is used:
3015 @smallexample
3016 $ gnatbind ada_unit
3017 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3018 @end smallexample
3019 If there is a problem due to interfering environment variables, it can
3020 be worked around by using an intermediate script. The following example
3021 shows the proper script to use when GNAT has not been installed at its
3022 default location and g++ has been installed at its default location:
3023
3024 @smallexample
3025 $ cat ./my_script
3026 #!/bin/sh
3027 unset BINUTILS_ROOT
3028 unset GCC_ROOT
3029 c++ $*
3030 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3031 @end smallexample
3032
3033 @item
3034 Using a non-GNU C++ compiler: The commands previously described can be
3035 used to insure that the C++ linker is used. Nonetheless, you need to add
3036 a few more parameters to the link command line, depending on the exception
3037 mechanism used.
3038
3039 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3040 to the libgcc libraries are required:
3041
3042 @smallexample
3043 $ cat ./my_script
3044 #!/bin/sh
3045 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3046 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3047 @end smallexample
3048
3049 Where CC is the name of the non-GNU C++ compiler.
3050
3051 If the @code{zero cost} exception mechanism is used, and the platform
3052 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3053 paths to more objects are required:
3054
3055 @smallexample
3056 $ cat ./my_script
3057 #!/bin/sh
3058 CC `gcc -print-file-name=crtbegin.o` $* \
3059 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3060 `gcc -print-file-name=crtend.o`
3061 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3062 @end smallexample
3063
3064 If the @code{zero cost} exception mechanism is used, and the platform
3065 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3066 Tru64 or AIX), the simple approach described above will not work and
3067 a pre-linking phase using GNAT will be necessary.
3068
3069 @end enumerate
3070
3071 @node A Simple Example
3072 @subsection  A Simple Example
3073 @noindent
3074 The following example, provided as part of the GNAT examples, shows how
3075 to achieve procedural interfacing between Ada and C++ in both
3076 directions. The C++ class A has two methods. The first method is exported
3077 to Ada by the means of an extern C wrapper function. The second method
3078 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3079 a limited record with a layout comparable to the C++ class. The Ada
3080 subprogram, in turn, calls the C++ method. So, starting from the C++
3081 main program, the process passes back and forth between the two
3082 languages.
3083
3084 @noindent
3085 Here are the compilation commands:
3086 @smallexample
3087 $ gnatmake -c simple_cpp_interface
3088 $ c++ -c cpp_main.C
3089 $ c++ -c ex7.C
3090 $ gnatbind -n simple_cpp_interface
3091 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3092       -lstdc++ ex7.o cpp_main.o
3093 @end smallexample
3094
3095 @noindent
3096 Here are the corresponding sources:
3097 @smallexample
3098
3099 //cpp_main.C
3100
3101 #include "ex7.h"
3102
3103 extern "C" @{
3104   void adainit (void);
3105   void adafinal (void);
3106   void method1 (A *t);
3107 @}
3108
3109 void method1 (A *t)
3110 @{
3111   t->method1 ();
3112 @}
3113
3114 int main ()
3115 @{
3116   A obj;
3117   adainit ();
3118   obj.method2 (3030);
3119   adafinal ();
3120 @}
3121
3122 //ex7.h
3123
3124 class Origin @{
3125  public:
3126   int o_value;
3127 @};
3128 class A : public Origin @{
3129  public:
3130   void method1 (void);
3131   void method2 (int v);
3132   A();
3133   int   a_value;
3134 @};
3135
3136 //ex7.C
3137
3138 #include "ex7.h"
3139 #include <stdio.h>
3140
3141 extern "C" @{ void ada_method2 (A *t, int v);@}
3142
3143 void A::method1 (void)
3144 @{
3145   a_value = 2020;
3146   printf ("in A::method1, a_value = %d \n",a_value);
3147
3148 @}
3149
3150 void A::method2 (int v)
3151 @{
3152    ada_method2 (this, v);
3153    printf ("in A::method2, a_value = %d \n",a_value);
3154
3155 @}
3156
3157 A::A(void)
3158 @{
3159    a_value = 1010;
3160   printf ("in A::A, a_value = %d \n",a_value);
3161 @}
3162 @end smallexample
3163
3164 @smallexample @c ada
3165 -- Ada sources
3166 package body Simple_Cpp_Interface is
3167
3168    procedure Ada_Method2 (This : in out A; V : Integer) is
3169    begin
3170       Method1 (This);
3171       This.A_Value := V;
3172    end Ada_Method2;
3173
3174 end Simple_Cpp_Interface;
3175
3176 with System;
3177 package Simple_Cpp_Interface is
3178    type A is limited
3179       record
3180          Vptr    : System.Address;
3181          O_Value : Integer;
3182          A_Value : Integer;
3183       end record;
3184    pragma Convention (C, A);
3185
3186    procedure Method1 (This : in out A);
3187    pragma Import (C, Method1);
3188
3189    procedure Ada_Method2 (This : in out A; V : Integer);
3190    pragma Export (C, Ada_Method2);
3191
3192 end Simple_Cpp_Interface;
3193 @end smallexample
3194
3195 @node Interfacing with C++ at the Class Level
3196 @subsection Interfacing with C++ at the Class Level
3197 @noindent
3198 In this section we demonstrate the GNAT features for interfacing with
3199 C++ by means of an example making use of Ada 2005 abstract interface
3200 types. This example consists of a classification of animals; classes
3201 have been used to model our main classification of animals, and
3202 interfaces provide support for the management of secondary
3203 classifications. We first demonstrate a case in which the types and
3204 constructors are defined on the C++ side and imported from the Ada
3205 side, and latter the reverse case.
3206
3207 The root of our derivation will be the @code{Animal} class, with a
3208 single private attribute (the @code{Age} of the animal) and two public
3209 primitives to set and get the value of this attribute.
3210
3211 @smallexample
3212 @b{class} Animal @{
3213  @b{public}:
3214    @b{virtual} void Set_Age (int New_Age);
3215    @b{virtual} int Age ();
3216  @b{private}:
3217    int Age_Count;
3218 @};
3219 @end smallexample
3220
3221 Abstract interface types are defined in C++ by means of classes with pure
3222 virtual functions and no data members. In our example we will use two
3223 interfaces that provide support for the common management of @code{Carnivore}
3224 and @code{Domestic} animals:
3225
3226 @smallexample
3227 @b{class} Carnivore @{
3228 @b{public}:
3229    @b{virtual} int Number_Of_Teeth () = 0;
3230 @};
3231
3232 @b{class} Domestic @{
3233 @b{public}:
3234    @b{virtual void} Set_Owner (char* Name) = 0;
3235 @};
3236 @end smallexample
3237
3238 Using these declarations, we can now say that a @code{Dog} is an animal that is
3239 both Carnivore and Domestic, that is:
3240
3241 @smallexample
3242 @b{class} Dog : Animal, Carnivore, Domestic @{
3243  @b{public}:
3244    @b{virtual} int  Number_Of_Teeth ();
3245    @b{virtual} void Set_Owner (char* Name);
3246
3247    Dog(); // Constructor
3248  @b{private}:
3249    int  Tooth_Count;
3250    char *Owner;
3251 @};
3252 @end smallexample
3253
3254 In the following examples we will assume that the previous declarations are
3255 located in a file named @code{animals.h}. The following package demonstrates
3256 how to import these C++ declarations from the Ada side:
3257
3258 @smallexample @c ada
3259 with Interfaces.C.Strings; use Interfaces.C.Strings;
3260 package Animals is
3261   type Carnivore is interface;
3262   pragma Convention (C_Plus_Plus, Carnivore);
3263   function Number_Of_Teeth (X : Carnivore)
3264      return Natural is abstract;
3265
3266   type Domestic is interface;
3267   pragma Convention (C_Plus_Plus, Set_Owner);
3268   procedure Set_Owner
3269     (X    : in out Domestic;
3270      Name : Chars_Ptr) is abstract;
3271
3272   type Animal is tagged record
3273     Age : Natural := 0;
3274   end record;
3275   pragma Import (C_Plus_Plus, Animal);
3276
3277   procedure Set_Age (X : in out Animal; Age : Integer);
3278   pragma Import (C_Plus_Plus, Set_Age);
3279
3280   function Age (X : Animal) return Integer;
3281   pragma Import (C_Plus_Plus, Age);
3282
3283   type Dog is new Animal and Carnivore and Domestic with record
3284     Tooth_Count : Natural;
3285     Owner       : String (1 .. 30);
3286   end record;
3287   pragma Import (C_Plus_Plus, Dog);
3288
3289   function Number_Of_Teeth (A : Dog) return Integer;
3290   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3291
3292   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3293   pragma Import (C_Plus_Plus, Set_Owner);
3294
3295   function New_Dog return Dog'Class;
3296   pragma CPP_Constructor (New_Dog);
3297   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3298 end Animals;
3299 @end smallexample
3300
3301 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3302 interfacing with these C++ classes is easy. The only requirement is that all
3303 the primitives and components must be declared exactly in the same order in
3304 the two languages.
3305
3306 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3307 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3308 the arguments to the called primitives will be the same as for C++. For the
3309 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3310 to indicate that they have been defined on the C++ side; this is required
3311 because the dispatch table associated with these tagged types will be built
3312 in the C++ side and therefore will not contain the predefined Ada primitives
3313 which Ada would otherwise expect.
3314
3315 As the reader can see there is no need to indicate the C++ mangled names
3316 associated with each subprogram because it is assumed that all the calls to
3317 these primitives will be dispatching calls. The only exception is the
3318 constructor, which must be registered with the compiler by means of
3319 @code{pragma CPP_Constructor} and needs to provide its associated C++
3320 mangled name because the Ada compiler generates direct calls to it.
3321
3322 With the above packages we can now declare objects of type Dog on the Ada side
3323 and dispatch calls to the corresponding subprograms on the C++ side. We can
3324 also extend the tagged type Dog with further fields and primitives, and
3325 override some of its C++ primitives on the Ada side. For example, here we have
3326 a type derivation defined on the Ada side that inherits all the dispatching
3327 primitives of the ancestor from the C++ side.
3328
3329 @smallexample
3330 @b{with} Animals; @b{use} Animals;
3331 @b{package} Vaccinated_Animals @b{is}
3332   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3333   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3334 @b{end} Vaccinated_Animals;
3335 @end smallexample
3336
3337 It is important to note that, because of the ABI compatibility, the programmer
3338 does not need to add any further information to indicate either the object
3339 layout or the dispatch table entry associated with each dispatching operation.
3340
3341 Now let us define all the types and constructors on the Ada side and export
3342 them to C++, using the same hierarchy of our previous example:
3343
3344 @smallexample @c ada
3345 with Interfaces.C.Strings;
3346 use Interfaces.C.Strings;
3347 package Animals is
3348   type Carnivore is interface;
3349   pragma Convention (C_Plus_Plus, Carnivore);
3350   function Number_Of_Teeth (X : Carnivore)
3351      return Natural is abstract;
3352
3353   type Domestic is interface;
3354   pragma Convention (C_Plus_Plus, Set_Owner);
3355   procedure Set_Owner
3356     (X    : in out Domestic;
3357      Name : Chars_Ptr) is abstract;
3358
3359   type Animal is tagged record
3360     Age : Natural := 0;
3361   end record;
3362   pragma Convention (C_Plus_Plus, Animal);
3363
3364   procedure Set_Age (X : in out Animal; Age : Integer);
3365   pragma Export (C_Plus_Plus, Set_Age);
3366
3367   function Age (X : Animal) return Integer;
3368   pragma Export (C_Plus_Plus, Age);
3369
3370   type Dog is new Animal and Carnivore and Domestic with record
3371     Tooth_Count : Natural;
3372     Owner       : String (1 .. 30);
3373   end record;
3374   pragma Convention (C_Plus_Plus, Dog);
3375
3376   function Number_Of_Teeth (A : Dog) return Integer;
3377   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3378
3379   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3380   pragma Export (C_Plus_Plus, Set_Owner);
3381
3382   function New_Dog return Dog'Class;
3383   pragma Export (C_Plus_Plus, New_Dog);
3384 end Animals;
3385 @end smallexample
3386
3387 Compared with our previous example the only difference is the use of
3388 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3389 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3390 nothing else to be done; as explained above, the only requirement is that all
3391 the primitives and components are declared in exactly the same order.
3392
3393 For completeness, let us see a brief C++ main program that uses the
3394 declarations available in @code{animals.h} (presented in our first example) to
3395 import and use the declarations from the Ada side, properly initializing and
3396 finalizing the Ada run-time system along the way:
3397
3398 @smallexample
3399 @b{#include} "animals.h"
3400 @b{#include} <iostream>
3401 @b{using namespace} std;
3402
3403 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3404 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3405 void Check_Animal (Animal *obj)       @{@dots{}@}
3406 void Check_Dog (Dog *obj)             @{@dots{}@}
3407
3408 @b{extern} "C" @{
3409   void adainit (void);
3410   void adafinal (void);
3411   Dog* new_dog ();
3412 @}
3413
3414 void test ()
3415 @{
3416   Dog *obj = new_dog();  // Ada constructor
3417   Check_Carnivore (obj); // Check secondary DT
3418   Check_Domestic (obj);  // Check secondary DT
3419   Check_Animal (obj);    // Check primary DT
3420   Check_Dog (obj);       // Check primary DT
3421 @}
3422
3423 int main ()
3424 @{
3425   adainit ();  test();  adafinal ();
3426   return 0;
3427 @}
3428 @end smallexample
3429
3430 @node Comparison between GNAT and C/C++ Compilation Models
3431 @section Comparison between GNAT and C/C++ Compilation Models
3432
3433 @noindent
3434 The GNAT model of compilation is close to the C and C++ models. You can
3435 think of Ada specs as corresponding to header files in C. As in C, you
3436 don't need to compile specs; they are compiled when they are used. The
3437 Ada @code{with} is similar in effect to the @code{#include} of a C
3438 header.
3439
3440 One notable difference is that, in Ada, you may compile specs separately
3441 to check them for semantic and syntactic accuracy. This is not always
3442 possible with C headers because they are fragments of programs that have
3443 less specific syntactic or semantic rules.
3444
3445 The other major difference is the requirement for running the binder,
3446 which performs two important functions. First, it checks for
3447 consistency. In C or C++, the only defense against assembling
3448 inconsistent programs lies outside the compiler, in a makefile, for
3449 example. The binder satisfies the Ada requirement that it be impossible
3450 to construct an inconsistent program when the compiler is used in normal
3451 mode.
3452
3453 @cindex Elaboration order control
3454 The other important function of the binder is to deal with elaboration
3455 issues. There are also elaboration issues in C++ that are handled
3456 automatically. This automatic handling has the advantage of being
3457 simpler to use, but the C++ programmer has no control over elaboration.
3458 Where @code{gnatbind} might complain there was no valid order of
3459 elaboration, a C++ compiler would simply construct a program that
3460 malfunctioned at run time.
3461 @end ifclear
3462
3463 @node Comparison between GNAT and Conventional Ada Library Models
3464 @section Comparison between GNAT and Conventional Ada Library Models
3465
3466 @noindent
3467 This section is intended for Ada programmers who have
3468 used an Ada compiler implementing the traditional Ada library
3469 model, as described in the Ada Reference Manual.
3470
3471 @cindex GNAT library
3472 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3473 source files themselves acts as the library. Compiling Ada programs does
3474 not generate any centralized information, but rather an object file and
3475 a ALI file, which are of interest only to the binder and linker.
3476 In a traditional system, the compiler reads information not only from
3477 the source file being compiled, but also from the centralized library.
3478 This means that the effect of a compilation depends on what has been
3479 previously compiled. In particular:
3480
3481 @itemize @bullet
3482 @item
3483 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3484 to the version of the unit most recently compiled into the library.
3485
3486 @item
3487 Inlining is effective only if the necessary body has already been
3488 compiled into the library.
3489
3490 @item
3491 Compiling a unit may obsolete other units in the library.
3492 @end itemize
3493
3494 @noindent
3495 In GNAT, compiling one unit never affects the compilation of any other
3496 units because the compiler reads only source files. Only changes to source
3497 files can affect the results of a compilation. In particular:
3498
3499 @itemize @bullet
3500 @item
3501 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3502 to the source version of the unit that is currently accessible to the
3503 compiler.
3504
3505 @item
3506 @cindex Inlining
3507 Inlining requires the appropriate source files for the package or
3508 subprogram bodies to be available to the compiler. Inlining is always
3509 effective, independent of the order in which units are complied.
3510
3511 @item
3512 Compiling a unit never affects any other compilations. The editing of
3513 sources may cause previous compilations to be out of date if they
3514 depended on the source file being modified.
3515 @end itemize
3516
3517 @noindent
3518 The most important result of these differences is that order of compilation
3519 is never significant in GNAT. There is no situation in which one is
3520 required to do one compilation before another. What shows up as order of
3521 compilation requirements in the traditional Ada library becomes, in
3522 GNAT, simple source dependencies; in other words, there is only a set
3523 of rules saying what source files must be present when a file is
3524 compiled.
3525
3526 @ifset vms
3527 @node Placement of temporary files
3528 @section Placement of temporary files
3529 @cindex Temporary files (user control over placement)
3530
3531 @noindent
3532 GNAT creates temporary files in the directory designated by the environment
3533 variable @env{TMPDIR}.
3534 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3535 for detailed information on how environment variables are resolved.
3536 For most users the easiest way to make use of this feature is to simply
3537 define @env{TMPDIR} as a job level logical name).
3538 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3539 for compiler temporary files, then you can include something like the
3540 following command in your @file{LOGIN.COM} file:
3541
3542 @smallexample
3543 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3544 @end smallexample
3545
3546 @noindent
3547 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3548 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3549 designated by @env{TEMP}.
3550 If none of these environment variables are defined then GNAT uses the
3551 directory designated by the logical name @code{SYS$SCRATCH:}
3552 (by default the user's home directory). If all else fails
3553 GNAT uses the current directory for temporary files.
3554 @end ifset
3555
3556 @c *************************
3557 @node Compiling Using gcc
3558 @chapter Compiling Using @command{gcc}
3559
3560 @noindent
3561 This chapter discusses how to compile Ada programs using the @command{gcc}
3562 command. It also describes the set of switches
3563 that can be used to control the behavior of the compiler.
3564 @menu
3565 * Compiling Programs::
3566 * Switches for gcc::
3567 * Search Paths and the Run-Time Library (RTL)::
3568 * Order of Compilation Issues::
3569 * Examples::
3570 @end menu
3571
3572 @node Compiling Programs
3573 @section Compiling Programs
3574
3575 @noindent
3576 The first step in creating an executable program is to compile the units
3577 of the program using the @command{gcc} command. You must compile the
3578 following files:
3579
3580 @itemize @bullet
3581 @item
3582 the body file (@file{.adb}) for a library level subprogram or generic
3583 subprogram
3584
3585 @item
3586 the spec file (@file{.ads}) for a library level package or generic
3587 package that has no body
3588
3589 @item
3590 the body file (@file{.adb}) for a library level package
3591 or generic package that has a body
3592
3593 @end itemize
3594
3595 @noindent
3596 You need @emph{not} compile the following files
3597
3598 @itemize @bullet
3599
3600 @item
3601 the spec of a library unit which has a body
3602
3603 @item
3604 subunits
3605 @end itemize
3606
3607 @noindent
3608 because they are compiled as part of compiling related units. GNAT
3609 package specs
3610 when the corresponding body is compiled, and subunits when the parent is
3611 compiled.
3612
3613 @cindex cannot generate code
3614 If you attempt to compile any of these files, you will get one of the
3615 following error messages (where @var{fff} is the name of the file you compiled):
3616
3617 @smallexample
3618 cannot generate code for file @var{fff} (package spec)
3619 to check package spec, use -gnatc
3620
3621 cannot generate code for file @var{fff} (missing subunits)
3622 to check parent unit, use -gnatc
3623
3624 cannot generate code for file @var{fff} (subprogram spec)
3625 to check subprogram spec, use -gnatc
3626
3627 cannot generate code for file @var{fff} (subunit)
3628 to check subunit, use -gnatc
3629 @end smallexample
3630
3631 @noindent
3632 As indicated by the above error messages, if you want to submit
3633 one of these files to the compiler to check for correct semantics
3634 without generating code, then use the @option{-gnatc} switch.
3635
3636 The basic command for compiling a file containing an Ada unit is
3637
3638 @smallexample
3639 $ gcc -c [@var{switches}] @file{file name}
3640 @end smallexample
3641
3642 @noindent
3643 where @var{file name} is the name of the Ada file (usually
3644 having an extension
3645 @file{.ads} for a spec or @file{.adb} for a body).
3646 @ifclear vms
3647 You specify the
3648 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3649 @end ifclear
3650 The result of a successful compilation is an object file, which has the
3651 same name as the source file but an extension of @file{.o} and an Ada
3652 Library Information (ALI) file, which also has the same name as the
3653 source file, but with @file{.ali} as the extension. GNAT creates these
3654 two output files in the current directory, but you may specify a source
3655 file in any directory using an absolute or relative path specification
3656 containing the directory information.
3657
3658 @findex gnat1
3659 @command{gcc} is actually a driver program that looks at the extensions of
3660 the file arguments and loads the appropriate compiler. For example, the
3661 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3662 These programs are in directories known to the driver program (in some
3663 configurations via environment variables you set), but need not be in
3664 your path. The @command{gcc} driver also calls the assembler and any other
3665 utilities needed to complete the generation of the required object
3666 files.
3667
3668 It is possible to supply several file names on the same @command{gcc}
3669 command. This causes @command{gcc} to call the appropriate compiler for
3670 each file. For example, the following command lists three separate
3671 files to be compiled:
3672
3673 @smallexample
3674 $ gcc -c x.adb y.adb z.c
3675 @end smallexample
3676
3677 @noindent
3678 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3679 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3680 The compiler generates three object files @file{x.o}, @file{y.o} and
3681 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3682 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3683 @ifclear vms
3684 except for
3685 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3686 @end ifclear
3687
3688 @node Switches for gcc
3689 @section Switches for @command{gcc}
3690
3691 @noindent
3692 The @command{gcc} command accepts switches that control the
3693 compilation process. These switches are fully described in this section.
3694 First we briefly list all the switches, in alphabetical order, then we
3695 describe the switches in more detail in functionally grouped sections.
3696
3697 More switches exist for GCC than those documented here, especially
3698 for specific targets. However, their use is not recommended as
3699 they may change code generation in ways that are incompatible with
3700 the Ada run-time library, or can cause inconsistencies between
3701 compilation units.
3702
3703 @menu
3704 * Output and Error Message Control::
3705 * Warning Message Control::
3706 * Debugging and Assertion Control::
3707 * Validity Checking::
3708 * Style Checking::
3709 * Run-Time Checks::
3710 * Using gcc for Syntax Checking::
3711 * Using gcc for Semantic Checking::
3712 * Compiling Different Versions of Ada::
3713 * Character Set Control::
3714 * File Naming Control::
3715 * Subprogram Inlining Control::
3716 * Auxiliary Output Control::
3717 * Debugging Control::
3718 * Exception Handling Control::
3719 * Units to Sources Mapping Files::
3720 * Integrated Preprocessing::
3721 * Code Generation Control::
3722 @ifset vms
3723 * Return Codes::
3724 @end ifset
3725 @end menu
3726
3727 @table @option
3728 @c !sort!
3729 @ifclear vms
3730 @cindex @option{-b} (@command{gcc})
3731 @item -b @var{target}
3732 Compile your program to run on @var{target}, which is the name of a
3733 system configuration. You must have a GNAT cross-compiler built if
3734 @var{target} is not the same as your host system.
3735
3736 @item -B@var{dir}
3737 @cindex @option{-B} (@command{gcc})
3738 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3739 from @var{dir} instead of the default location. Only use this switch
3740 when multiple versions of the GNAT compiler are available. See the
3741 @command{gcc} manual page for further details. You would normally use the
3742 @option{-b} or @option{-V} switch instead.
3743
3744 @item -c
3745 @cindex @option{-c} (@command{gcc})
3746 Compile. Always use this switch when compiling Ada programs.
3747
3748 Note: for some other languages when using @command{gcc}, notably in
3749 the case of C and C++, it is possible to use
3750 use @command{gcc} without a @option{-c} switch to
3751 compile and link in one step. In the case of GNAT, you
3752 cannot use this approach, because the binder must be run
3753 and @command{gcc} cannot be used to run the GNAT binder.
3754 @end ifclear
3755
3756 @item -fno-inline
3757 @cindex @option{-fno-inline} (@command{gcc})
3758 Suppresses all back-end inlining, even if other optimization or inlining
3759 switches are set.
3760 This includes suppression of inlining that results
3761 from the use of the pragma @code{Inline_Always}.
3762 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3763 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3764 effect if this switch is present.
3765
3766 @item -fno-strict-aliasing
3767 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3768 Causes the compiler to avoid assumptions regarding non-aliasing
3769 of objects of different types. See
3770 @ref{Optimization and Strict Aliasing} for details.
3771
3772 @item -fstack-check
3773 @cindex @option{-fstack-check} (@command{gcc})
3774 Activates stack checking.
3775 See @ref{Stack Overflow Checking} for details.
3776
3777 @item -fstack-usage
3778 @cindex @option{-fstack-usage} (@command{gcc})
3779 Makes the compiler output stack usage information for the program, on a
3780 per-function basis. See @ref{Static Stack Usage Analysis} for details.
3781
3782 @item -fcallgraph-info[=su]
3783 @cindex @option{-fcallgraph-info} (@command{gcc})
3784 Makes the compiler output callgraph information for the program, on a
3785 per-file basis.  The information is generated in the VCG format.  It can
3786 be decorated with stack-usage per-node information.
3787
3788 @item ^-g^/DEBUG^
3789 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3790 Generate debugging information. This information is stored in the object
3791 file and copied from there to the final executable file by the linker,
3792 where it can be read by the debugger. You must use the
3793 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3794
3795 @item -gnat83
3796 @cindex @option{-gnat83} (@command{gcc})
3797 Enforce Ada 83 restrictions.
3798
3799 @item -gnat95
3800 @cindex @option{-gnat95} (@command{gcc})
3801 Enforce Ada 95 restrictions.
3802
3803 @item -gnat05
3804 @cindex @option{-gnat05} (@command{gcc})
3805 Allow full Ada 2005 features.
3806
3807 @item -gnata
3808 @cindex @option{-gnata} (@command{gcc})
3809 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3810 activated. Note that these pragmas can also be controlled using the
3811 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3812
3813 @item -gnatA
3814 @cindex @option{-gnatA} (@command{gcc})
3815 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3816 it will be ignored.
3817
3818 @item -gnatb
3819 @cindex @option{-gnatb} (@command{gcc})
3820 Generate brief messages to @file{stderr} even if verbose mode set.
3821
3822 @item -gnatc
3823 @cindex @option{-gnatc} (@command{gcc})
3824 Check syntax and semantics only (no code generation attempted).
3825
3826 @item -gnatd
3827 @cindex @option{-gnatd} (@command{gcc})
3828 Specify debug options for the compiler. The string of characters after
3829 the @option{-gnatd} specify the specific debug options. The possible
3830 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3831 compiler source file @file{debug.adb} for details of the implemented
3832 debug options. Certain debug options are relevant to applications
3833 programmers, and these are documented at appropriate points in this
3834 users guide.
3835
3836 @item -gnatD
3837 @cindex @option{-gnatD} (@command{gcc})
3838 Create expanded source files for source level debugging. This switch
3839 also suppress generation of cross-reference information
3840 (see @option{-gnatx}).
3841
3842 @item -gnatec=@var{path}
3843 @cindex @option{-gnatec} (@command{gcc})
3844 Specify a configuration pragma file
3845 @ifclear vms
3846 (the equal sign is optional)
3847 @end ifclear
3848 (@pxref{The Configuration Pragmas Files}).
3849
3850 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3851 @cindex @option{-gnateD} (@command{gcc})
3852 Defines a symbol, associated with value, for preprocessing.
3853 (@pxref{Integrated Preprocessing}).
3854
3855 @item -gnatef
3856 @cindex @option{-gnatef} (@command{gcc})
3857 Display full source path name in brief error messages.
3858
3859 @item -gnatem=@var{path}
3860 @cindex @option{-gnatem} (@command{gcc})
3861 Specify a mapping file
3862 @ifclear vms
3863 (the equal sign is optional)
3864 @end ifclear
3865 (@pxref{Units to Sources Mapping Files}).
3866
3867 @item -gnatep=@var{file}
3868 @cindex @option{-gnatep} (@command{gcc})
3869 Specify a preprocessing data file
3870 @ifclear vms
3871 (the equal sign is optional)
3872 @end ifclear
3873 (@pxref{Integrated Preprocessing}).
3874
3875 @item -gnatE
3876 @cindex @option{-gnatE} (@command{gcc})
3877 Full dynamic elaboration checks.
3878
3879 @item -gnatf
3880 @cindex @option{-gnatf} (@command{gcc})
3881 Full errors. Multiple errors per line, all undefined references, do not
3882 attempt to suppress cascaded errors.
3883
3884 @item -gnatF
3885 @cindex @option{-gnatF} (@command{gcc})
3886 Externals names are folded to all uppercase.
3887
3888 @item ^-gnatg^/GNAT_INTERNAL^
3889 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
3890 Internal GNAT implementation mode. This should not be used for
3891 applications programs, it is intended only for use by the compiler
3892 and its run-time library. For documentation, see the GNAT sources.
3893 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
3894 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
3895 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
3896 so that all standard warnings and all standard style options are turned on.
3897 All warnings and style error messages are treated as errors.
3898
3899 @item -gnatG
3900 @cindex @option{-gnatG} (@command{gcc})
3901 List generated expanded code in source form.
3902
3903 @item ^-gnath^/HELP^
3904 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3905 Output usage information. The output is written to @file{stdout}.
3906
3907 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3908 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3909 Identifier character set
3910 @ifclear vms
3911 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3912 @end ifclear
3913 For details of the possible selections for @var{c},
3914 see @ref{Character Set Control}.
3915
3916 @item ^-gnatI^/IGNORE_REP_CLAUSES^
3917 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
3918 Ignore representation clauses. When this switch is used, all
3919 representation clauses are treated as comments. This is useful
3920 when initially porting code where you want to ignore rep clause
3921 problems, and also for compiling foreign code (particularly
3922 for use with ASIS).
3923
3924 @item -gnatjnn
3925 @cindex @option{-gnatjnn} (@command{gcc})
3926 Reformat error messages to fit on nn character lines
3927
3928 @item -gnatk=@var{n}
3929 @cindex @option{-gnatk} (@command{gcc})
3930 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3931
3932 @item -gnatl
3933 @cindex @option{-gnatl} (@command{gcc})
3934 Output full source listing with embedded error messages.
3935
3936 @item -gnatL
3937 @cindex @option{-gnatL} (@command{gcc})
3938 Used in conjunction with -gnatG or -gnatD to intersperse original
3939 source lines (as comment lines with line numbers) in the expanded
3940 source output.
3941
3942 @item -gnatm=@var{n}
3943 @cindex @option{-gnatm} (@command{gcc})
3944 Limit number of detected error or warning messages to @var{n}
3945 where @var{n} is in the range 1..999_999. The default setting if
3946 no switch is given is 9999. Compilation is terminated if this
3947 limit is exceeded. The equal sign here is optional.
3948
3949 @item -gnatn
3950 @cindex @option{-gnatn} (@command{gcc})
3951 Activate inlining for subprograms for which
3952 pragma @code{inline} is specified. This inlining is performed
3953 by the GCC back-end.
3954
3955 @item -gnatN
3956 @cindex @option{-gnatN} (@command{gcc})
3957 Activate front end inlining for subprograms for which
3958 pragma @code{Inline} is specified. This inlining is performed
3959 by the front end and will be visible in the
3960 @option{-gnatG} output.
3961 In some cases, this has proved more effective than the back end
3962 inlining resulting from the use of
3963 @option{-gnatn}.
3964 Note that
3965 @option{-gnatN} automatically implies
3966 @option{-gnatn} so it is not necessary
3967 to specify both options. There are a few cases that the back-end inlining
3968 catches that cannot be dealt with in the front-end.
3969
3970 @item -gnato
3971 @cindex @option{-gnato} (@command{gcc})
3972 Enable numeric overflow checking (which is not normally enabled by
3973 default). Not that division by zero is a separate check that is not
3974 controlled by this switch (division by zero checking is on by default).
3975
3976 @item -gnatp
3977 @cindex @option{-gnatp} (@command{gcc})
3978 Suppress all checks.
3979
3980 @item -gnatP
3981 @cindex @option{-gnatP} (@command{gcc})
3982 Enable polling. This is required on some systems (notably Windows NT) to
3983 obtain asynchronous abort and asynchronous transfer of control capability.
3984 See the description of pragma Polling in the GNAT Reference Manual for
3985 full details.
3986
3987 @item -gnatq
3988 @cindex @option{-gnatq} (@command{gcc})
3989 Don't quit; try semantics, even if parse errors.
3990
3991 @item -gnatQ
3992 @cindex @option{-gnatQ} (@command{gcc})
3993 Don't quit; generate @file{ALI} and tree files even if illegalities.
3994
3995 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3996 @cindex @option{-gnatR} (@command{gcc})
3997 Output representation information for declared types and objects.
3998
3999 @item -gnats
4000 @cindex @option{-gnats} (@command{gcc})
4001 Syntax check only.
4002
4003 @item -gnatS
4004 @cindex @option{-gnatS} (@command{gcc})
4005 Print package Standard.
4006
4007 @item -gnatt
4008 @cindex @option{-gnatt} (@command{gcc})
4009 Generate tree output file.
4010
4011 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4012 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4013 All compiler tables start at @var{nnn} times usual starting size.
4014
4015 @item -gnatu
4016 @cindex @option{-gnatu} (@command{gcc})
4017 List units for this compilation.
4018
4019 @item -gnatU
4020 @cindex @option{-gnatU} (@command{gcc})
4021 Tag all error messages with the unique string ``error:''
4022
4023 @item -gnatv
4024 @cindex @option{-gnatv} (@command{gcc})
4025 Verbose mode. Full error output with source lines to @file{stdout}.
4026
4027 @item -gnatV
4028 @cindex @option{-gnatV} (@command{gcc})
4029 Control level of validity checking. See separate section describing
4030 this feature.
4031
4032 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,@dots{}])^
4033 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4034 Warning mode where
4035 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4036 the exact warnings that
4037 are enabled or disabled (@pxref{Warning Message Control}).
4038
4039 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4040 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4041 Wide character encoding method
4042 @ifclear vms
4043 (@var{e}=n/h/u/s/e/8).
4044 @end ifclear
4045 @ifset vms
4046 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4047 @end ifset
4048
4049 @item -gnatx
4050 @cindex @option{-gnatx} (@command{gcc})
4051 Suppress generation of cross-reference information.
4052
4053 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4054 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4055 Enable built-in style checks (@pxref{Style Checking}).
4056
4057 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4058 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4059 Distribution stub generation and compilation
4060 @ifclear vms
4061 (@var{m}=r/c for receiver/caller stubs).
4062 @end ifclear
4063 @ifset vms
4064 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4065 to be generated and compiled).
4066 @end ifset
4067
4068 @item ^-I^/SEARCH=^@var{dir}
4069 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4070 @cindex RTL
4071 Direct GNAT to search the @var{dir} directory for source files needed by
4072 the current compilation
4073 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4074
4075 @item ^-I-^/NOCURRENT_DIRECTORY^
4076 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4077 @cindex RTL
4078 Except for the source file named in the command line, do not look for source
4079 files in the directory containing the source file named in the command line
4080 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4081
4082 @ifclear vms
4083 @item -mbig-switch
4084 @cindex @option{-mbig-switch} (@command{gcc})
4085 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4086 This standard gcc switch causes the compiler to use larger offsets in its
4087 jump table representation for @code{case} statements.
4088 This may result in less efficient code, but is sometimes necessary
4089 (for example on HP-UX targets)
4090 @cindex HP-UX and @option{-mbig-switch} option
4091 in order to compile large and/or nested @code{case} statements.
4092
4093 @item -o @var{file}
4094 @cindex @option{-o} (@command{gcc})
4095 This switch is used in @command{gcc} to redirect the generated object file
4096 and its associated ALI file. Beware of this switch with GNAT, because it may
4097 cause the object file and ALI file to have different names which in turn
4098 may confuse the binder and the linker.
4099 @end ifclear
4100
4101 @item -nostdinc
4102 @cindex @option{-nostdinc} (@command{gcc})
4103 Inhibit the search of the default location for the GNAT Run Time
4104 Library (RTL) source files.
4105
4106 @item -nostdlib
4107 @cindex @option{-nostdlib} (@command{gcc})
4108 Inhibit the search of the default location for the GNAT Run Time
4109 Library (RTL) ALI files.
4110
4111 @ifclear vms
4112 @item -O[@var{n}]
4113 @cindex @option{-O} (@command{gcc})
4114 @var{n} controls the optimization level.
4115
4116 @table @asis
4117 @item n = 0
4118 No optimization, the default setting if no @option{-O} appears
4119
4120 @item n = 1
4121 Normal optimization, the default if you specify @option{-O} without
4122 an operand. A good compromise between code quality and compilation
4123 time.
4124
4125 @item n = 2
4126 Extensive optimization, may improve execution time, possibly at the cost of
4127 substantially increased compilation time.
4128
4129 @item n = 3
4130 Same as @option{-O2}, and also includes inline expansion for small subprograms
4131 in the same unit.
4132
4133 @item n = s
4134 Optimize space usage
4135 @end table
4136
4137 @noindent
4138 See also @ref{Optimization Levels}.
4139 @end ifclear
4140
4141 @ifset vms
4142 @item  /NOOPTIMIZE
4143 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4144 Equivalent to @option{/OPTIMIZE=NONE}.
4145 This is the default behavior in the absence of an @option{/OPTIMIZE}
4146 qualifier.
4147
4148 @item /OPTIMIZE[=(keyword[,@dots{}])]
4149 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4150 Selects the level of optimization for your program. The supported
4151 keywords are as follows:
4152 @table @code
4153 @item   ALL
4154 Perform most optimizations, including those that
4155 are expensive.
4156 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4157 without keyword options.
4158
4159 @item   NONE
4160 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4161
4162 @item SOME
4163 Perform some optimizations, but omit ones that are costly.
4164
4165 @item   DEVELOPMENT
4166 Same as @code{SOME}.
4167
4168 @item INLINING
4169 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4170 automatic inlining of small subprograms within a unit
4171
4172 @item   UNROLL_LOOPS
4173 Try to unroll loops. This keyword may be specified together with
4174 any keyword above other than @code{NONE}. Loop unrolling
4175 usually, but not always, improves the performance of programs.
4176
4177 @item SPACE
4178 Optimize space usage
4179 @end table
4180
4181 @noindent
4182 See also @ref{Optimization Levels}.
4183 @end ifset
4184
4185 @ifclear vms
4186 @item -pass-exit-codes
4187 @cindex @option{-pass-exit-codes} (@command{gcc})
4188 Catch exit codes from the compiler and use the most meaningful as
4189 exit status.
4190 @end ifclear
4191
4192 @item --RTS=@var{rts-path}
4193 @cindex @option{--RTS} (@command{gcc})
4194 Specifies the default location of the runtime library. Same meaning as the
4195 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4196
4197 @item ^-S^/ASM^
4198 @cindex @option{^-S^/ASM^} (@command{gcc})
4199 ^Used in place of @option{-c} to^Used to^
4200 cause the assembler source file to be
4201 generated, using @file{^.s^.S^} as the extension,
4202 instead of the object file.
4203 This may be useful if you need to examine the generated assembly code.
4204
4205 @item ^-fverbose-asm^/VERBOSE_ASM^
4206 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4207 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4208 to cause the generated assembly code file to be annotated with variable
4209 names, making it significantly easier to follow.
4210
4211 @item ^-v^/VERBOSE^
4212 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4213 Show commands generated by the @command{gcc} driver. Normally used only for
4214 debugging purposes or if you need to be sure what version of the
4215 compiler you are executing.
4216
4217 @ifclear vms
4218 @item -V @var{ver}
4219 @cindex @option{-V} (@command{gcc})
4220 Execute @var{ver} version of the compiler. This is the @command{gcc}
4221 version, not the GNAT version.
4222 @end ifclear
4223
4224 @item ^-w^/NO_BACK_END_WARNINGS^
4225 @cindex @option{-w} (@command{gcc})
4226 Turn off warnings generated by the back end of the compiler. Use of
4227 this switch also causes the default for front end warnings to be set
4228 to suppress (as though @option{-gnatws} had appeared at the start of
4229 the options.
4230
4231 @end table
4232
4233 @ifclear vms
4234 @c Combining qualifiers does not work on VMS
4235 You may combine a sequence of GNAT switches into a single switch. For
4236 example, the combined switch
4237
4238 @cindex Combining GNAT switches
4239 @smallexample
4240 -gnatofi3
4241 @end smallexample
4242
4243 @noindent
4244 is equivalent to specifying the following sequence of switches:
4245
4246 @smallexample
4247 -gnato -gnatf -gnati3
4248 @end smallexample
4249 @end ifclear
4250
4251 @noindent
4252 The following restrictions apply to the combination of switches
4253 in this manner:
4254
4255 @itemize @bullet
4256 @item
4257 The switch @option{-gnatc} if combined with other switches must come
4258 first in the string.
4259
4260 @item
4261 The switch @option{-gnats} if combined with other switches must come
4262 first in the string.
4263
4264 @item
4265 The switches
4266 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4267 may not be combined with any other switches.
4268
4269 @ifclear vms
4270 @item
4271 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4272 switch), then all further characters in the switch are interpreted
4273 as style modifiers (see description of @option{-gnaty}).
4274
4275 @item
4276 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4277 switch), then all further characters in the switch are interpreted
4278 as debug flags (see description of @option{-gnatd}).
4279
4280 @item
4281 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4282 switch), then all further characters in the switch are interpreted
4283 as warning mode modifiers (see description of @option{-gnatw}).
4284
4285 @item
4286 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4287 switch), then all further characters in the switch are interpreted
4288 as validity checking options (see description of @option{-gnatV}).
4289 @end ifclear
4290 @end itemize
4291
4292 @node Output and Error Message Control
4293 @subsection Output and Error Message Control
4294 @findex stderr
4295
4296 @noindent
4297 The standard default format for error messages is called ``brief format''.
4298 Brief format messages are written to @file{stderr} (the standard error
4299 file) and have the following form:
4300
4301 @smallexample
4302 e.adb:3:04: Incorrect spelling of keyword "function"
4303 e.adb:4:20: ";" should be "is"
4304 @end smallexample
4305
4306 @noindent
4307 The first integer after the file name is the line number in the file,
4308 and the second integer is the column number within the line.
4309 @ifclear vms
4310 @code{GPS} can parse the error messages
4311 and point to the referenced character.
4312 @end ifclear
4313 The following switches provide control over the error message
4314 format:
4315
4316 @table @option
4317 @c !sort!
4318 @item -gnatv
4319 @cindex @option{-gnatv} (@command{gcc})
4320 @findex stdout
4321 @ifclear vms
4322 The v stands for verbose.
4323 @end ifclear
4324 The effect of this setting is to write long-format error
4325 messages to @file{stdout} (the standard output file.
4326 The same program compiled with the
4327 @option{-gnatv} switch would generate:
4328
4329 @smallexample
4330 @cartouche
4331 3. funcion X (Q : Integer)
4332    |
4333 >>> Incorrect spelling of keyword "function"
4334 4. return Integer;
4335                  |
4336 >>> ";" should be "is"
4337 @end cartouche
4338 @end smallexample
4339
4340 @noindent
4341 The vertical bar indicates the location of the error, and the @samp{>>>}
4342 prefix can be used to search for error messages. When this switch is
4343 used the only source lines output are those with errors.
4344
4345 @item -gnatl
4346 @cindex @option{-gnatl} (@command{gcc})
4347 @ifclear vms
4348 The @code{l} stands for list.
4349 @end ifclear
4350 This switch causes a full listing of
4351 the file to be generated. In the case where a body is
4352 compiled, the corresponding spec is also listed, along
4353 with any subunits. Typical output from compiling a package
4354 body @file{p.adb} might look like:
4355
4356 @smallexample @c ada
4357 @cartouche
4358  Compiling: p.adb
4359
4360      1. package body p is
4361      2.    procedure a;
4362      3.    procedure a is separate;
4363      4. begin
4364      5.    null
4365                |
4366         >>> missing ";"
4367
4368      6. end;
4369
4370 Compiling: p.ads
4371
4372      1. package p is
4373      2.    pragma Elaborate_Body
4374                                 |
4375         >>> missing ";"
4376
4377      3. end p;
4378
4379 Compiling: p-a.adb
4380
4381      1. separate p
4382                 |
4383         >>> missing "("
4384
4385      2. procedure a is
4386      3. begin
4387      4.    null
4388                |
4389         >>> missing ";"
4390
4391      5. end;
4392 @end cartouche
4393 @end smallexample
4394
4395 @noindent
4396 @findex stderr
4397 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4398 standard output is redirected, a brief summary is written to
4399 @file{stderr} (standard error) giving the number of error messages and
4400 warning messages generated.
4401
4402 @item -^gnatl^OUTPUT_FILE^=file
4403 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4404 This has the same effect as @option{-gnatl} except that the output is
4405 written to a file instead of to standard output. If the given name
4406 @file{fname} does not start with a period, then it is the full name
4407 of the file to be written. If @file{fname} is an extension, it is
4408 appended to the name of the file being compiled. For example, if
4409 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4410 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4411
4412 @item -gnatU
4413 @cindex @option{-gnatU} (@command{gcc})
4414 This switch forces all error messages to be preceded by the unique
4415 string ``error:''. This means that error messages take a few more
4416 characters in space, but allows easy searching for and identification
4417 of error messages.
4418
4419 @item -gnatb
4420 @cindex @option{-gnatb} (@command{gcc})
4421 @ifclear vms
4422 The @code{b} stands for brief.
4423 @end ifclear
4424 This switch causes GNAT to generate the
4425 brief format error messages to @file{stderr} (the standard error
4426 file) as well as the verbose
4427 format message or full listing (which as usual is written to
4428 @file{stdout} (the standard output file).
4429
4430 @item -gnatm=@var{n}
4431 @cindex @option{-gnatm} (@command{gcc})
4432 @ifclear vms
4433 The @code{m} stands for maximum.
4434 @end ifclear
4435 @var{n} is a decimal integer in the
4436 range of 1 to 999 and limits the number of error messages to be
4437 generated. For example, using @option{-gnatm2} might yield
4438
4439 @smallexample
4440 e.adb:3:04: Incorrect spelling of keyword "function"
4441 e.adb:5:35: missing ".."
4442 fatal error: maximum errors reached
4443 compilation abandoned
4444 @end smallexample
4445
4446 @noindent
4447 Note that the equal sign is optional, so the switches
4448 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4449
4450 @item -gnatf
4451 @cindex @option{-gnatf} (@command{gcc})
4452 @cindex Error messages, suppressing
4453 @ifclear vms
4454 The @code{f} stands for full.
4455 @end ifclear
4456 Normally, the compiler suppresses error messages that are likely to be
4457 redundant. This switch causes all error
4458 messages to be generated. In particular, in the case of
4459 references to undefined variables. If a given variable is referenced
4460 several times, the normal format of messages is
4461 @smallexample
4462 e.adb:7:07: "V" is undefined (more references follow)
4463 @end smallexample
4464
4465 @noindent
4466 where the parenthetical comment warns that there are additional
4467 references to the variable @code{V}. Compiling the same program with the
4468 @option{-gnatf} switch yields
4469
4470 @smallexample
4471 e.adb:7:07: "V" is undefined
4472 e.adb:8:07: "V" is undefined
4473 e.adb:8:12: "V" is undefined
4474 e.adb:8:16: "V" is undefined
4475 e.adb:9:07: "V" is undefined
4476 e.adb:9:12: "V" is undefined
4477 @end smallexample
4478
4479 @noindent
4480 The @option{-gnatf} switch also generates additional information for
4481 some error messages.  Some examples are:
4482
4483 @itemize @bullet
4484 @item
4485 Full details on entities not available in high integrity mode
4486 @item
4487 Details on possibly non-portable unchecked conversion
4488 @item
4489 List possible interpretations for ambiguous calls
4490 @item
4491 Additional details on incorrect parameters
4492 @end itemize
4493
4494 @item -gnatjnn
4495 @cindex @option{-gnatjnn} (@command{gcc})
4496 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4497 with continuation lines are treated as though the continuation lines were
4498 separate messages (and so a warning with two continuation lines counts as
4499 three warnings, and is listed as three separate messages).
4500
4501 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4502 messages are output in a different manner. A message and all its continuation
4503 lines are treated as a unit, and count as only one warning or message in the
4504 statistics totals. Furthermore, the message is reformatted so that no line
4505 is longer than nn characters.
4506
4507 @item -gnatq
4508 @cindex @option{-gnatq} (@command{gcc})
4509 @ifclear vms
4510 The @code{q} stands for quit (really ``don't quit'').
4511 @end ifclear
4512 In normal operation mode, the compiler first parses the program and
4513 determines if there are any syntax errors. If there are, appropriate
4514 error messages are generated and compilation is immediately terminated.
4515 This switch tells
4516 GNAT to continue with semantic analysis even if syntax errors have been
4517 found. This may enable the detection of more errors in a single run. On
4518 the other hand, the semantic analyzer is more likely to encounter some
4519 internal fatal error when given a syntactically invalid tree.
4520
4521 @item -gnatQ
4522 @cindex @option{-gnatQ} (@command{gcc})
4523 In normal operation mode, the @file{ALI} file is not generated if any
4524 illegalities are detected in the program. The use of @option{-gnatQ} forces
4525 generation of the @file{ALI} file. This file is marked as being in
4526 error, so it cannot be used for binding purposes, but it does contain
4527 reasonably complete cross-reference information, and thus may be useful
4528 for use by tools (e.g., semantic browsing tools or integrated development
4529 environments) that are driven from the @file{ALI} file. This switch
4530 implies @option{-gnatq}, since the semantic phase must be run to get a
4531 meaningful ALI file.
4532
4533 In addition, if @option{-gnatt} is also specified, then the tree file is
4534 generated even if there are illegalities. It may be useful in this case
4535 to also specify @option{-gnatq} to ensure that full semantic processing
4536 occurs. The resulting tree file can be processed by ASIS, for the purpose
4537 of providing partial information about illegal units, but if the error
4538 causes the tree to be badly malformed, then ASIS may crash during the
4539 analysis.
4540
4541 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4542 being in error, @command{gnatmake} will attempt to recompile the source when it
4543 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4544
4545 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4546 since ALI files are never generated if @option{-gnats} is set.
4547
4548 @end table
4549
4550 @node Warning Message Control
4551 @subsection Warning Message Control
4552 @cindex Warning messages
4553 @noindent
4554 In addition to error messages, which correspond to illegalities as defined
4555 in the Ada Reference Manual, the compiler detects two kinds of warning
4556 situations.
4557
4558 First, the compiler considers some constructs suspicious and generates a
4559 warning message to alert you to a possible error. Second, if the
4560 compiler detects a situation that is sure to raise an exception at
4561 run time, it generates a warning message. The following shows an example
4562 of warning messages:
4563 @smallexample
4564 e.adb:4:24: warning: creation of object may raise Storage_Error
4565 e.adb:10:17: warning: static value out of range
4566 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4567 @end smallexample
4568
4569 @noindent
4570 GNAT considers a large number of situations as appropriate
4571 for the generation of warning messages. As always, warnings are not
4572 definite indications of errors. For example, if you do an out-of-range
4573 assignment with the deliberate intention of raising a
4574 @code{Constraint_Error} exception, then the warning that may be
4575 issued does not indicate an error. Some of the situations for which GNAT
4576 issues warnings (at least some of the time) are given in the following
4577 list. This list is not complete, and new warnings are often added to
4578 subsequent versions of GNAT. The list is intended to give a general idea
4579 of the kinds of warnings that are generated.
4580
4581 @itemize @bullet
4582 @item
4583 Possible infinitely recursive calls
4584
4585 @item
4586 Out-of-range values being assigned
4587
4588 @item
4589 Possible order of elaboration problems
4590
4591 @item
4592 Assertions (pragma Assert) that are sure to fail
4593
4594 @item
4595 Unreachable code
4596
4597 @item
4598 Address clauses with possibly unaligned values, or where an attempt is
4599 made to overlay a smaller variable with a larger one.
4600
4601 @item
4602 Fixed-point type declarations with a null range
4603
4604 @item
4605 Direct_IO or Sequential_IO instantiated with a type that has access values
4606
4607 @item
4608 Variables that are never assigned a value
4609
4610 @item
4611 Variables that are referenced before being initialized
4612
4613 @item
4614 Task entries with no corresponding @code{accept} statement
4615
4616 @item
4617 Duplicate accepts for the same task entry in a @code{select}
4618
4619 @item
4620 Objects that take too much storage
4621
4622 @item
4623 Unchecked conversion between types of differing sizes
4624
4625 @item
4626 Missing @code{return} statement along some execution path in a function
4627
4628 @item
4629 Incorrect (unrecognized) pragmas
4630
4631 @item
4632 Incorrect external names
4633
4634 @item
4635 Allocation from empty storage pool
4636
4637 @item
4638 Potentially blocking operation in protected type
4639
4640 @item
4641 Suspicious parenthesization of expressions
4642
4643 @item
4644 Mismatching bounds in an aggregate
4645
4646 @item
4647 Attempt to return local value by reference
4648
4649 @item
4650 Premature instantiation of a generic body
4651
4652 @item
4653 Attempt to pack aliased components
4654
4655 @item
4656 Out of bounds array subscripts
4657
4658 @item
4659 Wrong length on string assignment
4660
4661 @item
4662 Violations of style rules if style checking is enabled
4663
4664 @item
4665 Unused @code{with} clauses
4666
4667 @item
4668 @code{Bit_Order} usage that does not have any effect
4669
4670 @item
4671 @code{Standard.Duration} used to resolve universal fixed expression
4672
4673 @item
4674 Dereference of possibly null value
4675
4676 @item
4677 Declaration that is likely to cause storage error
4678
4679 @item
4680 Internal GNAT unit @code{with}'ed by application unit
4681
4682 @item
4683 Values known to be out of range at compile time
4684
4685 @item
4686 Unreferenced labels and variables
4687
4688 @item
4689 Address overlays that could clobber memory
4690
4691 @item
4692 Unexpected initialization when address clause present
4693
4694 @item
4695 Bad alignment for address clause
4696
4697 @item
4698 Useless type conversions
4699
4700 @item
4701 Redundant assignment statements and other redundant constructs
4702
4703 @item
4704 Useless exception handlers
4705
4706 @item
4707 Accidental hiding of name by child unit
4708
4709 @item
4710 Access before elaboration detected at compile time
4711
4712 @item
4713 A range in a @code{for} loop that is known to be null or might be null
4714
4715 @end itemize
4716
4717 @noindent
4718 The following section lists compiler switches that are available
4719 to control the handling of warning messages. It is also possible
4720 to exercise much finer control over what warnings are issued and
4721 suppressed using the GNAT pragma Warnings, which is documented
4722 in the GNAT Reference manual.
4723
4724 @table @option
4725 @c !sort!
4726 @item -gnatwa
4727 @emph{Activate all optional errors.}
4728 @cindex @option{-gnatwa} (@command{gcc})
4729 This switch activates most optional warning messages, see remaining list
4730 in this section for details on optional warning messages that can be
4731 individually controlled.  The warnings that are not turned on by this
4732 switch are
4733 @option{-gnatwd} (implicit dereferencing),
4734 @option{-gnatwh} (hiding),
4735 @option{-gnatwl} (elaboration warnings),
4736 @option{-gnatw.o} (warn on values set by out parameters ignored)
4737 and @option{-gnatwt} (tracking of deleted conditional code).
4738 All other optional warnings are turned on.
4739
4740 @item -gnatwA
4741 @emph{Suppress all optional errors.}
4742 @cindex @option{-gnatwA} (@command{gcc})
4743 This switch suppresses all optional warning messages, see remaining list
4744 in this section for details on optional warning messages that can be
4745 individually controlled.
4746
4747 @item -gnatw.a
4748 @emph{Activate warnings on failing assertions.}
4749 @cindex @option{-gnatw.a} (@command{gcc})
4750 @cindex Assert failures
4751 This switch activates warnings for assertions where the compiler can tell at
4752 compile time that the assertion will fail. Note that this warning is given
4753 even if assertions are disabled. The default is that such warnings are
4754 generated.
4755
4756 @item -gnatw.A
4757 @emph{Suppress warnings on failing assertions.}
4758 @cindex @option{-gnatw.A} (@command{gcc})
4759 @cindex Assert failures
4760 This switch suppresses warnings for assertions where the compiler can tell at
4761 compile time that the assertion will fail.
4762
4763 @item -gnatwb
4764 @emph{Activate warnings on bad fixed values.}
4765 @cindex @option{-gnatwb} (@command{gcc})
4766 @cindex Bad fixed values
4767 @cindex Fixed-point Small value
4768 @cindex Small value
4769 This switch activates warnings for static fixed-point expressions whose
4770 value is not an exact multiple of Small. Such values are implementation
4771 dependent, since an implementation is free to choose either of the multiples
4772 that surround the value. GNAT always chooses the closer one, but this is not
4773 required behavior, and it is better to specify a value that is an exact
4774 multiple, ensuring predictable execution. The default is that such warnings
4775 are not generated.
4776
4777 @item -gnatwB
4778 @emph{Suppress warnings on bad fixed values.}
4779 @cindex @option{-gnatwB} (@command{gcc})
4780 This switch suppresses warnings for static fixed-point expressions whose
4781 value is not an exact multiple of Small.
4782
4783 @item -gnatwc
4784 @emph{Activate warnings on conditionals.}
4785 @cindex @option{-gnatwc} (@command{gcc})
4786 @cindex Conditionals, constant
4787 This switch activates warnings for conditional expressions used in
4788 tests that are known to be True or False at compile time. The default
4789 is that such warnings are not generated.
4790 Note that this warning does
4791 not get issued for the use of boolean variables or constants whose
4792 values are known at compile time, since this is a standard technique
4793 for conditional compilation in Ada, and this would generate too many
4794 false positive warnings.
4795
4796 This warning option also activates a special test for comparisons using
4797 the operators ``>='' and`` <=''.
4798 If the compiler can tell that only the equality condition is possible,
4799 then it will warn that the ``>'' or ``<'' part of the test
4800 is useless and that the operator could be replaced by ``=''.
4801 An example would be comparing a @code{Natural} variable <= 0.
4802
4803 This warning option also generates warnings if
4804 one or both tests is optimized away in a membership test for integer
4805 values if the result can be determined at compile time. Range tests on
4806 enumeration types are not included, since it is common for such tests
4807 to include an end point.
4808
4809 This warning can also be turned on using @option{-gnatwa}.
4810
4811 @item -gnatwC
4812 @emph{Suppress warnings on conditionals.}
4813 @cindex @option{-gnatwC} (@command{gcc})
4814 This switch suppresses warnings for conditional expressions used in
4815 tests that are known to be True or False at compile time.
4816
4817 @item -gnatw.c
4818 @emph{Activate warnings on missing component clauses.}
4819 @cindex @option{-gnatw.c} (@command{gcc})
4820 @cindex Component clause, missing
4821 This switch activates warnings for record components where a record
4822 representation clause is present and has component clauses for the
4823 majority, but not all, of the components. A warning is given for each
4824 component for which no component clause is present.
4825
4826 This warning can also be turned on using @option{-gnatwa}.
4827
4828 @item -gnatw.C
4829 @emph{Suppress warnings on missing component clauses.}
4830 @cindex @option{-gnatwC} (@command{gcc})
4831 This switch suppresses warnings for record components that are
4832 missing a component clause in the situation described above.
4833
4834 @item -gnatwd
4835 @emph{Activate warnings on implicit dereferencing.}
4836 @cindex @option{-gnatwd} (@command{gcc})
4837 If this switch is set, then the use of a prefix of an access type
4838 in an indexed component, slice, or selected component without an
4839 explicit @code{.all} will generate a warning. With this warning
4840 enabled, access checks occur only at points where an explicit
4841 @code{.all} appears in the source code (assuming no warnings are
4842 generated as a result of this switch). The default is that such
4843 warnings are not generated.
4844 Note that @option{-gnatwa} does not affect the setting of
4845 this warning option.
4846
4847 @item -gnatwD
4848 @emph{Suppress warnings on implicit dereferencing.}
4849 @cindex @option{-gnatwD} (@command{gcc})
4850 @cindex Implicit dereferencing
4851 @cindex Dereferencing, implicit
4852 This switch suppresses warnings for implicit dereferences in
4853 indexed components, slices, and selected components.
4854
4855 @item -gnatwe
4856 @emph{Treat warnings as errors.}
4857 @cindex @option{-gnatwe} (@command{gcc})
4858 @cindex Warnings, treat as error
4859 This switch causes warning messages to be treated as errors.
4860 The warning string still appears, but the warning messages are counted
4861 as errors, and prevent the generation of an object file.
4862
4863 @item -gnatwf
4864 @emph{Activate warnings on unreferenced formals.}
4865 @cindex @option{-gnatwf} (@command{gcc})
4866 @cindex Formals, unreferenced
4867 This switch causes a warning to be generated if a formal parameter
4868 is not referenced in the body of the subprogram. This warning can
4869 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
4870 default is that these warnings are not generated.
4871
4872 @item -gnatwF
4873 @emph{Suppress warnings on unreferenced formals.}
4874 @cindex @option{-gnatwF} (@command{gcc})
4875 This switch suppresses warnings for unreferenced formal
4876 parameters. Note that the
4877 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4878 effect of warning on unreferenced entities other than subprogram
4879 formals.
4880
4881 @item -gnatwg
4882 @emph{Activate warnings on unrecognized pragmas.}
4883 @cindex @option{-gnatwg} (@command{gcc})
4884 @cindex Pragmas, unrecognized
4885 This switch causes a warning to be generated if an unrecognized
4886 pragma is encountered. Apart from issuing this warning, the
4887 pragma is ignored and has no effect. This warning can
4888 also be turned on using @option{-gnatwa}. The default
4889 is that such warnings are issued (satisfying the Ada Reference
4890 Manual requirement that such warnings appear).
4891
4892 @item -gnatwG
4893 @emph{Suppress warnings on unrecognized pragmas.}
4894 @cindex @option{-gnatwG} (@command{gcc})
4895 This switch suppresses warnings for unrecognized pragmas.
4896
4897 @item -gnatwh
4898 @emph{Activate warnings on hiding.}
4899 @cindex @option{-gnatwh} (@command{gcc})
4900 @cindex Hiding of Declarations
4901 This switch activates warnings on hiding declarations.
4902 A declaration is considered hiding
4903 if it is for a non-overloadable entity, and it declares an entity with the
4904 same name as some other entity that is directly or use-visible. The default
4905 is that such warnings are not generated.
4906 Note that @option{-gnatwa} does not affect the setting of this warning option.
4907
4908 @item -gnatwH
4909 @emph{Suppress warnings on hiding.}
4910 @cindex @option{-gnatwH} (@command{gcc})
4911 This switch suppresses warnings on hiding declarations.
4912
4913 @item -gnatwi
4914 @emph{Activate warnings on implementation units.}
4915 @cindex @option{-gnatwi} (@command{gcc})
4916 This switch activates warnings for a @code{with} of an internal GNAT
4917 implementation unit, defined as any unit from the @code{Ada},
4918 @code{Interfaces}, @code{GNAT},
4919 ^^@code{DEC},^ or @code{System}
4920 hierarchies that is not
4921 documented in either the Ada Reference Manual or the GNAT
4922 Programmer's Reference Manual. Such units are intended only
4923 for internal implementation purposes and should not be @code{with}'ed
4924 by user programs. The default is that such warnings are generated
4925 This warning can also be turned on using @option{-gnatwa}.
4926
4927 @item -gnatwI
4928 @emph{Disable warnings on implementation units.}
4929 @cindex @option{-gnatwI} (@command{gcc})
4930 This switch disables warnings for a @code{with} of an internal GNAT
4931 implementation unit.
4932
4933 @item -gnatwj
4934 @emph{Activate warnings on obsolescent features (Annex J).}
4935 @cindex @option{-gnatwj} (@command{gcc})
4936 @cindex Features, obsolescent
4937 @cindex Obsolescent features
4938 If this warning option is activated, then warnings are generated for
4939 calls to subprograms marked with @code{pragma Obsolescent} and
4940 for use of features in Annex J of the Ada Reference Manual. In the
4941 case of Annex J, not all features are flagged. In particular use
4942 of the renamed packages (like @code{Text_IO}) and use of package
4943 @code{ASCII} are not flagged, since these are very common and
4944 would generate many annoying positive warnings. The default is that
4945 such warnings are not generated. This warning is also turned on by
4946 the use of @option{-gnatwa}.
4947
4948 In addition to the above cases, warnings are also generated for
4949 GNAT features that have been provided in past versions but which
4950 have been superseded (typically by features in the new Ada standard).
4951 For example, @code{pragma Ravenscar} will be flagged since its
4952 function is replaced by @code{pragma Profile(Ravenscar)}.
4953
4954 Note that this warning option functions differently from the
4955 restriction @code{No_Obsolescent_Features} in two respects.
4956 First, the restriction applies only to annex J features.
4957 Second, the restriction does flag uses of package @code{ASCII}.
4958
4959 @item -gnatwJ
4960 @emph{Suppress warnings on obsolescent features (Annex J).}
4961 @cindex @option{-gnatwJ} (@command{gcc})
4962 This switch disables warnings on use of obsolescent features.
4963
4964 @item -gnatwk
4965 @emph{Activate warnings on variables that could be constants.}
4966 @cindex @option{-gnatwk} (@command{gcc})
4967 This switch activates warnings for variables that are initialized but
4968 never modified, and then could be declared constants. The default is that
4969 such warnings are not given.
4970 This warning can also be turned on using @option{-gnatwa}.
4971
4972 @item -gnatwK
4973 @emph{Suppress warnings on variables that could be constants.}
4974 @cindex @option{-gnatwK} (@command{gcc})
4975 This switch disables warnings on variables that could be declared constants.
4976
4977 @item -gnatwl
4978 @emph{Activate warnings for missing elaboration pragmas.}
4979 @cindex @option{-gnatwl} (@command{gcc})
4980 @cindex Elaboration, warnings
4981 This switch activates warnings on missing
4982 @code{Elaborate_All} and @code{Elaborate} pragmas.
4983 See the section in this guide on elaboration checking for details on
4984 when such pragmas should be used. Warnings are also generated if you
4985 are using the static mode of elaboration, and a @code{pragma Elaborate}
4986 is encountered. The default is that such warnings
4987 are not generated.
4988 This warning is not automatically turned on by the use of @option{-gnatwa}.
4989
4990 @item -gnatwL
4991 @emph{Suppress warnings for missing elaboration pragmas.}
4992 @cindex @option{-gnatwL} (@command{gcc})
4993 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
4994 See the section in this guide on elaboration checking for details on
4995 when such pragmas should be used.
4996
4997 @item -gnatwm
4998 @emph{Activate warnings on modified but unreferenced variables.}
4999 @cindex @option{-gnatwm} (@command{gcc})
5000 This switch activates warnings for variables that are assigned (using
5001 an initialization value or with one or more assignment statements) but
5002 whose value is never read. The warning is suppressed for volatile
5003 variables and also for variables that are renamings of other variables
5004 or for which an address clause is given.
5005 This warning can also be turned on using @option{-gnatwa}.
5006 The default is that these warnings are not given.
5007
5008 @item -gnatwM
5009 @emph{Disable warnings on modified but unreferenced variables.}
5010 @cindex @option{-gnatwM} (@command{gcc})
5011 This switch disables warnings for variables that are assigned or
5012 initialized, but never read.
5013
5014 @item -gnatwn
5015 @emph{Set normal warnings mode.}
5016 @cindex @option{-gnatwn} (@command{gcc})
5017 This switch sets normal warning mode, in which enabled warnings are
5018 issued and treated as warnings rather than errors. This is the default
5019 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5020 an explicit @option{-gnatws} or
5021 @option{-gnatwe}. It also cancels the effect of the
5022 implicit @option{-gnatwe} that is activated by the
5023 use of @option{-gnatg}.
5024
5025 @item -gnatwo
5026 @emph{Activate warnings on address clause overlays.}
5027 @cindex @option{-gnatwo} (@command{gcc})
5028 @cindex Address Clauses, warnings
5029 This switch activates warnings for possibly unintended initialization
5030 effects of defining address clauses that cause one variable to overlap
5031 another. The default is that such warnings are generated.
5032 This warning can also be turned on using @option{-gnatwa}.
5033
5034 @item -gnatwO
5035 @emph{Suppress warnings on address clause overlays.}
5036 @cindex @option{-gnatwO} (@command{gcc})
5037 This switch suppresses warnings on possibly unintended initialization
5038 effects of defining address clauses that cause one variable to overlap
5039 another.
5040
5041 @item -gnatw.o
5042 @emph{Activate warnings on modified but unreferenced out parameters.}
5043 @cindex @option{-gnatw.o} (@command{gcc})
5044 This switch activates warnings for variables that are modified by using
5045 them as actuals for a call to a procedure with an out mode formal, where
5046 the resulting assigned value is never read. It is applicable in the case
5047 where there is more than one out mode formal. If there is only one out
5048 mode formal, the warning is issued by default (controlled by -gnatwu).
5049 The warning is suppressed for volatile
5050 variables and also for variables that are renamings of other variables
5051 or for which an address clause is given.
5052 The default is that these warnings are not given. Note that this warning
5053 is not included in -gnatwa, it must be activated explicitly.
5054
5055 @item -gnatw.O
5056 @emph{Disable warnings on modified but unreferenced out parameters.}
5057 @cindex @option{-gnatw.O} (@command{gcc})
5058 This switch suppresses warnings for variables that are modified by using
5059 them as actuals for a call to a procedure with an out mode formal, where
5060 the resulting assigned value is never read.
5061
5062 @item -gnatwp
5063 @emph{Activate warnings on ineffective pragma Inlines.}
5064 @cindex @option{-gnatwp} (@command{gcc})
5065 @cindex Inlining, warnings
5066 This switch activates warnings for failure of front end inlining
5067 (activated by @option{-gnatN}) to inline a particular call. There are
5068 many reasons for not being able to inline a call, including most
5069 commonly that the call is too complex to inline. The default is
5070 that such warnings are not given.
5071 This warning can also be turned on using @option{-gnatwa}.
5072 Warnings on ineffective inlining by the gcc back-end can be activated
5073 separately, using the gcc switch -Winline.
5074
5075 @item -gnatwP
5076 @emph{Suppress warnings on ineffective pragma Inlines.}
5077 @cindex @option{-gnatwP} (@command{gcc})
5078 This switch suppresses warnings on ineffective pragma Inlines. If the
5079 inlining mechanism cannot inline a call, it will simply ignore the
5080 request silently.
5081
5082 @item -gnatwq
5083 @emph{Activate warnings on questionable missing parentheses.}
5084 @cindex @option{-gnatwq} (@command{gcc})
5085 @cindex Parentheses, warnings
5086 This switch activates warnings for cases where parentheses are not used and
5087 the result is potential ambiguity from a readers point of view. For example
5088 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5089 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5090 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5091 follow the rule of always parenthesizing to make the association clear, and
5092 this warning switch warns if such parentheses are not present. The default
5093 is that these warnings are given.
5094 This warning can also be turned on using @option{-gnatwa}.
5095
5096 @item -gnatwQ
5097 @emph{Suppress warnings on questionable missing parentheses.}
5098 @cindex @option{-gnatwQ} (@command{gcc})
5099 This switch suppresses warnings for cases where the association is not
5100 clear and the use of parentheses is preferred.
5101
5102 @item -gnatwr
5103 @emph{Activate warnings on redundant constructs.}
5104 @cindex @option{-gnatwr} (@command{gcc})
5105 This switch activates warnings for redundant constructs. The following
5106 is the current list of constructs regarded as redundant:
5107
5108 @itemize @bullet
5109 @item
5110 Assignment of an item to itself.
5111 @item
5112 Type conversion that converts an expression to its own type.
5113 @item
5114 Use of the attribute @code{Base} where @code{typ'Base} is the same
5115 as @code{typ}.
5116 @item
5117 Use of pragma @code{Pack} when all components are placed by a record
5118 representation clause.
5119 @item
5120 Exception handler containing only a reraise statement (raise with no
5121 operand) which has no effect.
5122 @item
5123 Use of the operator abs on an operand that is known at compile time
5124 to be non-negative
5125 @item
5126 Comparison of boolean expressions to an explicit True value.
5127 @end itemize
5128
5129 This warning can also be turned on using @option{-gnatwa}.
5130 The default is that warnings for redundant constructs are not given.
5131
5132 @item -gnatwR
5133 @emph{Suppress warnings on redundant constructs.}
5134 @cindex @option{-gnatwR} (@command{gcc})
5135 This switch suppresses warnings for redundant constructs.
5136
5137 @item -gnatws
5138 @emph{Suppress all warnings.}
5139 @cindex @option{-gnatws} (@command{gcc})
5140 This switch completely suppresses the
5141 output of all warning messages from the GNAT front end.
5142 Note that it does not suppress warnings from the @command{gcc} back end.
5143 To suppress these back end warnings as well, use the switch @option{-w}
5144 in addition to @option{-gnatws}.
5145
5146 @item -gnatwt
5147 @emph{Activate warnings for tracking of deleted conditional code.}
5148 @cindex @option{-gnatwt} (@command{gcc})
5149 @cindex Deactivated code, warnings
5150 @cindex Deleted code, warnings
5151 This switch activates warnings for tracking of code in conditionals (IF and
5152 CASE statements) that is detected to be dead code which cannot be executed, and
5153 which is removed by the front end. This warning is off by default, and is not
5154 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5155 useful for detecting deactivated code in certified applications.
5156
5157 @item -gnatwT
5158 @emph{Suppress warnings for tracking of deleted conditional code.}
5159 @cindex @option{-gnatwT} (@command{gcc})
5160 This switch suppresses warnings for tracking of deleted conditional code.
5161
5162 @item -gnatwu
5163 @emph{Activate warnings on unused entities.}
5164 @cindex @option{-gnatwu} (@command{gcc})
5165 This switch activates warnings to be generated for entities that
5166 are declared but not referenced, and for units that are @code{with}'ed
5167 and not
5168 referenced. In the case of packages, a warning is also generated if
5169 no entities in the package are referenced. This means that if the package
5170 is referenced but the only references are in @code{use}
5171 clauses or @code{renames}
5172 declarations, a warning is still generated. A warning is also generated
5173 for a generic package that is @code{with}'ed but never instantiated.
5174 In the case where a package or subprogram body is compiled, and there
5175 is a @code{with} on the corresponding spec
5176 that is only referenced in the body,
5177 a warning is also generated, noting that the
5178 @code{with} can be moved to the body. The default is that
5179 such warnings are not generated.
5180 This switch also activates warnings on unreferenced formals
5181 (it includes the effect of @option{-gnatwf}).
5182 This warning can also be turned on using @option{-gnatwa}.
5183
5184 @item -gnatwU
5185 @emph{Suppress warnings on unused entities.}
5186 @cindex @option{-gnatwU} (@command{gcc})
5187 This switch suppresses warnings for unused entities and packages.
5188 It also turns off warnings on unreferenced formals (and thus includes
5189 the effect of @option{-gnatwF}).
5190
5191 @item -gnatwv
5192 @emph{Activate warnings on unassigned variables.}
5193 @cindex @option{-gnatwv} (@command{gcc})
5194 @cindex Unassigned variable warnings
5195 This switch activates warnings for access to variables which
5196 may not be properly initialized. The default is that
5197 such warnings are generated.
5198 This warning can also be turned on using @option{-gnatwa}.
5199
5200 @item -gnatwV
5201 @emph{Suppress warnings on unassigned variables.}
5202 @cindex @option{-gnatwV} (@command{gcc})
5203 This switch suppresses warnings for access to variables which
5204 may not be properly initialized.
5205 For variables of a composite type, the warning can also be suppressed in
5206 Ada 2005 by using a default initialization with a box. For example, if
5207 Table is an array of records whose components are only partially uninitialized,
5208 then the following code:
5209
5210 @smallexample @c ada
5211    Tab : Table := (others => <>);
5212 @end smallexample
5213
5214 will suppress warnings on subsequent statements that access components
5215 of variable Tab.
5216
5217 @item -gnatww
5218 @emph{Activate warnings on wrong low bound assumption.}
5219 @cindex @option{-gnatww} (@command{gcc})
5220 @cindex String indexing warnings
5221 This switch activates warnings for indexing an unconstrained string parameter
5222 with a literal or S'Length. This is a case where the code is assuming that the
5223 low bound is one, which is in general not true (for example when a slice is
5224 passed). The default is that such warnings are generated.
5225 This warning can also be turned on using @option{-gnatwa}.
5226
5227 @item -gnatwW
5228 @emph{Suppress warnings on wrong low bound assumption.}
5229 @cindex @option{-gnatwW} (@command{gcc})
5230 This switch activates warnings for indexing an unconstrained string parameter
5231 with a literal or S'Length. This warning can also be suppressed by providing
5232 an Assert pragma that checks the low bound, for example:
5233
5234 @smallexample @c ada
5235    procedure K (S : String) is
5236       pragma Assert (S'First = 1);
5237       @dots{}
5238 @end smallexample
5239
5240 @item -gnatwx
5241 @emph{Activate warnings on Export/Import pragmas.}
5242 @cindex @option{-gnatwx} (@command{gcc})
5243 @cindex Export/Import pragma warnings
5244 This switch activates warnings on Export/Import pragmas when
5245 the compiler detects a possible conflict between the Ada and
5246 foreign language calling sequences. For example, the use of
5247 default parameters in a convention C procedure is dubious
5248 because the C compiler cannot supply the proper default, so
5249 a warning is issued. The default is that such warnings are
5250 generated.
5251 This warning can also be turned on using @option{-gnatwa}.
5252
5253 @item -gnatwX
5254 @emph{Suppress warnings on Export/Import pragmas.}
5255 @cindex @option{-gnatwX} (@command{gcc})
5256 This switch suppresses warnings on Export/Import pragmas.
5257 The sense of this is that you are telling the compiler that
5258 you know what you are doing in writing the pragma, and it
5259 should not complain at you.
5260
5261 @item -gnatw.x
5262 @emph{Activate warnings for No_Exception_Propagation mode.}
5263 @cindex @option{-gnatwm} (@command{gcc})
5264 This switch activates warnings for exception usage when pragma Restrictions
5265 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5266 explicit exception raises which are not covered by a local handler, and for
5267 exception handlers which do not cover a local raise. The default is that these
5268 warnings are not given.
5269
5270 @item -gnatw.X
5271 @emph{Disable warnings for No_Exception_Propagation mode.}
5272 This switch disables warnings for exception usage when pragma Restrictions
5273 (No_Exception_Propagation) is in effect.
5274
5275 @item -gnatwy
5276 @emph{Activate warnings for Ada 2005 compatibility issues.}
5277 @cindex @option{-gnatwy} (@command{gcc})
5278 @cindex Ada 2005 compatibility issues warnings
5279 For the most part Ada 2005 is upwards compatible with Ada 95,
5280 but there are some exceptions (for example the fact that
5281 @code{interface} is now a reserved word in Ada 2005). This
5282 switch activates several warnings to help in identifying
5283 and correcting such incompatibilities. The default is that
5284 these warnings are generated. Note that at one point Ada 2005
5285 was called Ada 0Y, hence the choice of character.
5286 This warning can also be turned on using @option{-gnatwa}.
5287
5288 @item -gnatwY
5289 @emph{Disable warnings for Ada 2005 compatibility issues.}
5290 @cindex @option{-gnatwY} (@command{gcc})
5291 @cindex Ada 2005 compatibility issues warnings
5292 This switch suppresses several warnings intended to help in identifying
5293 incompatibilities between Ada 95 and Ada 2005.
5294
5295 @item -gnatwz
5296 @emph{Activate warnings on unchecked conversions.}
5297 @cindex @option{-gnatwz} (@command{gcc})
5298 @cindex Unchecked_Conversion warnings
5299 This switch activates warnings for unchecked conversions
5300 where the types are known at compile time to have different
5301 sizes. The default
5302 is that such warnings are generated.
5303 This warning can also be turned on using @option{-gnatwa}.
5304
5305 @item -gnatwZ
5306 @emph{Suppress warnings on unchecked conversions.}
5307 @cindex @option{-gnatwZ} (@command{gcc})
5308 This switch suppresses warnings for unchecked conversions
5309 where the types are known at compile time to have different
5310 sizes.
5311
5312 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5313 @cindex @option{-Wuninitialized}
5314 The warnings controlled by the @option{-gnatw} switch are generated by the
5315 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
5316 can provide additional warnings. One such useful warning is provided by
5317 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
5318 conjunction with turning on optimization mode. This causes the flow
5319 analysis circuits of the back end optimizer to output additional
5320 warnings about uninitialized variables.
5321
5322 @item ^-w^/NO_BACK_END_WARNINGS^
5323 @cindex @option{-w}
5324 This switch suppresses warnings from the @option{^gcc^GCC^} back end. The
5325 code generator detects a number of warning situations that are missed
5326 by the @option{GNAT} front end, and this switch can be used to suppress them.
5327 The use of this switch also sets the default front end warning mode to
5328 @option{-gnatws}, that is, front end warnings suppressed as well.
5329
5330 @end table
5331
5332 @noindent
5333 @ifclear vms
5334 A string of warning parameters can be used in the same parameter. For example:
5335
5336 @smallexample
5337 -gnatwaLe
5338 @end smallexample
5339
5340 @noindent
5341 will turn on all optional warnings except for elaboration pragma warnings,
5342 and also specify that warnings should be treated as errors.
5343 @end ifclear
5344 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5345
5346 @table @option
5347 @c !sort!
5348 @item -gnatwC
5349 @item -gnatwD
5350 @item -gnatwF
5351 @item -gnatwg
5352 @item -gnatwH
5353 @item -gnatwi
5354 @item -gnatwJ
5355 @item -gnatwK
5356 @item -gnatwL
5357 @item -gnatwM
5358 @item -gnatwn
5359 @item -gnatwo
5360 @item -gnatwP
5361 @item -gnatwR
5362 @item -gnatwU
5363 @item -gnatwv
5364 @item -gnatwz
5365 @item -gnatwx
5366
5367 @end table
5368
5369 @node Debugging and Assertion Control
5370 @subsection Debugging and Assertion Control
5371
5372 @table @option
5373 @item -gnata
5374 @cindex @option{-gnata} (@command{gcc})
5375 @findex Assert
5376 @findex Debug
5377 @cindex Assertions
5378
5379 @noindent
5380 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5381 are ignored. This switch, where @samp{a} stands for assert, causes
5382 @code{Assert} and @code{Debug} pragmas to be activated.
5383
5384 The pragmas have the form:
5385
5386 @smallexample
5387 @cartouche
5388    @b{pragma} Assert (@var{Boolean-expression} [,
5389                       @var{static-string-expression}])
5390    @b{pragma} Debug (@var{procedure call})
5391 @end cartouche
5392 @end smallexample
5393
5394 @noindent
5395 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5396 If the result is @code{True}, the pragma has no effect (other than
5397 possible side effects from evaluating the expression). If the result is
5398 @code{False}, the exception @code{Assert_Failure} declared in the package
5399 @code{System.Assertions} is
5400 raised (passing @var{static-string-expression}, if present, as the
5401 message associated with the exception). If no string expression is
5402 given the default is a string giving the file name and line number
5403 of the pragma.
5404
5405 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5406 @code{pragma Debug} may appear within a declaration sequence, allowing
5407 debugging procedures to be called between declarations.
5408
5409 @ifset vms
5410 @item /DEBUG[=debug-level]
5411 @itemx  /NODEBUG
5412 Specifies how much debugging information is to be included in
5413 the resulting object file where 'debug-level' is one of the following:
5414 @table @code
5415 @item   TRACEBACK
5416 Include both debugger symbol records and traceback
5417 the object file.
5418 This is the default setting.
5419 @item   ALL
5420 Include both debugger symbol records and traceback in
5421 object file.
5422 @item   NONE
5423 Excludes both debugger symbol records and traceback
5424 the object file. Same as /NODEBUG.
5425 @item   SYMBOLS
5426 Includes only debugger symbol records in the object
5427 file. Note that this doesn't include traceback information.
5428 @end table
5429 @end ifset
5430 @end table
5431
5432 @node Validity Checking
5433 @subsection Validity Checking
5434 @findex Validity Checking
5435
5436 @noindent
5437 The Ada Reference Manual has specific requirements for checking
5438 for invalid values. In particular, RM 13.9.1 requires that the
5439 evaluation of invalid values (for example from unchecked conversions),
5440 not result in erroneous execution. In GNAT, the result of such an
5441 evaluation in normal default mode is to either use the value
5442 unmodified, or to raise Constraint_Error in those cases where use
5443 of the unmodified value would cause erroneous execution. The cases
5444 where unmodified values might lead to erroneous execution are case
5445 statements (where a wild jump might result from an invalid value),
5446 and subscripts on the left hand side (where memory corruption could
5447 occur as a result of an invalid value).
5448
5449 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5450 checking mode.
5451 @ifclear vms
5452 The @code{x} argument is a string of letters that
5453 indicate validity checks that are performed or not performed in addition
5454 to the default checks described above.
5455 @end ifclear
5456 @ifset vms
5457 The options allowed for this qualifier
5458 indicate validity checks that are performed or not performed in addition
5459 to the default checks described above.
5460 @end ifset
5461
5462 @table @option
5463 @c !sort!
5464 @item -gnatVa
5465 @emph{All validity checks.}
5466 @cindex @option{-gnatVa} (@command{gcc})
5467 All validity checks are turned on.
5468 @ifclear vms
5469 That is, @option{-gnatVa} is
5470 equivalent to @option{gnatVcdfimorst}.
5471 @end ifclear
5472
5473 @item -gnatVc
5474 @emph{Validity checks for copies.}
5475 @cindex @option{-gnatVc} (@command{gcc})
5476 The right hand side of assignments, and the initializing values of
5477 object declarations are validity checked.
5478
5479 @item -gnatVd
5480 @emph{Default (RM) validity checks.}
5481 @cindex @option{-gnatVd} (@command{gcc})
5482 Some validity checks are done by default following normal Ada semantics
5483 (RM 13.9.1 (9-11)).
5484 A check is done in case statements that the expression is within the range
5485 of the subtype. If it is not, Constraint_Error is raised.
5486 For assignments to array components, a check is done that the expression used
5487 as index is within the range. If it is not, Constraint_Error is raised.
5488 Both these validity checks may be turned off using switch @option{-gnatVD}.
5489 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5490 switch @option{-gnatVd} will leave the checks turned on.
5491 Switch @option{-gnatVD} should be used only if you are sure that all such
5492 expressions have valid values. If you use this switch and invalid values
5493 are present, then the program is erroneous, and wild jumps or memory
5494 overwriting may occur.
5495
5496 @item -gnatVe
5497 @emph{Validity checks for elementary components.}
5498 @cindex @option{-gnatVe} (@command{gcc})
5499 In the absence of this switch, assignments to record or array components are
5500 not validity checked, even if validity checks for assignments generally
5501 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5502 require valid data, but assignment of individual components does. So for
5503 example, there is a difference between copying the elements of an array with a
5504 slice assignment, compared to assigning element by element in a loop. This
5505 switch allows you to turn off validity checking for components, even when they
5506 are assigned component by component.
5507
5508 @item -gnatVf
5509 @emph{Validity checks for floating-point values.}
5510 @cindex @option{-gnatVf} (@command{gcc})
5511 In the absence of this switch, validity checking occurs only for discrete
5512 values. If @option{-gnatVf} is specified, then validity checking also applies
5513 for floating-point values, and NaNs and infinities are considered invalid,
5514 as well as out of range values for constrained types. Note that this means
5515 that standard IEEE infinity mode is not allowed. The exact contexts
5516 in which floating-point values are checked depends on the setting of other
5517 options. For example,
5518 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5519 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5520 (the order does not matter) specifies that floating-point parameters of mode
5521 @code{in} should be validity checked.
5522
5523 @item -gnatVi
5524 @emph{Validity checks for @code{in} mode parameters}
5525 @cindex @option{-gnatVi} (@command{gcc})
5526 Arguments for parameters of mode @code{in} are validity checked in function
5527 and procedure calls at the point of call.
5528
5529 @item -gnatVm
5530 @emph{Validity checks for @code{in out} mode parameters.}
5531 @cindex @option{-gnatVm} (@command{gcc})
5532 Arguments for parameters of mode @code{in out} are validity checked in
5533 procedure calls at the point of call. The @code{'m'} here stands for
5534 modify, since this concerns parameters that can be modified by the call.
5535 Note that there is no specific option to test @code{out} parameters,
5536 but any reference within the subprogram will be tested in the usual
5537 manner, and if an invalid value is copied back, any reference to it
5538 will be subject to validity checking.
5539
5540 @item -gnatVn
5541 @emph{No validity checks.}
5542 @cindex @option{-gnatVn} (@command{gcc})
5543 This switch turns off all validity checking, including the default checking
5544 for case statements and left hand side subscripts. Note that the use of
5545 the switch @option{-gnatp} suppresses all run-time checks, including
5546 validity checks, and thus implies @option{-gnatVn}. When this switch
5547 is used, it cancels any other @option{-gnatV} previously issued.
5548
5549 @item -gnatVo
5550 @emph{Validity checks for operator and attribute operands.}
5551 @cindex @option{-gnatVo} (@command{gcc})
5552 Arguments for predefined operators and attributes are validity checked.
5553 This includes all operators in package @code{Standard},
5554 the shift operators defined as intrinsic in package @code{Interfaces}
5555 and operands for attributes such as @code{Pos}. Checks are also made
5556 on individual component values for composite comparisons, and on the
5557 expressions in type conversions and qualified expressions. Checks are
5558 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
5559
5560 @item -gnatVp
5561 @emph{Validity checks for parameters.}
5562 @cindex @option{-gnatVp} (@command{gcc})
5563 This controls the treatment of parameters within a subprogram (as opposed
5564 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5565 of parameters on a call. If either of these call options is used, then
5566 normally an assumption is made within a subprogram that the input arguments
5567 have been validity checking at the point of call, and do not need checking
5568 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5569 is not made, and parameters are not assumed to be valid, so their validity
5570 will be checked (or rechecked) within the subprogram.
5571
5572 @item -gnatVr
5573 @emph{Validity checks for function returns.}
5574 @cindex @option{-gnatVr} (@command{gcc})
5575 The expression in @code{return} statements in functions is validity
5576 checked.
5577
5578 @item -gnatVs
5579 @emph{Validity checks for subscripts.}
5580 @cindex @option{-gnatVs} (@command{gcc})
5581 All subscripts expressions are checked for validity, whether they appear
5582 on the right side or left side (in default mode only left side subscripts
5583 are validity checked).
5584
5585 @item -gnatVt
5586 @emph{Validity checks for tests.}
5587 @cindex @option{-gnatVt} (@command{gcc})
5588 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5589 statements are checked, as well as guard expressions in entry calls.
5590
5591 @end table
5592
5593 @noindent
5594 The @option{-gnatV} switch may be followed by
5595 ^a string of letters^a list of options^
5596 to turn on a series of validity checking options.
5597 For example,
5598 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5599 specifies that in addition to the default validity checking, copies and
5600 function return expressions are to be validity checked.
5601 In order to make it easier
5602 to specify the desired combination of effects,
5603 @ifclear vms
5604 the upper case letters @code{CDFIMORST} may
5605 be used to turn off the corresponding lower case option.
5606 @end ifclear
5607 @ifset vms
5608 the prefix @code{NO} on an option turns off the corresponding validity
5609 checking:
5610 @itemize @bullet
5611 @item @code{NOCOPIES}
5612 @item @code{NODEFAULT}
5613 @item @code{NOFLOATS}
5614 @item @code{NOIN_PARAMS}
5615 @item @code{NOMOD_PARAMS}
5616 @item @code{NOOPERANDS}
5617 @item @code{NORETURNS}
5618 @item @code{NOSUBSCRIPTS}
5619 @item @code{NOTESTS}
5620 @end itemize
5621 @end ifset
5622 Thus
5623 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5624 turns on all validity checking options except for
5625 checking of @code{@b{in out}} procedure arguments.
5626
5627 The specification of additional validity checking generates extra code (and
5628 in the case of @option{-gnatVa} the code expansion can be substantial.
5629 However, these additional checks can be very useful in detecting
5630 uninitialized variables, incorrect use of unchecked conversion, and other
5631 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5632 is useful in conjunction with the extra validity checking, since this
5633 ensures that wherever possible uninitialized variables have invalid values.
5634
5635 See also the pragma @code{Validity_Checks} which allows modification of
5636 the validity checking mode at the program source level, and also allows for
5637 temporary disabling of validity checks.
5638
5639 @node Style Checking
5640 @subsection Style Checking
5641 @findex Style checking
5642
5643 @noindent
5644 The @option{-gnaty^x^(option,option,@dots{})^} switch
5645 @cindex @option{-gnaty} (@command{gcc})
5646 causes the compiler to
5647 enforce specified style rules. A limited set of style rules has been used
5648 in writing the GNAT sources themselves. This switch allows user programs
5649 to activate all or some of these checks. If the source program fails a
5650 specified style check, an appropriate warning message is given, preceded by
5651 the character sequence ``(style)''.
5652 @ifset vms
5653 @code{(option,option,@dots{})} is a sequence of keywords
5654 @end ifset
5655 @ifclear vms
5656 The string @var{x} is a sequence of letters or digits
5657 @end ifclear
5658 indicating the particular style
5659 checks to be performed. The following checks are defined:
5660
5661 @table @option
5662 @c !sort!
5663 @item 1-9
5664 @emph{Specify indentation level.}
5665 If a digit from 1-9 appears
5666 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5667 then proper indentation is checked, with the digit indicating the
5668 indentation level required.
5669 The general style of required indentation is as specified by
5670 the examples in the Ada Reference Manual. Full line comments must be
5671 aligned with the @code{--} starting on a column that is a multiple of
5672 the alignment level, or they may be aligned the same way as the following
5673 non-blank line (this is useful when full line comments appear in the middle
5674 of a statement.
5675
5676 @item ^a^ATTRIBUTE^
5677 @emph{Check attribute casing.}
5678 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5679 then attribute names, including the case of keywords such as @code{digits}
5680 used as attributes names, must be written in mixed case, that is, the
5681 initial letter and any letter following an underscore must be uppercase.
5682 All other letters must be lowercase.
5683
5684 @item ^A^ARRAY_INDEXES^
5685 @emph{Use of array index numbers in array attributes.}
5686 If the ^letter A^word ARRAY_INDEXES^ appears in the string after
5687 @option{-gnaty} then when using the array attributes First, Last, Range,
5688 or Length, the index number must be omitted for one-dimensional arrays
5689 and is required for multi-dimensional arrays.
5690
5691 @item ^b^BLANKS^
5692 @emph{Blanks not allowed at statement end.}
5693 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5694 trailing blanks are not allowed at the end of statements. The purpose of this
5695 rule, together with h (no horizontal tabs), is to enforce a canonical format
5696 for the use of blanks to separate source tokens.
5697
5698 @item ^c^COMMENTS^
5699 @emph{Check comments.}
5700 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5701 then comments must meet the following set of rules:
5702
5703 @itemize @bullet
5704
5705 @item
5706 The ``@code{--}'' that starts the column must either start in column one,
5707 or else at least one blank must precede this sequence.
5708
5709 @item
5710 Comments that follow other tokens on a line must have at least one blank
5711 following the ``@code{--}'' at the start of the comment.
5712
5713 @item
5714 Full line comments must have two blanks following the ``@code{--}'' that
5715 starts the comment, with the following exceptions.
5716
5717 @item
5718 A line consisting only of the ``@code{--}'' characters, possibly preceded
5719 by blanks is permitted.
5720
5721 @item
5722 A comment starting with ``@code{--x}'' where @code{x} is a special character
5723 is permitted.
5724 This allows proper processing of the output generated by specialized tools
5725 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5726 annotation
5727 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5728 special character is defined as being in one of the ASCII ranges
5729 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
5730 Note that this usage is not permitted
5731 in GNAT implementation units (i.e., when @option{-gnatg} is used).
5732
5733 @item
5734 A line consisting entirely of minus signs, possibly preceded by blanks, is
5735 permitted. This allows the construction of box comments where lines of minus
5736 signs are used to form the top and bottom of the box.
5737
5738 @item
5739 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5740 least one blank follows the initial ``@code{--}''. Together with the preceding
5741 rule, this allows the construction of box comments, as shown in the following
5742 example:
5743 @smallexample
5744 ---------------------------
5745 -- This is a box comment --
5746 -- with two text lines.  --
5747 ---------------------------
5748 @end smallexample
5749 @end itemize
5750
5751 @item ^d^DOS_LINE_ENDINGS^
5752 @emph{Check no DOS line terminators present.}
5753 If the ^letter d^word DOS_LINE_ENDINGS^ appears in the string after
5754 @option{-gnaty} then all lines must be terminated by a single ASCII.LF
5755 character (in particular the DOS line terminator sequence CR/LF is not
5756 allowed).
5757
5758 @item ^e^END^
5759 @emph{Check end/exit labels.}
5760 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5761 optional labels on @code{end} statements ending subprograms and on
5762 @code{exit} statements exiting named loops, are required to be present.
5763
5764 @item ^f^VTABS^
5765 @emph{No form feeds or vertical tabs.}
5766 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5767 neither form feeds nor vertical tab characters are permitted
5768 in the source text.
5769
5770 @item ^g^GNAT^
5771 @emph{GNAT style mode}
5772 If the ^letter g^word GNAT^ appears in the string after @option{-gnaty} then
5773 the set of style check switches is set to match that used by the GNAT sources.
5774 This may be useful when developing code that is eventually intended to be
5775 incorporated into GNAT. For further details, see GNAT sources.
5776
5777 @item ^h^HTABS^
5778 @emph{No horizontal tabs.}
5779 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5780 horizontal tab characters are not permitted in the source text.
5781 Together with the b (no blanks at end of line) check, this
5782 enforces a canonical form for the use of blanks to separate
5783 source tokens.
5784
5785 @item ^i^IF_THEN^
5786 @emph{Check if-then layout.}
5787 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5788 then the keyword @code{then} must appear either on the same
5789 line as corresponding @code{if}, or on a line on its own, lined
5790 up under the @code{if} with at least one non-blank line in between
5791 containing all or part of the condition to be tested.
5792
5793 @item ^I^IN_MODE^
5794 @emph{check mode IN keywords}
5795 If the ^letter I (upper case)^word IN_MODE^ appears in the string
5796 after @option{-gnaty} then mode @code{in} (the default mode) is not
5797 allowed to be given explicitly. @code{in out} is fine,
5798 but not @code{in} on its own.
5799
5800 @item ^k^KEYWORD^
5801 @emph{Check keyword casing.}
5802 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5803 all keywords must be in lower case (with the exception of keywords
5804 such as @code{digits} used as attribute names to which this check
5805 does not apply).
5806
5807 @item ^l^LAYOUT^
5808 @emph{Check layout.}
5809 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5810 layout of statement and declaration constructs must follow the
5811 recommendations in the Ada Reference Manual, as indicated by the
5812 form of the syntax rules. For example an @code{else} keyword must
5813 be lined up with the corresponding @code{if} keyword.
5814
5815 There are two respects in which the style rule enforced by this check
5816 option are more liberal than those in the Ada Reference Manual. First
5817 in the case of record declarations, it is permissible to put the
5818 @code{record} keyword on the same line as the @code{type} keyword, and
5819 then the @code{end} in @code{end record} must line up under @code{type}.
5820 This is also permitted when the type declaration is split on two lines.
5821 For example, any of the following three layouts is acceptable:
5822
5823 @smallexample @c ada
5824 @cartouche
5825 type q is 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 type q is
5837    record
5838       a : integer;
5839       b : integer;
5840 end record;
5841
5842 @end cartouche
5843 @end smallexample
5844
5845 @noindent
5846 Second, in the case of a block statement, a permitted alternative
5847 is to put the block label on the same line as the @code{declare} or
5848 @code{begin} keyword, and then line the @code{end} keyword up under
5849 the block label. For example both the following are permitted:
5850
5851 @smallexample @c ada
5852 @cartouche
5853 Block : declare
5854    A : Integer := 3;
5855 begin
5856    Proc (A, A);
5857 end Block;
5858
5859 Block :
5860    declare
5861       A : Integer := 3;
5862    begin
5863       Proc (A, A);
5864    end Block;
5865 @end cartouche
5866 @end smallexample
5867
5868 @noindent
5869 The same alternative format is allowed for loops. For example, both of
5870 the following are permitted:
5871
5872 @smallexample @c ada
5873 @cartouche
5874 Clear : while J < 10 loop
5875    A (J) := 0;
5876 end loop Clear;
5877
5878 Clear :
5879    while J < 10 loop
5880       A (J) := 0;
5881    end loop Clear;
5882 @end cartouche
5883 @end smallexample
5884
5885 @item ^Lnnn^MAX_NESTING=nnn^
5886 @emph{Set maximum nesting level}
5887 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5888 the range 0-999, appears in the string after @option{-gnaty} then the
5889 maximum level of nesting of constructs (including subprograms, loops,
5890 blocks, packages, and conditionals) may not exceed the given value. A
5891 value of zero disconnects this style check.
5892
5893 @item ^m^LINE_LENGTH^
5894 @emph{Check maximum line length.}
5895 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5896 then the length of source lines must not exceed 79 characters, including
5897 any trailing blanks. The value of 79 allows convenient display on an
5898 80 character wide device or window, allowing for possible special
5899 treatment of 80 character lines. Note that this count is of
5900 characters in the source text. This means that a tab character counts
5901 as one character in this count but a wide character sequence counts as
5902 a single character (however many bytes are needed in the encoding).
5903
5904 @item ^Mnnn^MAX_LENGTH=nnn^
5905 @emph{Set maximum line length.}
5906 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5907 the string after @option{-gnaty} then the length of lines must not exceed the
5908 given value. The maximum value that can be specified is 32767.
5909
5910 @item ^n^STANDARD_CASING^
5911 @emph{Check casing of entities in Standard.}
5912 If the ^letter n^word STANDARD_CASING^ appears in the string
5913 after @option{-gnaty} then any identifier from Standard must be cased
5914 to match the presentation in the Ada Reference Manual (for example,
5915 @code{Integer} and @code{ASCII.NUL}).
5916
5917 @item ^o^ORDERED_SUBPROGRAMS^
5918 @emph{Check order of subprogram bodies.}
5919 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5920 after @option{-gnaty} then all subprogram bodies in a given scope
5921 (e.g.@: a package body) must be in alphabetical order. The ordering
5922 rule uses normal Ada rules for comparing strings, ignoring casing
5923 of letters, except that if there is a trailing numeric suffix, then
5924 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
5925 before Junk10).
5926
5927 @item ^p^PRAGMA^
5928 @emph{Check pragma casing.}
5929 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5930 pragma names must be written in mixed case, that is, the
5931 initial letter and any letter following an underscore must be uppercase.
5932 All other letters must be lowercase.
5933
5934 @item ^r^REFERENCES^
5935 @emph{Check references.}
5936 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5937 then all identifier references must be cased in the same way as the
5938 corresponding declaration. No specific casing style is imposed on
5939 identifiers. The only requirement is for consistency of references
5940 with declarations.
5941
5942 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
5943 @emph{Check no statements after THEN/ELSE.}
5944 If the ^letter S^word STATEMENTS_AFTER_THEN_ELSE^ appears in the
5945 string after @option{-gnaty} then it is not permitted to write any
5946 statements on the same line as a THEN OR ELSE keyword following the
5947 keyword in an IF statement. OR ELSE and AND THEN are not affected,
5948 and a special exception allows a pragma to appear after ELSE.
5949
5950 @item ^s^SPECS^
5951 @emph{Check separate specs.}
5952 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5953 separate declarations (``specs'') are required for subprograms (a
5954 body is not allowed to serve as its own declaration). The only
5955 exception is that parameterless library level procedures are
5956 not required to have a separate declaration. This exception covers
5957 the most frequent form of main program procedures.
5958
5959 @item ^t^TOKEN^
5960 @emph{Check token spacing.}
5961 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5962 the following token spacing rules are enforced:
5963
5964 @itemize @bullet
5965
5966 @item
5967 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5968
5969 @item
5970 The token @code{=>} must be surrounded by spaces.
5971
5972 @item
5973 The token @code{<>} must be preceded by a space or a left parenthesis.
5974
5975 @item
5976 Binary operators other than @code{**} must be surrounded by spaces.
5977 There is no restriction on the layout of the @code{**} binary operator.
5978
5979 @item
5980 Colon must be surrounded by spaces.
5981
5982 @item
5983 Colon-equal (assignment, initialization) must be surrounded by spaces.
5984
5985 @item
5986 Comma must be the first non-blank character on the line, or be
5987 immediately preceded by a non-blank character, and must be followed
5988 by a space.
5989
5990 @item
5991 If the token preceding a left parenthesis ends with a letter or digit, then
5992 a space must separate the two tokens.
5993
5994 @item
5995 A right parenthesis must either be the first non-blank character on
5996 a line, or it must be preceded by a non-blank character.
5997
5998 @item
5999 A semicolon must not be preceded by a space, and must not be followed by
6000 a non-blank character.
6001
6002 @item
6003 A unary plus or minus may not be followed by a space.
6004
6005 @item
6006 A vertical bar must be surrounded by spaces.
6007 @end itemize
6008
6009 @item ^u^UNNECESSARY_BLANK_LINES^
6010 @emph{Check unnecessary blank lines.}
6011 Check for unnecessary blank lines. A blank line is considered
6012 unnecessary if it appears at the end of the file, or if more than
6013 one blank line occurs in sequence.
6014
6015 @item ^x^XTRA_PARENS^
6016 @emph{Check extra parentheses.}
6017 Check for the use of an unnecessary extra level of parentheses (C-style)
6018 around conditions in @code{if} statements, @code{while} statements and
6019 @code{exit} statements.
6020
6021 @end table
6022
6023 @noindent
6024 In the above rules, appearing in column one is always permitted, that is,
6025 counts as meeting either a requirement for a required preceding space,
6026 or as meeting a requirement for no preceding space.
6027
6028 Appearing at the end of a line is also always permitted, that is, counts
6029 as meeting either a requirement for a following space, or as meeting
6030 a requirement for no following space.
6031
6032 @noindent
6033 If any of these style rules is violated, a message is generated giving
6034 details on the violation. The initial characters of such messages are
6035 always ``@code{(style)}''. Note that these messages are treated as warning
6036 messages, so they normally do not prevent the generation of an object
6037 file. The @option{-gnatwe} switch can be used to treat warning messages,
6038 including style messages, as fatal errors.
6039
6040 The switch
6041 @ifclear vms
6042 @option{-gnaty} on its own (that is not
6043 followed by any letters or digits),
6044 is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6045 options enabled with the exception of @option{-gnatyo},
6046 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6047 @end ifclear
6048 @ifset vms
6049 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6050 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6051 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6052 @end ifset
6053 an indentation level of 3 is set. This is similar to the standard
6054 checking option that is used for the GNAT sources.
6055
6056 The switch
6057 @ifclear vms
6058 @option{-gnatyN}
6059 @end ifclear
6060 @ifset vms
6061 /STYLE_CHECKS=NONE
6062 @end ifset
6063 clears any previously set style checks.
6064
6065 @node Run-Time Checks
6066 @subsection Run-Time Checks
6067 @cindex Division by zero
6068 @cindex Access before elaboration
6069 @cindex Checks, division by zero
6070 @cindex Checks, access before elaboration
6071 @cindex Checks, stack overflow checking
6072
6073 @noindent
6074 If you compile with the default options, GNAT will insert many run-time
6075 checks into the compiled code, including code that performs range
6076 checking against constraints, but not arithmetic overflow checking for
6077 integer operations (including division by zero), checks for access
6078 before elaboration on subprogram calls, or stack overflow checking. All
6079 other run-time checks, as required by the Ada Reference Manual, are
6080 generated by default. The following @command{gcc} switches refine this
6081 default behavior:
6082
6083 @table @option
6084 @c !sort!
6085 @item -gnatp
6086 @cindex @option{-gnatp} (@command{gcc})
6087 @cindex Suppressing checks
6088 @cindex Checks, suppressing
6089 @findex Suppress
6090 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
6091 had been present in the source. Validity checks are also suppressed (in
6092 other words @option{-gnatp} also implies @option{-gnatVn}.
6093 Use this switch to improve the performance
6094 of the code at the expense of safety in the presence of invalid data or
6095 program bugs.
6096
6097 @item -gnato
6098 @cindex @option{-gnato} (@command{gcc})
6099 @cindex Overflow checks
6100 @cindex Check, overflow
6101 Enables overflow checking for integer operations.
6102 This causes GNAT to generate slower and larger executable
6103 programs by adding code to check for overflow (resulting in raising
6104 @code{Constraint_Error} as required by standard Ada
6105 semantics). These overflow checks correspond to situations in which
6106 the true value of the result of an operation may be outside the base
6107 range of the result type. The following example shows the distinction:
6108
6109 @smallexample @c ada
6110 X1 : Integer := Integer'Last;
6111 X2 : Integer range 1 .. 5 := 5;
6112 X3 : Integer := Integer'Last;
6113 X4 : Integer range 1 .. 5 := 5;
6114 F  : Float := 2.0E+20;
6115 @dots{}
6116 X1 := X1 + 1;
6117 X2 := X2 + 1;
6118 X3 := Integer (F);
6119 X4 := Integer (F);
6120 @end smallexample
6121
6122 @noindent
6123 Here the first addition results in a value that is outside the base range
6124 of Integer, and hence requires an overflow check for detection of the
6125 constraint error. Thus the first assignment to @code{X1} raises a
6126 @code{Constraint_Error} exception only if @option{-gnato} is set.
6127
6128 The second increment operation results in a violation
6129 of the explicit range constraint, and such range checks are always
6130 performed (unless specifically suppressed with a pragma @code{suppress}
6131 or the use of @option{-gnatp}).
6132
6133 The two conversions of @code{F} both result in values that are outside
6134 the base range of type @code{Integer} and thus will raise
6135 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6136 The fact that the result of the second conversion is assigned to
6137 variable @code{X4} with a restricted range is irrelevant, since the problem
6138 is in the conversion, not the assignment.
6139
6140 Basically the rule is that in the default mode (@option{-gnato} not
6141 used), the generated code assures that all integer variables stay
6142 within their declared ranges, or within the base range if there is
6143 no declared range. This prevents any serious problems like indexes
6144 out of range for array operations.
6145
6146 What is not checked in default mode is an overflow that results in
6147 an in-range, but incorrect value. In the above example, the assignments
6148 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6149 range of the target variable, but the result is wrong in the sense that
6150 it is too large to be represented correctly. Typically the assignment
6151 to @code{X1} will result in wrap around to the largest negative number.
6152 The conversions of @code{F} will result in some @code{Integer} value
6153 and if that integer value is out of the @code{X4} range then the
6154 subsequent assignment would generate an exception.
6155
6156 @findex Machine_Overflows
6157 Note that the @option{-gnato} switch does not affect the code generated
6158 for any floating-point operations; it applies only to integer
6159 semantics).
6160 For floating-point, GNAT has the @code{Machine_Overflows}
6161 attribute set to @code{False} and the normal mode of operation is to
6162 generate IEEE NaN and infinite values on overflow or invalid operations
6163 (such as dividing 0.0 by 0.0).
6164
6165 The reason that we distinguish overflow checking from other kinds of
6166 range constraint checking is that a failure of an overflow check can
6167 generate an incorrect value, but cannot cause erroneous behavior. This
6168 is unlike the situation with a constraint check on an array subscript,
6169 where failure to perform the check can result in random memory description,
6170 or the range check on a case statement, where failure to perform the check
6171 can cause a wild jump.
6172
6173 Note again that @option{-gnato} is off by default, so overflow checking is
6174 not performed in default mode. This means that out of the box, with the
6175 default settings, GNAT does not do all the checks expected from the
6176 language description in the Ada Reference Manual. If you want all constraint
6177 checks to be performed, as described in this Manual, then you must
6178 explicitly use the -gnato switch either on the @command{gnatmake} or
6179 @command{gcc} command.
6180
6181 @item -gnatE
6182 @cindex @option{-gnatE} (@command{gcc})
6183 @cindex Elaboration checks
6184 @cindex Check, elaboration
6185 Enables dynamic checks for access-before-elaboration
6186 on subprogram calls and generic instantiations.
6187 For full details of the effect and use of this switch,
6188 @xref{Compiling Using gcc}.
6189
6190 @item -fstack-check
6191 @cindex @option{-fstack-check} (@command{gcc})
6192 @cindex Stack Overflow Checking
6193 @cindex Checks, stack overflow checking
6194 Activates stack overflow checking. For full details of the effect and use of
6195 this switch see @ref{Stack Overflow Checking}.
6196 @end table
6197
6198 @findex Unsuppress
6199 @noindent
6200 The setting of these switches only controls the default setting of the
6201 checks. You may modify them using either @code{Suppress} (to remove
6202 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6203 the program source.
6204
6205 @node Using gcc for Syntax Checking
6206 @subsection Using @command{gcc} for Syntax Checking
6207 @table @option
6208 @item -gnats
6209 @cindex @option{-gnats} (@command{gcc})
6210 @ifclear vms
6211
6212 @noindent
6213 The @code{s} stands for ``syntax''.
6214 @end ifclear
6215
6216 Run GNAT in syntax checking only mode. For
6217 example, the command
6218
6219 @smallexample
6220 $ gcc -c -gnats x.adb
6221 @end smallexample
6222
6223 @noindent
6224 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6225 series of files in a single command
6226 @ifclear vms
6227 , and can use wild cards to specify such a group of files.
6228 Note that you must specify the @option{-c} (compile
6229 only) flag in addition to the @option{-gnats} flag.
6230 @end ifclear
6231 .
6232 You may use other switches in conjunction with @option{-gnats}. In
6233 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6234 format of any generated error messages.
6235
6236 When the source file is empty or contains only empty lines and/or comments,
6237 the output is a warning:
6238
6239 @smallexample
6240 $ gcc -c -gnats -x ada toto.txt
6241 toto.txt:1:01: warning: empty file, contains no compilation units
6242 $
6243 @end smallexample
6244
6245 Otherwise, the output is simply the error messages, if any. No object file or
6246 ALI file is generated by a syntax-only compilation. Also, no units other
6247 than the one specified are accessed. For example, if a unit @code{X}
6248 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6249 check only mode does not access the source file containing unit
6250 @code{Y}.
6251
6252 @cindex Multiple units, syntax checking
6253 Normally, GNAT allows only a single unit in a source file. However, this
6254 restriction does not apply in syntax-check-only mode, and it is possible
6255 to check a file containing multiple compilation units concatenated
6256 together. This is primarily used by the @code{gnatchop} utility
6257 (@pxref{Renaming Files Using gnatchop}).
6258 @end table
6259
6260 @node Using gcc for Semantic Checking
6261 @subsection Using @command{gcc} for Semantic Checking
6262 @table @option
6263 @item -gnatc
6264 @cindex @option{-gnatc} (@command{gcc})
6265
6266 @ifclear vms
6267 @noindent
6268 The @code{c} stands for ``check''.
6269 @end ifclear
6270 Causes the compiler to operate in semantic check mode,
6271 with full checking for all illegalities specified in the
6272 Ada Reference Manual, but without generation of any object code
6273 (no object file is generated).
6274
6275 Because dependent files must be accessed, you must follow the GNAT
6276 semantic restrictions on file structuring to operate in this mode:
6277
6278 @itemize @bullet
6279 @item
6280 The needed source files must be accessible
6281 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6282
6283 @item
6284 Each file must contain only one compilation unit.
6285
6286 @item
6287 The file name and unit name must match (@pxref{File Naming Rules}).
6288 @end itemize
6289
6290 The output consists of error messages as appropriate. No object file is
6291 generated. An @file{ALI} file is generated for use in the context of
6292 cross-reference tools, but this file is marked as not being suitable
6293 for binding (since no object file is generated).
6294 The checking corresponds exactly to the notion of
6295 legality in the Ada Reference Manual.
6296
6297 Any unit can be compiled in semantics-checking-only mode, including
6298 units that would not normally be compiled (subunits,
6299 and specifications where a separate body is present).
6300 @end table
6301
6302 @node Compiling Different Versions of Ada
6303 @subsection Compiling Different Versions of Ada
6304
6305 @noindent
6306 The switches described in this section allow you to explicitly specify
6307 the version of the Ada language that your programs are written in.
6308 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6309 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6310 indicate Ada 83 compatibility mode.
6311
6312 @table @option
6313 @cindex Compatibility with Ada 83
6314
6315 @item -gnat83 (Ada 83 Compatibility Mode)
6316 @cindex @option{-gnat83} (@command{gcc})
6317 @cindex ACVC, Ada 83 tests
6318 @cindex Ada 83 mode
6319
6320 @noindent
6321 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6322 specifies that the program is to be compiled in Ada 83 mode. With
6323 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6324 semantics where this can be done easily.
6325 It is not possible to guarantee this switch does a perfect
6326 job; some subtle tests, such as are
6327 found in earlier ACVC tests (and that have been removed from the ACATS suite
6328 for Ada 95), might not compile correctly.
6329 Nevertheless, this switch may be useful in some circumstances, for example
6330 where, due to contractual reasons, existing code needs to be maintained
6331 using only Ada 83 features.
6332
6333 With few exceptions (most notably the need to use @code{<>} on
6334 @cindex Generic formal parameters
6335 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6336 reserved words, and the use of packages
6337 with optional bodies), it is not necessary to specify the
6338 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6339 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6340 a correct Ada 83 program is usually also a correct program
6341 in these later versions of the language standard.
6342 For further information, please refer to @ref{Compatibility and Porting Guide}.
6343
6344 @item -gnat95 (Ada 95 mode)
6345 @cindex @option{-gnat95} (@command{gcc})
6346 @cindex Ada 95 mode
6347
6348 @noindent
6349 This switch directs the compiler to implement the Ada 95 version of the
6350 language.
6351 Since Ada 95 is almost completely upwards
6352 compatible with Ada 83, Ada 83 programs may generally be compiled using
6353 this switch (see the description of the @option{-gnat83} switch for further
6354 information about Ada 83 mode).
6355 If an Ada 2005 program is compiled in Ada 95 mode,
6356 uses of the new Ada 2005 features will cause error
6357 messages or warnings.
6358
6359 This switch also can be used to cancel the effect of a previous
6360 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6361
6362 @item -gnat05 (Ada 2005 mode)
6363 @cindex @option{-gnat05} (@command{gcc})
6364 @cindex Ada 2005 mode
6365
6366 @noindent
6367 This switch directs the compiler to implement the Ada 2005 version of the
6368 language.
6369 Since Ada 2005 is almost completely upwards
6370 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6371 may generally be compiled using this switch (see the description of the
6372 @option{-gnat83} and @option{-gnat95} switches for further
6373 information).
6374
6375 For information about the approved ``Ada Issues'' that have been incorporated
6376 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6377 Included with GNAT releases is a file @file{features-ada0y} that describes
6378 the set of implemented Ada 2005 features.
6379 @end table
6380
6381
6382 @node Character Set Control
6383 @subsection Character Set Control
6384 @table @option
6385 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6386 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6387
6388 @noindent
6389 Normally GNAT recognizes the Latin-1 character set in source program
6390 identifiers, as described in the Ada Reference Manual.
6391 This switch causes
6392 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6393 single character ^^or word^ indicating the character set, as follows:
6394
6395 @table @code
6396 @item 1
6397 ISO 8859-1 (Latin-1) identifiers
6398
6399 @item 2
6400 ISO 8859-2 (Latin-2) letters allowed in identifiers
6401
6402 @item 3
6403 ISO 8859-3 (Latin-3) letters allowed in identifiers
6404
6405 @item 4
6406 ISO 8859-4 (Latin-4) letters allowed in identifiers
6407
6408 @item 5
6409 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6410
6411 @item 9
6412 ISO 8859-15 (Latin-9) letters allowed in identifiers
6413
6414 @item ^p^PC^
6415 IBM PC letters (code page 437) allowed in identifiers
6416
6417 @item ^8^PC850^
6418 IBM PC letters (code page 850) allowed in identifiers
6419
6420 @item ^f^FULL_UPPER^
6421 Full upper-half codes allowed in identifiers
6422
6423 @item ^n^NO_UPPER^
6424 No upper-half codes allowed in identifiers
6425
6426 @item ^w^WIDE^
6427 Wide-character codes (that is, codes greater than 255)
6428 allowed in identifiers
6429 @end table
6430
6431 @xref{Foreign Language Representation}, for full details on the
6432 implementation of these character sets.
6433
6434 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6435 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6436 Specify the method of encoding for wide characters.
6437 @var{e} is one of the following:
6438
6439 @table @code
6440
6441 @item ^h^HEX^
6442 Hex encoding (brackets coding also recognized)
6443
6444 @item ^u^UPPER^
6445 Upper half encoding (brackets encoding also recognized)
6446
6447 @item ^s^SHIFT_JIS^
6448 Shift/JIS encoding (brackets encoding also recognized)
6449
6450 @item ^e^EUC^
6451 EUC encoding (brackets encoding also recognized)
6452
6453 @item ^8^UTF8^
6454 UTF-8 encoding (brackets encoding also recognized)
6455
6456 @item ^b^BRACKETS^
6457 Brackets encoding only (default value)
6458 @end table
6459 For full details on these encoding
6460 methods see @ref{Wide Character Encodings}.
6461 Note that brackets coding is always accepted, even if one of the other
6462 options is specified, so for example @option{-gnatW8} specifies that both
6463 brackets and UTF-8 encodings will be recognized. The units that are
6464 with'ed directly or indirectly will be scanned using the specified
6465 representation scheme, and so if one of the non-brackets scheme is
6466 used, it must be used consistently throughout the program. However,
6467 since brackets encoding is always recognized, it may be conveniently
6468 used in standard libraries, allowing these libraries to be used with
6469 any of the available coding schemes.
6470 scheme.
6471
6472 If no @option{-gnatW?} parameter is present, then the default
6473 representation is normally Brackets encoding only. However, if the
6474 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6475 byte order mark or BOM for UTF-8), then these three characters are
6476 skipped and the default representation for the file is set to UTF-8.
6477
6478 Note that the wide character representation that is specified (explicitly
6479 or by default) for the main program also acts as the default encoding used
6480 for Wide_Text_IO files if not specifically overridden by a WCEM form
6481 parameter.
6482
6483 @end table
6484 @node File Naming Control
6485 @subsection File Naming Control
6486
6487 @table @option
6488 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6489 @cindex @option{-gnatk} (@command{gcc})
6490 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6491 1-999, indicates the maximum allowable length of a file name (not
6492 including the @file{.ads} or @file{.adb} extension). The default is not
6493 to enable file name krunching.
6494
6495 For the source file naming rules, @xref{File Naming Rules}.
6496 @end table
6497
6498 @node Subprogram Inlining Control
6499 @subsection Subprogram Inlining Control
6500
6501 @table @option
6502 @c !sort!
6503 @item -gnatn
6504 @cindex @option{-gnatn} (@command{gcc})
6505 @ifclear vms
6506 The @code{n} here is intended to suggest the first syllable of the
6507 word ``inline''.
6508 @end ifclear
6509 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6510 inlining to actually occur, optimization must be enabled. To enable
6511 inlining of subprograms specified by pragma @code{Inline},
6512 you must also specify this switch.
6513 In the absence of this switch, GNAT does not attempt
6514 inlining and does not need to access the bodies of
6515 subprograms for which @code{pragma Inline} is specified if they are not
6516 in the current unit.
6517
6518 If you specify this switch the compiler will access these bodies,
6519 creating an extra source dependency for the resulting object file, and
6520 where possible, the call will be inlined.
6521 For further details on when inlining is possible
6522 see @ref{Inlining of Subprograms}.
6523
6524 @item -gnatN
6525 @cindex @option{-gnatN} (@command{gcc})
6526 The front end inlining activated by this switch is generally more extensive,
6527 and quite often more effective than the standard @option{-gnatn} inlining mode.
6528 It will also generate additional dependencies.
6529 Note that
6530 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6531 to specify both options.
6532 @end table
6533
6534 @node Auxiliary Output Control
6535 @subsection Auxiliary Output Control
6536
6537 @table @option
6538 @item -gnatt
6539 @cindex @option{-gnatt} (@command{gcc})
6540 @cindex Writing internal trees
6541 @cindex Internal trees, writing to file
6542 Causes GNAT to write the internal tree for a unit to a file (with the
6543 extension @file{.adt}.
6544 This not normally required, but is used by separate analysis tools.
6545 Typically
6546 these tools do the necessary compilations automatically, so you should
6547 not have to specify this switch in normal operation.
6548
6549 @item -gnatu
6550 @cindex @option{-gnatu} (@command{gcc})
6551 Print a list of units required by this compilation on @file{stdout}.
6552 The listing includes all units on which the unit being compiled depends
6553 either directly or indirectly.
6554
6555 @ifclear vms
6556 @item -pass-exit-codes
6557 @cindex @option{-pass-exit-codes} (@command{gcc})
6558 If this switch is not used, the exit code returned by @command{gcc} when
6559 compiling multiple files indicates whether all source files have
6560 been successfully used to generate object files or not.
6561
6562 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6563 exit status and allows an integrated development environment to better
6564 react to a compilation failure. Those exit status are:
6565
6566 @table @asis
6567 @item 5
6568 There was an error in at least one source file.
6569 @item 3
6570 At least one source file did not generate an object file.
6571 @item 2
6572 The compiler died unexpectedly (internal error for example).
6573 @item 0
6574 An object file has been generated for every source file.
6575 @end table
6576 @end ifclear
6577 @end table
6578
6579 @node Debugging Control
6580 @subsection Debugging Control
6581
6582 @table @option
6583 @c !sort!
6584 @cindex Debugging options
6585 @ifclear vms
6586 @item -gnatd@var{x}
6587 @cindex @option{-gnatd} (@command{gcc})
6588 Activate internal debugging switches. @var{x} is a letter or digit, or
6589 string of letters or digits, which specifies the type of debugging
6590 outputs desired. Normally these are used only for internal development
6591 or system debugging purposes. You can find full documentation for these
6592 switches in the body of the @code{Debug} unit in the compiler source
6593 file @file{debug.adb}.
6594 @end ifclear
6595
6596 @item -gnatG
6597 @cindex @option{-gnatG} (@command{gcc})
6598 This switch causes the compiler to generate auxiliary output containing
6599 a pseudo-source listing of the generated expanded code. Like most Ada
6600 compilers, GNAT works by first transforming the high level Ada code into
6601 lower level constructs. For example, tasking operations are transformed
6602 into calls to the tasking run-time routines. A unique capability of GNAT
6603 is to list this expanded code in a form very close to normal Ada source.
6604 This is very useful in understanding the implications of various Ada
6605 usage on the efficiency of the generated code. There are many cases in
6606 Ada (e.g.@: the use of controlled types), where simple Ada statements can
6607 generate a lot of run-time code. By using @option{-gnatG} you can identify
6608 these cases, and consider whether it may be desirable to modify the coding
6609 approach to improve efficiency.
6610
6611 The format of the output is very similar to standard Ada source, and is
6612 easily understood by an Ada programmer. The following special syntactic
6613 additions correspond to low level features used in the generated code that
6614 do not have any exact analogies in pure Ada source form. The following
6615 is a partial list of these special constructions. See the specification
6616 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6617
6618 If the switch @option{-gnatL} is used in conjunction with
6619 @cindex @option{-gnatL} (@command{gcc})
6620 @option{-gnatG}, then the original source lines are interspersed
6621 in the expanded source (as comment lines with the original line number).
6622
6623 @table @code
6624 @item new @var{xxx} [storage_pool = @var{yyy}]
6625 Shows the storage pool being used for an allocator.
6626
6627 @item at end @var{procedure-name};
6628 Shows the finalization (cleanup) procedure for a scope.
6629
6630 @item (if @var{expr} then @var{expr} else @var{expr})
6631 Conditional expression equivalent to the @code{x?y:z} construction in C.
6632
6633 @item @var{target}^^^(@var{source})
6634 A conversion with floating-point truncation instead of rounding.
6635
6636 @item @var{target}?(@var{source})
6637 A conversion that bypasses normal Ada semantic checking. In particular
6638 enumeration types and fixed-point types are treated simply as integers.
6639
6640 @item @var{target}?^^^(@var{source})
6641 Combines the above two cases.
6642
6643 @item @var{x} #/ @var{y}
6644 @itemx @var{x} #mod @var{y}
6645 @itemx @var{x} #* @var{y}
6646 @itemx @var{x} #rem @var{y}
6647 A division or multiplication of fixed-point values which are treated as
6648 integers without any kind of scaling.
6649
6650 @item free @var{expr} [storage_pool = @var{xxx}]
6651 Shows the storage pool associated with a @code{free} statement.
6652
6653 @item [subtype or type declaration]
6654 Used to list an equivalent declaration for an internally generated
6655 type that is referenced elsewhere in the listing.
6656
6657 @item freeze @var{type-name} [@var{actions}]
6658 Shows the point at which @var{type-name} is frozen, with possible
6659 associated actions to be performed at the freeze point.
6660
6661 @item reference @var{itype}
6662 Reference (and hence definition) to internal type @var{itype}.
6663
6664 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6665 Intrinsic function call.
6666
6667 @item @var{label-name} : label
6668 Declaration of label @var{labelname}.
6669
6670 @item #$ @var{subprogram-name}
6671 An implicit call to a run-time support routine
6672 (to meet the requirement of H.3.1(9) in a
6673 convenient manner).
6674
6675 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
6676 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6677 @var{expr}, but handled more efficiently).
6678
6679 @item [constraint_error]
6680 Raise the @code{Constraint_Error} exception.
6681
6682 @item @var{expression}'reference
6683 A pointer to the result of evaluating @var{expression}.
6684
6685 @item @var{target-type}!(@var{source-expression})
6686 An unchecked conversion of @var{source-expression} to @var{target-type}.
6687
6688 @item [@var{numerator}/@var{denominator}]
6689 Used to represent internal real literals (that) have no exact
6690 representation in base 2-16 (for example, the result of compile time
6691 evaluation of the expression 1.0/27.0).
6692 @end table
6693
6694 @item -gnatD
6695 @cindex @option{-gnatD} (@command{gcc})
6696 When used in conjunction with @option{-gnatG}, this switch causes
6697 the expanded source, as described above for
6698 @option{-gnatG} to be written to files with names
6699 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6700 instead of to the standard output file. For
6701 example, if the source file name is @file{hello.adb}, then a file
6702 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6703 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6704 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6705 you to do source level debugging using the generated code which is
6706 sometimes useful for complex code, for example to find out exactly
6707 which part of a complex construction raised an exception. This switch
6708 also suppress generation of cross-reference information (see
6709 @option{-gnatx}) since otherwise the cross-reference information
6710 would refer to the @file{^.dg^.DG^} file, which would cause
6711 confusion since this is not the original source file.
6712
6713 Note that @option{-gnatD} actually implies @option{-gnatG}
6714 automatically, so it is not necessary to give both options.
6715 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6716
6717 If the switch @option{-gnatL} is used in conjunction with
6718 @cindex @option{-gnatL} (@command{gcc})
6719 @option{-gnatDG}, then the original source lines are interspersed
6720 in the expanded source (as comment lines with the original line number).
6721
6722 @ifclear vms
6723 @item -gnatR[0|1|2|3[s]]
6724 @cindex @option{-gnatR} (@command{gcc})
6725 This switch controls output from the compiler of a listing showing
6726 representation information for declared types and objects. For
6727 @option{-gnatR0}, no information is output (equivalent to omitting
6728 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6729 so @option{-gnatR} with no parameter has the same effect), size and alignment
6730 information is listed for declared array and record types. For
6731 @option{-gnatR2}, size and alignment information is listed for all
6732 declared types and objects. Finally @option{-gnatR3} includes symbolic
6733 expressions for values that are computed at run time for
6734 variant records. These symbolic expressions have a mostly obvious
6735 format with #n being used to represent the value of the n'th
6736 discriminant. See source files @file{repinfo.ads/adb} in the
6737 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6738 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
6739 the output is to a file with the name @file{^file.rep^file_REP^} where
6740 file is the name of the corresponding source file.
6741 @end ifclear
6742 @ifset vms
6743 @item /REPRESENTATION_INFO
6744 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6745 This qualifier controls output from the compiler of a listing showing
6746 representation information for declared types and objects. For
6747 @option{/REPRESENTATION_INFO=NONE}, no information is output
6748 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6749 @option{/REPRESENTATION_INFO} without option is equivalent to
6750 @option{/REPRESENTATION_INFO=ARRAYS}.
6751 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6752 information is listed for declared array and record types. For
6753 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6754 is listed for all expression information for values that are computed
6755 at run time for variant records. These symbolic expressions have a mostly
6756 obvious format with #n being used to represent the value of the n'th
6757 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6758 @code{GNAT} sources for full details on the format of
6759 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6760 If _FILE is added at the end of an option
6761 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6762 then the output is to a file with the name @file{file_REP} where
6763 file is the name of the corresponding source file.
6764 @end ifset
6765 Note that it is possible for record components to have zero size. In
6766 this case, the component clause uses an obvious extension of permitted
6767 Ada syntax, for example @code{at 0 range 0 .. -1}.
6768
6769 Representation information requires that code be generated (since it is the
6770 code generator that lays out complex data structures). If an attempt is made
6771 to output representation information when no code is generated, for example
6772 when a subunit is compiled on its own, then no information can be generated
6773 and the compiler outputs a message to this effect.
6774
6775 @item -gnatS
6776 @cindex @option{-gnatS} (@command{gcc})
6777 The use of the switch @option{-gnatS} for an
6778 Ada compilation will cause the compiler to output a
6779 representation of package Standard in a form very
6780 close to standard Ada. It is not quite possible to
6781 do this entirely in standard Ada (since new
6782 numeric base types cannot be created in standard
6783 Ada), but the output is easily
6784 readable to any Ada programmer, and is useful to
6785 determine the characteristics of target dependent
6786 types in package Standard.
6787
6788 @item -gnatx
6789 @cindex @option{-gnatx} (@command{gcc})
6790 Normally the compiler generates full cross-referencing information in
6791 the @file{ALI} file. This information is used by a number of tools,
6792 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6793 suppresses this information. This saves some space and may slightly
6794 speed up compilation, but means that these tools cannot be used.
6795 @end table
6796
6797 @node Exception Handling Control
6798 @subsection Exception Handling Control
6799
6800 @noindent
6801 GNAT uses two methods for handling exceptions at run-time. The
6802 @code{setjmp/longjmp} method saves the context when entering
6803 a frame with an exception handler. Then when an exception is
6804 raised, the context can be restored immediately, without the
6805 need for tracing stack frames. This method provides very fast
6806 exception propagation, but introduces significant overhead for
6807 the use of exception handlers, even if no exception is raised.
6808
6809 The other approach is called ``zero cost'' exception handling.
6810 With this method, the compiler builds static tables to describe
6811 the exception ranges. No dynamic code is required when entering
6812 a frame containing an exception handler. When an exception is
6813 raised, the tables are used to control a back trace of the
6814 subprogram invocation stack to locate the required exception
6815 handler. This method has considerably poorer performance for
6816 the propagation of exceptions, but there is no overhead for
6817 exception handlers if no exception is raised. Note that in this
6818 mode and in the context of mixed Ada and C/C++ programming,
6819 to propagate an exception through a C/C++ code, the C/C++ code
6820 must be compiled with the @option{-funwind-tables} GCC's
6821 option.
6822
6823 The following switches may be used to control which of the
6824 two exception handling methods is used.
6825
6826 @table @option
6827 @c !sort!
6828
6829 @item --RTS=sjlj
6830 @cindex @option{--RTS=sjlj} (@command{gnatmake})
6831 This switch causes the setjmp/longjmp run-time (when available) to be used
6832 for exception handling. If the default
6833 mechanism for the target is zero cost exceptions, then
6834 this switch can be used to modify this default, and must be
6835 used for all units in the partition.
6836 This option is rarely used. One case in which it may be
6837 advantageous is if you have an application where exception
6838 raising is common and the overall performance of the
6839 application is improved by favoring exception propagation.
6840
6841 @item --RTS=zcx
6842 @cindex @option{--RTS=zcx} (@command{gnatmake})
6843 @cindex Zero Cost Exceptions
6844 This switch causes the zero cost approach to be used
6845 for exception handling. If this is the default mechanism for the
6846 target (see below), then this switch is unneeded. If the default
6847 mechanism for the target is setjmp/longjmp exceptions, then
6848 this switch can be used to modify this default, and must be
6849 used for all units in the partition.
6850 This option can only be used if the zero cost approach
6851 is available for the target in use, otherwise it will generate an error.
6852 @end table
6853
6854 @noindent
6855 The same option @option{--RTS} must be used both for @command{gcc}
6856 and @command{gnatbind}. Passing this option to @command{gnatmake}
6857 (@pxref{Switches for gnatmake}) will ensure the required consistency
6858 through the compilation and binding steps.
6859
6860 @node Units to Sources Mapping Files
6861 @subsection Units to Sources Mapping Files
6862
6863 @table @option
6864
6865 @item -gnatem^^=^@var{path}
6866 @cindex @option{-gnatem} (@command{gcc})
6867 A mapping file is a way to communicate to the compiler two mappings:
6868 from unit names to file names (without any directory information) and from
6869 file names to path names (with full directory information). These mappings
6870 are used by the compiler to short-circuit the path search.
6871
6872 The use of mapping files is not required for correct operation of the
6873 compiler, but mapping files can improve efficiency, particularly when
6874 sources are read over a slow network connection. In normal operation,
6875 you need not be concerned with the format or use of mapping files,
6876 and the @option{-gnatem} switch is not a switch that you would use
6877 explicitly. it is intended only for use by automatic tools such as
6878 @command{gnatmake} running under the project file facility. The
6879 description here of the format of mapping files is provided
6880 for completeness and for possible use by other tools.
6881
6882 A mapping file is a sequence of sets of three lines. In each set,
6883 the first line is the unit name, in lower case, with ``@code{%s}''
6884 appended for
6885 specifications and ``@code{%b}'' appended for bodies; the second line is the
6886 file name; and the third line is the path name.
6887
6888 Example:
6889 @smallexample
6890    main%b
6891    main.2.ada
6892    /gnat/project1/sources/main.2.ada
6893 @end smallexample
6894
6895 When the switch @option{-gnatem} is specified, the compiler will create
6896 in memory the two mappings from the specified file. If there is any problem
6897 (nonexistent file, truncated file or duplicate entries), no mapping will
6898 be created.
6899
6900 Several @option{-gnatem} switches may be specified; however, only the last
6901 one on the command line will be taken into account.
6902
6903 When using a project file, @command{gnatmake} create a temporary mapping file
6904 and communicates it to the compiler using this switch.
6905
6906 @end table
6907
6908 @node Integrated Preprocessing
6909 @subsection Integrated Preprocessing
6910
6911 @noindent
6912 GNAT sources may be preprocessed immediately before compilation.
6913 In this case, the actual
6914 text of the source is not the text of the source file, but is derived from it
6915 through a process called preprocessing. Integrated preprocessing is specified
6916 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6917 indicates, through a text file, the preprocessing data to be used.
6918 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6919
6920 @noindent
6921 Note that when integrated preprocessing is used, the output from the
6922 preprocessor is not written to any external file. Instead it is passed
6923 internally to the compiler. If you need to preserve the result of
6924 preprocessing in a file, then you should use @command{gnatprep}
6925 to perform the desired preprocessing in stand-alone mode.
6926
6927 @noindent
6928 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6929 used when Integrated Preprocessing is used. The reason is that preprocessing
6930 with another Preprocessing Data file without changing the sources will
6931 not trigger recompilation without this switch.
6932
6933 @noindent
6934 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6935 always trigger recompilation for sources that are preprocessed,
6936 because @command{gnatmake} cannot compute the checksum of the source after
6937 preprocessing.
6938
6939 @noindent
6940 The actual preprocessing function is described in details in section
6941 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6942 preprocessing is triggered and parameterized.
6943
6944 @table @code
6945
6946 @item -gnatep=@var{file}
6947 @cindex @option{-gnatep} (@command{gcc})
6948 This switch indicates to the compiler the file name (without directory
6949 information) of the preprocessor data file to use. The preprocessor data file
6950 should be found in the source directories.
6951
6952 @noindent
6953 A preprocessing data file is a text file with significant lines indicating
6954 how should be preprocessed either a specific source or all sources not
6955 mentioned in other lines. A significant line is a nonempty, non-comment line.
6956 Comments are similar to Ada comments.
6957
6958 @noindent
6959 Each significant line starts with either a literal string or the character '*'.
6960 A literal string is the file name (without directory information) of the source
6961 to preprocess. A character '*' indicates the preprocessing for all the sources
6962 that are not specified explicitly on other lines (order of the lines is not
6963 significant). It is an error to have two lines with the same file name or two
6964 lines starting with the character '*'.
6965
6966 @noindent
6967 After the file name or the character '*', another optional literal string
6968 indicating the file name of the definition file to be used for preprocessing
6969 (@pxref{Form of Definitions File}). The definition files are found by the
6970 compiler in one of the source directories. In some cases, when compiling
6971 a source in a directory other than the current directory, if the definition
6972 file is in the current directory, it may be necessary to add the current
6973 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6974 the compiler would not find the definition file.
6975
6976 @noindent
6977 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6978 be found. Those ^switches^switches^ are:
6979
6980 @table @code
6981
6982 @item -b
6983 Causes both preprocessor lines and the lines deleted by
6984 preprocessing to be replaced by blank lines, preserving the line number.
6985 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6986 it cancels the effect of @option{-c}.
6987
6988 @item -c
6989 Causes both preprocessor lines and the lines deleted
6990 by preprocessing to be retained as comments marked
6991 with the special string ``@code{--! }''.
6992
6993 @item -Dsymbol=value
6994 Define or redefine a symbol, associated with value. A symbol is an Ada
6995 identifier, or an Ada reserved word, with the exception of @code{if},
6996 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6997 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6998 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6999 same name defined in a definition file.
7000
7001 @item -s
7002 Causes a sorted list of symbol names and values to be
7003 listed on the standard output file.
7004
7005 @item -u
7006 Causes undefined symbols to be treated as having the value @code{FALSE}
7007 in the context
7008 of a preprocessor test. In the absence of this option, an undefined symbol in
7009 a @code{#if} or @code{#elsif} test will be treated as an error.
7010
7011 @end table
7012
7013 @noindent
7014 Examples of valid lines in a preprocessor data file:
7015
7016 @smallexample
7017   "toto.adb"  "prep.def" -u
7018   --  preprocess "toto.adb", using definition file "prep.def",
7019   --  undefined symbol are False.
7020
7021   * -c -DVERSION=V101
7022   --  preprocess all other sources without a definition file;
7023   --  suppressed lined are commented; symbol VERSION has the value V101.
7024
7025   "titi.adb" "prep2.def" -s
7026   --  preprocess "titi.adb", using definition file "prep2.def";
7027   --  list all symbols with their values.
7028 @end smallexample
7029
7030 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
7031 @cindex @option{-gnateD} (@command{gcc})
7032 Define or redefine a preprocessing symbol, associated with value. If no value
7033 is given on the command line, then the value of the symbol is @code{True}.
7034 A symbol is an identifier, following normal Ada (case-insensitive)
7035 rules for its syntax, and value is any sequence (including an empty sequence)
7036 of characters from the set (letters, digits, period, underline).
7037 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7038 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7039
7040 @noindent
7041 A symbol declared with this ^switch^switch^ on the command line replaces a
7042 symbol with the same name either in a definition file or specified with a
7043 ^switch^switch^ -D in the preprocessor data file.
7044
7045 @noindent
7046 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7047
7048 @end table
7049
7050 @node Code Generation Control
7051 @subsection Code Generation Control
7052
7053 @noindent
7054
7055 The GCC technology provides a wide range of target dependent
7056 @option{-m} switches for controlling
7057 details of code generation with respect to different versions of
7058 architectures. This includes variations in instruction sets (e.g.@:
7059 different members of the power pc family), and different requirements
7060 for optimal arrangement of instructions (e.g.@: different members of
7061 the x86 family). The list of available @option{-m} switches may be
7062 found in the GCC documentation.
7063
7064 Use of these @option{-m} switches may in some cases result in improved
7065 code performance.
7066
7067 The GNAT Pro technology is tested and qualified without any
7068 @option{-m} switches,
7069 so generally the most reliable approach is to avoid the use of these
7070 switches. However, we generally expect most of these switches to work
7071 successfully with GNAT Pro, and many customers have reported successful
7072 use of these options.
7073
7074 Our general advice is to avoid the use of @option{-m} switches unless
7075 special needs lead to requirements in this area. In particular,
7076 there is no point in using @option{-m} switches to improve performance
7077 unless you actually see a performance improvement.
7078
7079 @ifset vms
7080 @node Return Codes
7081 @subsection Return Codes
7082 @cindex Return Codes
7083 @cindex @option{/RETURN_CODES=VMS}
7084
7085 @noindent
7086 On VMS, GNAT compiled programs return POSIX-style codes by default,
7087 e.g.@: @option{/RETURN_CODES=POSIX}.
7088
7089 To enable VMS style return codes, use GNAT BIND and LINK with the option
7090 @option{/RETURN_CODES=VMS}. For example:
7091
7092 @smallexample
7093 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7094 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7095 @end smallexample
7096
7097 @noindent
7098 Programs built with /RETURN_CODES=VMS are suitable to be called in
7099 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7100 are suitable for spawning with appropriate GNAT RTL routines.
7101
7102 @end ifset
7103
7104 @node Search Paths and the Run-Time Library (RTL)
7105 @section Search Paths and the Run-Time Library (RTL)
7106
7107 @noindent
7108 With the GNAT source-based library system, the compiler must be able to
7109 find source files for units that are needed by the unit being compiled.
7110 Search paths are used to guide this process.
7111
7112 The compiler compiles one source file whose name must be given
7113 explicitly on the command line. In other words, no searching is done
7114 for this file. To find all other source files that are needed (the most
7115 common being the specs of units), the compiler examines the following
7116 directories, in the following order:
7117
7118 @enumerate
7119 @item
7120 The directory containing the source file of the main unit being compiled
7121 (the file name on the command line).
7122
7123 @item
7124 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7125 @command{gcc} command line, in the order given.
7126
7127 @item
7128 @findex ADA_PRJ_INCLUDE_FILE
7129 Each of the directories listed in the text file whose name is given
7130 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7131
7132 @noindent
7133 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7134 driver when project files are used. It should not normally be set
7135 by other means.
7136
7137 @item
7138 @findex ADA_INCLUDE_PATH
7139 Each of the directories listed in the value of the
7140 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7141 @ifclear vms
7142 Construct this value
7143 exactly as the @env{PATH} environment variable: a list of directory
7144 names separated by colons (semicolons when working with the NT version).
7145 @end ifclear
7146 @ifset vms
7147 Normally, define this value as a logical name containing a comma separated
7148 list of directory names.
7149
7150 This variable can also be defined by means of an environment string
7151 (an argument to the HP C exec* set of functions).
7152
7153 Logical Name:
7154 @smallexample
7155 DEFINE ANOTHER_PATH FOO:[BAG]
7156 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7157 @end smallexample
7158
7159 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7160 first, followed by the standard Ada
7161 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7162 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7163 (Text_IO, Sequential_IO, etc)
7164 instead of the standard Ada packages. Thus, in order to get the standard Ada
7165 packages by default, ADA_INCLUDE_PATH must be redefined.
7166 @end ifset
7167
7168 @item
7169 The content of the @file{ada_source_path} file which is part of the GNAT
7170 installation tree and is used to store standard libraries such as the
7171 GNAT Run Time Library (RTL) source files.
7172 @ifclear vms
7173 @ref{Installing a library}
7174 @end ifclear
7175 @end enumerate
7176
7177 @noindent
7178 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7179 inhibits the use of the directory
7180 containing the source file named in the command line. You can still
7181 have this directory on your search path, but in this case it must be
7182 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7183
7184 Specifying the switch @option{-nostdinc}
7185 inhibits the search of the default location for the GNAT Run Time
7186 Library (RTL) source files.
7187
7188 The compiler outputs its object files and ALI files in the current
7189 working directory.
7190 @ifclear vms
7191 Caution: The object file can be redirected with the @option{-o} switch;
7192 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7193 so the @file{ALI} file will not go to the right place. Therefore, you should
7194 avoid using the @option{-o} switch.
7195 @end ifclear
7196
7197 @findex System.IO
7198 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7199 children make up the GNAT RTL, together with the simple @code{System.IO}
7200 package used in the @code{"Hello World"} example. The sources for these units
7201 are needed by the compiler and are kept together in one directory. Not
7202 all of the bodies are needed, but all of the sources are kept together
7203 anyway. In a normal installation, you need not specify these directory
7204 names when compiling or binding. Either the environment variables or
7205 the built-in defaults cause these files to be found.
7206
7207 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7208 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7209 consisting of child units of @code{GNAT}. This is a collection of generally
7210 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
7211 further details.
7212
7213 Besides simplifying access to the RTL, a major use of search paths is
7214 in compiling sources from multiple directories. This can make
7215 development environments much more flexible.
7216
7217 @node Order of Compilation Issues
7218 @section Order of Compilation Issues
7219
7220 @noindent
7221 If, in our earlier example, there was a spec for the @code{hello}
7222 procedure, it would be contained in the file @file{hello.ads}; yet this
7223 file would not have to be explicitly compiled. This is the result of the
7224 model we chose to implement library management. Some of the consequences
7225 of this model are as follows:
7226
7227 @itemize @bullet
7228 @item
7229 There is no point in compiling specs (except for package
7230 specs with no bodies) because these are compiled as needed by clients. If
7231 you attempt a useless compilation, you will receive an error message.
7232 It is also useless to compile subunits because they are compiled as needed
7233 by the parent.
7234
7235 @item
7236 There are no order of compilation requirements: performing a
7237 compilation never obsoletes anything. The only way you can obsolete
7238 something and require recompilations is to modify one of the
7239 source files on which it depends.
7240
7241 @item
7242 There is no library as such, apart from the ALI files
7243 (@pxref{The Ada Library Information Files}, for information on the format
7244 of these files). For now we find it convenient to create separate ALI files,
7245 but eventually the information therein may be incorporated into the object
7246 file directly.
7247
7248 @item
7249 When you compile a unit, the source files for the specs of all units
7250 that it @code{with}'s, all its subunits, and the bodies of any generics it
7251 instantiates must be available (reachable by the search-paths mechanism
7252 described above), or you will receive a fatal error message.
7253 @end itemize
7254
7255 @node Examples
7256 @section Examples
7257
7258 @noindent
7259 The following are some typical Ada compilation command line examples:
7260
7261 @table @code
7262 @item $ gcc -c xyz.adb
7263 Compile body in file @file{xyz.adb} with all default options.
7264
7265 @ifclear vms
7266 @item $ gcc -c -O2 -gnata xyz-def.adb
7267 @end ifclear
7268 @ifset vms
7269 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7270 @end ifset
7271
7272 Compile the child unit package in file @file{xyz-def.adb} with extensive
7273 optimizations, and pragma @code{Assert}/@code{Debug} statements
7274 enabled.
7275
7276 @item $ gcc -c -gnatc abc-def.adb
7277 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7278 mode.
7279 @end table
7280
7281 @node Binding Using gnatbind
7282 @chapter Binding Using @code{gnatbind}
7283 @findex gnatbind
7284
7285 @menu
7286 * Running gnatbind::
7287 * Switches for gnatbind::
7288 * Command-Line Access::
7289 * Search Paths for gnatbind::
7290 * Examples of gnatbind Usage::
7291 @end menu
7292
7293 @noindent
7294 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7295 to bind compiled GNAT objects.
7296
7297 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7298 driver (see @ref{The GNAT Driver and Project Files}).
7299
7300 The @code{gnatbind} program performs four separate functions:
7301
7302 @enumerate
7303 @item
7304 Checks that a program is consistent, in accordance with the rules in
7305 Chapter 10 of the Ada Reference Manual. In particular, error
7306 messages are generated if a program uses inconsistent versions of a
7307 given unit.
7308
7309 @item
7310 Checks that an acceptable order of elaboration exists for the program
7311 and issues an error message if it cannot find an order of elaboration
7312 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7313
7314 @item
7315 Generates a main program incorporating the given elaboration order.
7316 This program is a small Ada package (body and spec) that
7317 must be subsequently compiled
7318 using the GNAT compiler. The necessary compilation step is usually
7319 performed automatically by @command{gnatlink}. The two most important
7320 functions of this program
7321 are to call the elaboration routines of units in an appropriate order
7322 and to call the main program.
7323
7324 @item
7325 Determines the set of object files required by the given main program.
7326 This information is output in the forms of comments in the generated program,
7327 to be read by the @command{gnatlink} utility used to link the Ada application.
7328 @end enumerate
7329
7330 @node Running gnatbind
7331 @section Running @code{gnatbind}
7332
7333 @noindent
7334 The form of the @code{gnatbind} command is
7335
7336 @smallexample
7337 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
7338 @end smallexample
7339
7340 @noindent
7341 where @file{@i{mainprog}.adb} is the Ada file containing the main program
7342 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7343 package in two files whose names are
7344 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
7345 For example, if given the
7346 parameter @file{hello.ali}, for a main program contained in file
7347 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7348 and @file{b~hello.adb}.
7349
7350 When doing consistency checking, the binder takes into consideration
7351 any source files it can locate. For example, if the binder determines
7352 that the given main program requires the package @code{Pack}, whose
7353 @file{.ALI}
7354 file is @file{pack.ali} and whose corresponding source spec file is
7355 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7356 (using the same search path conventions as previously described for the
7357 @command{gcc} command). If it can locate this source file, it checks that
7358 the time stamps
7359 or source checksums of the source and its references to in @file{ALI} files
7360 match. In other words, any @file{ALI} files that mentions this spec must have
7361 resulted from compiling this version of the source file (or in the case
7362 where the source checksums match, a version close enough that the
7363 difference does not matter).
7364
7365 @cindex Source files, use by binder
7366 The effect of this consistency checking, which includes source files, is
7367 that the binder ensures that the program is consistent with the latest
7368 version of the source files that can be located at bind time. Editing a
7369 source file without compiling files that depend on the source file cause
7370 error messages to be generated by the binder.
7371
7372 For example, suppose you have a main program @file{hello.adb} and a
7373 package @code{P}, from file @file{p.ads} and you perform the following
7374 steps:
7375
7376 @enumerate
7377 @item
7378 Enter @code{gcc -c hello.adb} to compile the main program.
7379
7380 @item
7381 Enter @code{gcc -c p.ads} to compile package @code{P}.
7382
7383 @item
7384 Edit file @file{p.ads}.
7385
7386 @item
7387 Enter @code{gnatbind hello}.
7388 @end enumerate
7389
7390 @noindent
7391 At this point, the file @file{p.ali} contains an out-of-date time stamp
7392 because the file @file{p.ads} has been edited. The attempt at binding
7393 fails, and the binder generates the following error messages:
7394
7395 @smallexample
7396 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7397 error: "p.ads" has been modified and must be recompiled
7398 @end smallexample
7399
7400 @noindent
7401 Now both files must be recompiled as indicated, and then the bind can
7402 succeed, generating a main program. You need not normally be concerned
7403 with the contents of this file, but for reference purposes a sample
7404 binder output file is given in @ref{Example of Binder Output File}.
7405
7406 In most normal usage, the default mode of @command{gnatbind} which is to
7407 generate the main package in Ada, as described in the previous section.
7408 In particular, this means that any Ada programmer can read and understand
7409 the generated main program. It can also be debugged just like any other
7410 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7411 @command{gnatbind} and @command{gnatlink}.
7412
7413 However for some purposes it may be convenient to generate the main
7414 program in C rather than Ada. This may for example be helpful when you
7415 are generating a mixed language program with the main program in C. The
7416 GNAT compiler itself is an example.
7417 The use of the @option{^-C^/BIND_FILE=C^} switch
7418 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7419 be generated in C (and compiled using the gnu C compiler).
7420
7421 @node Switches for gnatbind
7422 @section Switches for @command{gnatbind}
7423
7424 @noindent
7425 The following switches are available with @code{gnatbind}; details will
7426 be presented in subsequent sections.
7427
7428 @menu
7429 * Consistency-Checking Modes::
7430 * Binder Error Message Control::
7431 * Elaboration Control::
7432 * Output Control::
7433 * Binding with Non-Ada Main Programs::
7434 * Binding Programs with No Main Subprogram::
7435 @end menu
7436
7437 @table @option
7438 @c !sort!
7439
7440 @item --version
7441 @cindex @option{--version} @command{gnatbind}
7442 Display Copyright and version, then exit disregarding all other options.
7443
7444 @item --help
7445 @cindex @option{--help} @command{gnatbind}
7446 If @option{--version} was not used, display usage, then exit disregarding
7447 all other options.
7448
7449 @item -a
7450 @cindex @option{-a} @command{gnatbind}
7451 Indicates that, if supported by the platform, the adainit procedure should
7452 be treated as an initialisation routine by the linker (a constructor). This
7453 is intended to be used by the Project Manager to automatically initialize
7454 shared Stand-Alone Libraries.
7455
7456 @item ^-aO^/OBJECT_SEARCH^
7457 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7458 Specify directory to be searched for ALI files.
7459
7460 @item ^-aI^/SOURCE_SEARCH^
7461 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7462 Specify directory to be searched for source file.
7463
7464 @item ^-A^/BIND_FILE=ADA^
7465 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7466 Generate binder program in Ada (default)
7467
7468 @item ^-b^/REPORT_ERRORS=BRIEF^
7469 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7470 Generate brief messages to @file{stderr} even if verbose mode set.
7471
7472 @item ^-c^/NOOUTPUT^
7473 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7474 Check only, no generation of binder output file.
7475
7476 @item ^-C^/BIND_FILE=C^
7477 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7478 Generate binder program in C
7479
7480 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]
7481 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]} (@command{gnatbind})
7482 This switch can be used to change the default task stack size value
7483 to a specified size @var{nn}, which is expressed in bytes by default, or
7484 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7485 with @var{m}.
7486 In the absence of a [k|m] suffix, this switch is equivalent, in effect,
7487 to completing all task specs with
7488 @smallexample @c ada
7489    pragma Storage_Size (nn);
7490 @end smallexample
7491 When they do not already have such a pragma.
7492
7493 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}[k|m]
7494 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7495 This switch can be used to change the default secondary stack size value
7496 to a specified size @var{nn}, which is expressed in bytes by default, or
7497 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7498 with @var{m}.
7499
7500 The secondary stack is used to deal with functions that return a variable
7501 sized result, for example a function returning an unconstrained
7502 String. There are two ways in which this secondary stack is allocated.
7503
7504 For most targets, the secondary stack is growing on demand and is allocated
7505 as a chain of blocks in the heap. The -D option is not very
7506 relevant. It only give some control over the size of the allocated
7507 blocks (whose size is the minimum of the default secondary stack size value,
7508 and the actual size needed for the current allocation request).
7509
7510 For certain targets, notably VxWorks 653,
7511 the secondary stack is allocated by carving off a fixed ratio chunk of the
7512 primary task stack. The -D option is used to define the
7513 size of the environment task's secondary stack.
7514
7515 @item ^-e^/ELABORATION_DEPENDENCIES^
7516 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7517 Output complete list of elaboration-order dependencies.
7518
7519 @item ^-E^/STORE_TRACEBACKS^
7520 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7521 Store tracebacks in exception occurrences when the target supports it.
7522 This is the default with the zero cost exception mechanism.
7523 @ignore
7524 @c The following may get moved to an appendix
7525 This option is currently supported on the following targets:
7526 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7527 @end ignore
7528 See also the packages @code{GNAT.Traceback} and
7529 @code{GNAT.Traceback.Symbolic} for more information.
7530 @ifclear vms
7531 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7532 @command{gcc} option.
7533 @end ifclear
7534
7535 @item ^-F^/FORCE_ELABS_FLAGS^
7536 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7537 Force the checks of elaboration flags. @command{gnatbind} does not normally
7538 generate checks of elaboration flags for the main executable, except when
7539 a Stand-Alone Library is used. However, there are cases when this cannot be
7540 detected by gnatbind. An example is importing an interface of a Stand-Alone
7541 Library through a pragma Import and only specifying through a linker switch
7542 this Stand-Alone Library. This switch is used to guarantee that elaboration
7543 flag checks are generated.
7544
7545 @item ^-h^/HELP^
7546 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7547 Output usage (help) information
7548
7549 @item ^-I^/SEARCH^
7550 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7551 Specify directory to be searched for source and ALI files.
7552
7553 @item ^-I-^/NOCURRENT_DIRECTORY^
7554 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7555 Do not look for sources in the current directory where @code{gnatbind} was
7556 invoked, and do not look for ALI files in the directory containing the
7557 ALI file named in the @code{gnatbind} command line.
7558
7559 @item ^-l^/ORDER_OF_ELABORATION^
7560 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7561 Output chosen elaboration order.
7562
7563 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7564 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7565 Bind the units for library building. In this case the adainit and
7566 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7567 are renamed to ^xxxinit^XXXINIT^ and
7568 ^xxxfinal^XXXFINAL^.
7569 Implies ^-n^/NOCOMPILE^.
7570 @ifclear vms
7571 (@xref{GNAT and Libraries}, for more details.)
7572 @end ifclear
7573 @ifset vms
7574 On OpenVMS, these init and final procedures are exported in uppercase
7575 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7576 the init procedure will be "TOTOINIT" and the exported name of the final
7577 procedure will be "TOTOFINAL".
7578 @end ifset
7579
7580 @item ^-Mxyz^/RENAME_MAIN=xyz^
7581 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7582 Rename generated main program from main to xyz. This option is
7583 supported on cross environments only.
7584
7585 @item ^-m^/ERROR_LIMIT=^@var{n}
7586 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7587 Limit number of detected errors to @var{n}, where @var{n} is
7588 in the range 1..999_999. The default value if no switch is
7589 given is 9999. Binding is terminated if the limit is exceeded.
7590 @ifset unw
7591 Furthermore, under Windows, the sources pointed to by the libraries path
7592 set in the registry are not searched for.
7593 @end ifset
7594
7595 @item ^-n^/NOMAIN^
7596 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7597 No main program.
7598
7599 @item -nostdinc
7600 @cindex @option{-nostdinc} (@command{gnatbind})
7601 Do not look for sources in the system default directory.
7602
7603 @item -nostdlib
7604 @cindex @option{-nostdlib} (@command{gnatbind})
7605 Do not look for library files in the system default directory.
7606
7607 @item --RTS=@var{rts-path}
7608 @cindex @option{--RTS} (@code{gnatbind})
7609 Specifies the default location of the runtime library. Same meaning as the
7610 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7611
7612 @item ^-o ^/OUTPUT=^@var{file}
7613 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7614 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7615 Note that if this option is used, then linking must be done manually,
7616 gnatlink cannot be used.
7617
7618 @item ^-O^/OBJECT_LIST^
7619 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7620 Output object list.
7621
7622 @item ^-p^/PESSIMISTIC_ELABORATION^
7623 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7624 Pessimistic (worst-case) elaboration order
7625
7626 @item ^-R^-R^
7627 @cindex @option{^-R^-R^} (@command{gnatbind})
7628 Output closure source list.
7629
7630 @item ^-s^/READ_SOURCES=ALL^
7631 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7632 Require all source files to be present.
7633
7634 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7635 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7636 Specifies the value to be used when detecting uninitialized scalar
7637 objects with pragma Initialize_Scalars.
7638 The @var{xxx} ^string specified with the switch^option^ may be either
7639 @itemize @bullet
7640 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7641 @item ``@option{^lo^LOW^}'' for the lowest possible value
7642 @item ``@option{^hi^HIGH^}'' for the highest possible value
7643 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7644 value 16#xx# (i.e., xx is a string of two hexadecimal digits).
7645 @end itemize
7646
7647 In addition, you can specify @option{-Sev} to indicate that the value is
7648 to be set at run time. In this case, the program will look for an environment
7649 @cindex GNAT_INIT_SCALARS
7650 variable of the form @env{GNAT_INIT_SCALARS=xx}, where xx is one
7651 of @option{in/lo/hi/xx} with the same meanings as above.
7652 If no environment variable is found, or if it does not have a valid value,
7653 then the default is @option{in} (invalid values).
7654
7655 @ifclear vms
7656 @item -static
7657 @cindex @option{-static} (@code{gnatbind})
7658 Link against a static GNAT run time.
7659
7660 @item -shared
7661 @cindex @option{-shared} (@code{gnatbind})
7662 Link against a shared GNAT run time when available.
7663 @end ifclear
7664
7665 @item ^-t^/NOTIME_STAMP_CHECK^
7666 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7667 Tolerate time stamp and other consistency errors
7668
7669 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7670 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7671 Set the time slice value to @var{n} milliseconds. If the system supports
7672 the specification of a specific time slice value, then the indicated value
7673 is used. If the system does not support specific time slice values, but
7674 does support some general notion of round-robin scheduling, then any
7675 nonzero value will activate round-robin scheduling.
7676
7677 A value of zero is treated specially. It turns off time
7678 slicing, and in addition, indicates to the tasking run time that the
7679 semantics should match as closely as possible the Annex D
7680 requirements of the Ada RM, and in particular sets the default
7681 scheduling policy to @code{FIFO_Within_Priorities}.
7682
7683 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
7684 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
7685 Enable dynamic stack usage, with @var{n} results stored and displayed
7686 at program termination. A result is generated when a task
7687 terminates. Results that can't be stored are displayed on the fly, at
7688 task termination. This option is currently not supported on Itanium
7689 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
7690
7691 @item ^-v^/REPORT_ERRORS=VERBOSE^
7692 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7693 Verbose mode. Write error messages, header, summary output to
7694 @file{stdout}.
7695
7696 @ifclear vms
7697 @item -w@var{x}
7698 @cindex @option{-w} (@code{gnatbind})
7699 Warning mode (@var{x}=s/e for suppress/treat as error)
7700 @end ifclear
7701
7702 @ifset vms
7703 @item /WARNINGS=NORMAL
7704 @cindex @option{/WARNINGS} (@code{gnatbind})
7705 Normal warnings mode. Warnings are issued but ignored
7706
7707 @item /WARNINGS=SUPPRESS
7708 @cindex @option{/WARNINGS} (@code{gnatbind})
7709 All warning messages are suppressed
7710
7711 @item /WARNINGS=ERROR
7712 @cindex @option{/WARNINGS} (@code{gnatbind})
7713 Warning messages are treated as fatal errors
7714 @end ifset
7715
7716 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
7717 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
7718 Override default wide character encoding for standard Text_IO files.
7719
7720 @item ^-x^/READ_SOURCES=NONE^
7721 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7722 Exclude source files (check object consistency only).
7723
7724 @ifset vms
7725 @item /READ_SOURCES=AVAILABLE
7726 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7727 Default mode, in which sources are checked for consistency only if
7728 they are available.
7729 @end ifset
7730
7731 @item ^-y^/ENABLE_LEAP_SECONDS^
7732 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
7733 Enable leap seconds support in @code{Ada.Calendar} and its children.
7734
7735 @item ^-z^/ZERO_MAIN^
7736 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7737 No main subprogram.
7738 @end table
7739
7740 @ifclear vms
7741 @noindent
7742 You may obtain this listing of switches by running @code{gnatbind} with
7743 no arguments.
7744 @end ifclear
7745
7746 @node Consistency-Checking Modes
7747 @subsection Consistency-Checking Modes
7748
7749 @noindent
7750 As described earlier, by default @code{gnatbind} checks
7751 that object files are consistent with one another and are consistent
7752 with any source files it can locate. The following switches control binder
7753 access to sources.
7754
7755 @table @option
7756 @c !sort!
7757 @item ^-s^/READ_SOURCES=ALL^
7758 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7759 Require source files to be present. In this mode, the binder must be
7760 able to locate all source files that are referenced, in order to check
7761 their consistency. In normal mode, if a source file cannot be located it
7762 is simply ignored. If you specify this switch, a missing source
7763 file is an error.
7764
7765 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
7766 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
7767 Override default wide character encoding for standard Text_IO files.
7768 Normally the default wide character encoding method used for standard
7769 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
7770 the main source input (see description of switch
7771 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
7772 use of this switch for the binder (which has the same set of
7773 possible arguments) overrides this default as specified.
7774
7775 @item ^-x^/READ_SOURCES=NONE^
7776 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7777 Exclude source files. In this mode, the binder only checks that ALI
7778 files are consistent with one another. Source files are not accessed.
7779 The binder runs faster in this mode, and there is still a guarantee that
7780 the resulting program is self-consistent.
7781 If a source file has been edited since it was last compiled, and you
7782 specify this switch, the binder will not detect that the object
7783 file is out of date with respect to the source file. Note that this is the
7784 mode that is automatically used by @command{gnatmake} because in this
7785 case the checking against sources has already been performed by
7786 @command{gnatmake} in the course of compilation (i.e.@: before binding).
7787
7788 @ifset vms
7789 @item /READ_SOURCES=AVAILABLE
7790 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7791 This is the default mode in which source files are checked if they are
7792 available, and ignored if they are not available.
7793 @end ifset
7794 @end table
7795
7796 @node Binder Error Message Control
7797 @subsection Binder Error Message Control
7798
7799 @noindent
7800 The following switches provide control over the generation of error
7801 messages from the binder:
7802
7803 @table @option
7804 @c !sort!
7805 @item ^-v^/REPORT_ERRORS=VERBOSE^
7806 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7807 Verbose mode. In the normal mode, brief error messages are generated to
7808 @file{stderr}. If this switch is present, a header is written
7809 to @file{stdout} and any error messages are directed to @file{stdout}.
7810 All that is written to @file{stderr} is a brief summary message.
7811
7812 @item ^-b^/REPORT_ERRORS=BRIEF^
7813 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7814 Generate brief error messages to @file{stderr} even if verbose mode is
7815 specified. This is relevant only when used with the
7816 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7817
7818 @ifclear vms
7819 @item -m@var{n}
7820 @cindex @option{-m} (@code{gnatbind})
7821 Limits the number of error messages to @var{n}, a decimal integer in the
7822 range 1-999. The binder terminates immediately if this limit is reached.
7823
7824 @item -M@var{xxx}
7825 @cindex @option{-M} (@code{gnatbind})
7826 Renames the generated main program from @code{main} to @code{xxx}.
7827 This is useful in the case of some cross-building environments, where
7828 the actual main program is separate from the one generated
7829 by @code{gnatbind}.
7830 @end ifclear
7831
7832 @item ^-ws^/WARNINGS=SUPPRESS^
7833 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7834 @cindex Warnings
7835 Suppress all warning messages.
7836
7837 @item ^-we^/WARNINGS=ERROR^
7838 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7839 Treat any warning messages as fatal errors.
7840
7841 @ifset vms
7842 @item /WARNINGS=NORMAL
7843 Standard mode with warnings generated, but warnings do not get treated
7844 as errors.
7845 @end ifset
7846
7847 @item ^-t^/NOTIME_STAMP_CHECK^
7848 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7849 @cindex Time stamp checks, in binder
7850 @cindex Binder consistency checks
7851 @cindex Consistency checks, in binder
7852 The binder performs a number of consistency checks including:
7853
7854 @itemize @bullet
7855 @item
7856 Check that time stamps of a given source unit are consistent
7857 @item
7858 Check that checksums of a given source unit are consistent
7859 @item
7860 Check that consistent versions of @code{GNAT} were used for compilation
7861 @item
7862 Check consistency of configuration pragmas as required
7863 @end itemize
7864
7865 @noindent
7866 Normally failure of such checks, in accordance with the consistency
7867 requirements of the Ada Reference Manual, causes error messages to be
7868 generated which abort the binder and prevent the output of a binder
7869 file and subsequent link to obtain an executable.
7870
7871 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7872 into warnings, so that
7873 binding and linking can continue to completion even in the presence of such
7874 errors. The result may be a failed link (due to missing symbols), or a
7875 non-functional executable which has undefined semantics.
7876 @emph{This means that
7877 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7878 with extreme care.}
7879 @end table
7880
7881 @node Elaboration Control
7882 @subsection Elaboration Control
7883
7884 @noindent
7885 The following switches provide additional control over the elaboration
7886 order. For full details see @ref{Elaboration Order Handling in GNAT}.
7887
7888 @table @option
7889 @item ^-p^/PESSIMISTIC_ELABORATION^
7890 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7891 Normally the binder attempts to choose an elaboration order that is
7892 likely to minimize the likelihood of an elaboration order error resulting
7893 in raising a @code{Program_Error} exception. This switch reverses the
7894 action of the binder, and requests that it deliberately choose an order
7895 that is likely to maximize the likelihood of an elaboration error.
7896 This is useful in ensuring portability and avoiding dependence on
7897 accidental fortuitous elaboration ordering.
7898
7899 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7900 switch if dynamic
7901 elaboration checking is used (@option{-gnatE} switch used for compilation).
7902 This is because in the default static elaboration mode, all necessary
7903 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
7904 These implicit pragmas are still respected by the binder in
7905 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7906 safe elaboration order is assured.
7907 @end table
7908
7909 @node Output Control
7910 @subsection Output Control
7911
7912 @noindent
7913 The following switches allow additional control over the output
7914 generated by the binder.
7915
7916 @table @option
7917 @c !sort!
7918
7919 @item ^-A^/BIND_FILE=ADA^
7920 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7921 Generate binder program in Ada (default). The binder program is named
7922 @file{b~@var{mainprog}.adb} by default. This can be changed with
7923 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7924
7925 @item ^-c^/NOOUTPUT^
7926 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7927 Check only. Do not generate the binder output file. In this mode the
7928 binder performs all error checks but does not generate an output file.
7929
7930 @item ^-C^/BIND_FILE=C^
7931 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7932 Generate binder program in C. The binder program is named
7933 @file{b_@var{mainprog}.c}.
7934 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7935 option.
7936
7937 @item ^-e^/ELABORATION_DEPENDENCIES^
7938 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7939 Output complete list of elaboration-order dependencies, showing the
7940 reason for each dependency. This output can be rather extensive but may
7941 be useful in diagnosing problems with elaboration order. The output is
7942 written to @file{stdout}.
7943
7944 @item ^-h^/HELP^
7945 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7946 Output usage information. The output is written to @file{stdout}.
7947
7948 @item ^-K^/LINKER_OPTION_LIST^
7949 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7950 Output linker options to @file{stdout}. Includes library search paths,
7951 contents of pragmas Ident and Linker_Options, and libraries added
7952 by @code{gnatbind}.
7953
7954 @item ^-l^/ORDER_OF_ELABORATION^
7955 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7956 Output chosen elaboration order. The output is written to @file{stdout}.
7957
7958 @item ^-O^/OBJECT_LIST^
7959 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7960 Output full names of all the object files that must be linked to provide
7961 the Ada component of the program. The output is written to @file{stdout}.
7962 This list includes the files explicitly supplied and referenced by the user
7963 as well as implicitly referenced run-time unit files. The latter are
7964 omitted if the corresponding units reside in shared libraries. The
7965 directory names for the run-time units depend on the system configuration.
7966
7967 @item ^-o ^/OUTPUT=^@var{file}
7968 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7969 Set name of output file to @var{file} instead of the normal
7970 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7971 binder generated body filename. In C mode you would normally give
7972 @var{file} an extension of @file{.c} because it will be a C source program.
7973 Note that if this option is used, then linking must be done manually.
7974 It is not possible to use gnatlink in this case, since it cannot locate
7975 the binder file.
7976
7977 @item ^-r^/RESTRICTION_LIST^
7978 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7979 Generate list of @code{pragma Restrictions} that could be applied to
7980 the current unit. This is useful for code audit purposes, and also may
7981 be used to improve code generation in some cases.
7982
7983 @end table
7984
7985 @node Binding with Non-Ada Main Programs
7986 @subsection Binding with Non-Ada Main Programs
7987
7988 @noindent
7989 In our description so far we have assumed that the main
7990 program is in Ada, and that the task of the binder is to generate a
7991 corresponding function @code{main} that invokes this Ada main
7992 program. GNAT also supports the building of executable programs where
7993 the main program is not in Ada, but some of the called routines are
7994 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7995 The following switch is used in this situation:
7996
7997 @table @option
7998 @item ^-n^/NOMAIN^
7999 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8000 No main program. The main program is not in Ada.
8001 @end table
8002
8003 @noindent
8004 In this case, most of the functions of the binder are still required,
8005 but instead of generating a main program, the binder generates a file
8006 containing the following callable routines:
8007
8008 @table @code
8009 @item adainit
8010 @findex adainit
8011 You must call this routine to initialize the Ada part of the program by
8012 calling the necessary elaboration routines. A call to @code{adainit} is
8013 required before the first call to an Ada subprogram.
8014
8015 Note that it is assumed that the basic execution environment must be setup
8016 to be appropriate for Ada execution at the point where the first Ada
8017 subprogram is called. In particular, if the Ada code will do any
8018 floating-point operations, then the FPU must be setup in an appropriate
8019 manner. For the case of the x86, for example, full precision mode is
8020 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8021 that the FPU is in the right state.
8022
8023 @item adafinal
8024 @findex adafinal
8025 You must call this routine to perform any library-level finalization
8026 required by the Ada subprograms. A call to @code{adafinal} is required
8027 after the last call to an Ada subprogram, and before the program
8028 terminates.
8029 @end table
8030
8031 @noindent
8032 If the @option{^-n^/NOMAIN^} switch
8033 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8034 @cindex Binder, multiple input files
8035 is given, more than one ALI file may appear on
8036 the command line for @code{gnatbind}. The normal @dfn{closure}
8037 calculation is performed for each of the specified units. Calculating
8038 the closure means finding out the set of units involved by tracing
8039 @code{with} references. The reason it is necessary to be able to
8040 specify more than one ALI file is that a given program may invoke two or
8041 more quite separate groups of Ada units.
8042
8043 The binder takes the name of its output file from the last specified ALI
8044 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8045 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8046 The output is an Ada unit in source form that can
8047 be compiled with GNAT unless the -C switch is used in which case the
8048 output is a C source file, which must be compiled using the C compiler.
8049 This compilation occurs automatically as part of the @command{gnatlink}
8050 processing.
8051
8052 Currently the GNAT run time requires a FPU using 80 bits mode
8053 precision. Under targets where this is not the default it is required to
8054 call GNAT.Float_Control.Reset before using floating point numbers (this
8055 include float computation, float input and output) in the Ada code. A
8056 side effect is that this could be the wrong mode for the foreign code
8057 where floating point computation could be broken after this call.
8058
8059 @node Binding Programs with No Main Subprogram
8060 @subsection Binding Programs with No Main Subprogram
8061
8062 @noindent
8063 It is possible to have an Ada program which does not have a main
8064 subprogram. This program will call the elaboration routines of all the
8065 packages, then the finalization routines.
8066
8067 The following switch is used to bind programs organized in this manner:
8068
8069 @table @option
8070 @item ^-z^/ZERO_MAIN^
8071 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8072 Normally the binder checks that the unit name given on the command line
8073 corresponds to a suitable main subprogram. When this switch is used,
8074 a list of ALI files can be given, and the execution of the program
8075 consists of elaboration of these units in an appropriate order. Note
8076 that the default wide character encoding method for standard Text_IO
8077 files is always set to Brackets if this switch is set (you can use
8078 the binder switch
8079 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8080 @end table
8081
8082 @node Command-Line Access
8083 @section Command-Line Access
8084
8085 @noindent
8086 The package @code{Ada.Command_Line} provides access to the command-line
8087 arguments and program name. In order for this interface to operate
8088 correctly, the two variables
8089
8090 @smallexample
8091 @group
8092 int gnat_argc;
8093 char **gnat_argv;
8094 @end group
8095 @end smallexample
8096
8097 @noindent
8098 @findex gnat_argv
8099 @findex gnat_argc
8100 are declared in one of the GNAT library routines. These variables must
8101 be set from the actual @code{argc} and @code{argv} values passed to the
8102 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8103 generates the C main program to automatically set these variables.
8104 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8105 set these variables. If they are not set, the procedures in
8106 @code{Ada.Command_Line} will not be available, and any attempt to use
8107 them will raise @code{Constraint_Error}. If command line access is
8108 required, your main program must set @code{gnat_argc} and
8109 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8110 it.
8111
8112 @node Search Paths for gnatbind
8113 @section Search Paths for @code{gnatbind}
8114
8115 @noindent
8116 The binder takes the name of an ALI file as its argument and needs to
8117 locate source files as well as other ALI files to verify object consistency.
8118
8119 For source files, it follows exactly the same search rules as @command{gcc}
8120 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8121 directories searched are:
8122
8123 @enumerate
8124 @item
8125 The directory containing the ALI file named in the command line, unless
8126 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8127
8128 @item
8129 All directories specified by @option{^-I^/SEARCH^}
8130 switches on the @code{gnatbind}
8131 command line, in the order given.
8132
8133 @item
8134 @findex ADA_PRJ_OBJECTS_FILE
8135 Each of the directories listed in the text file whose name is given
8136 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8137
8138 @noindent
8139 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8140 driver when project files are used. It should not normally be set
8141 by other means.
8142
8143 @item
8144 @findex ADA_OBJECTS_PATH
8145 Each of the directories listed in the value of the
8146 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8147 @ifset unw
8148 Construct this value
8149 exactly as the @env{PATH} environment variable: a list of directory
8150 names separated by colons (semicolons when working with the NT version
8151 of GNAT).
8152 @end ifset
8153 @ifset vms
8154 Normally, define this value as a logical name containing a comma separated
8155 list of directory names.
8156
8157 This variable can also be defined by means of an environment string
8158 (an argument to the HP C exec* set of functions).
8159
8160 Logical Name:
8161 @smallexample
8162 DEFINE ANOTHER_PATH FOO:[BAG]
8163 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8164 @end smallexample
8165
8166 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8167 first, followed by the standard Ada
8168 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8169 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8170 (Text_IO, Sequential_IO, etc)
8171 instead of the standard Ada packages. Thus, in order to get the standard Ada
8172 packages by default, ADA_OBJECTS_PATH must be redefined.
8173 @end ifset
8174
8175 @item
8176 The content of the @file{ada_object_path} file which is part of the GNAT
8177 installation tree and is used to store standard libraries such as the
8178 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8179 specified.
8180 @ifclear vms
8181 @ref{Installing a library}
8182 @end ifclear
8183 @end enumerate
8184
8185 @noindent
8186 In the binder the switch @option{^-I^/SEARCH^}
8187 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8188 is used to specify both source and
8189 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8190 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8191 instead if you want to specify
8192 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8193 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8194 if you want to specify library paths
8195 only. This means that for the binder
8196 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8197 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8198 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8199 The binder generates the bind file (a C language source file) in the
8200 current working directory.
8201
8202 @findex Ada
8203 @findex System
8204 @findex Interfaces
8205 @findex GNAT
8206 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8207 children make up the GNAT Run-Time Library, together with the package
8208 GNAT and its children, which contain a set of useful additional
8209 library functions provided by GNAT. The sources for these units are
8210 needed by the compiler and are kept together in one directory. The ALI
8211 files and object files generated by compiling the RTL are needed by the
8212 binder and the linker and are kept together in one directory, typically
8213 different from the directory containing the sources. In a normal
8214 installation, you need not specify these directory names when compiling
8215 or binding. Either the environment variables or the built-in defaults
8216 cause these files to be found.
8217
8218 Besides simplifying access to the RTL, a major use of search paths is
8219 in compiling sources from multiple directories. This can make
8220 development environments much more flexible.
8221
8222 @node Examples of gnatbind Usage
8223 @section Examples of @code{gnatbind} Usage
8224
8225 @noindent
8226 This section contains a number of examples of using the GNAT binding
8227 utility @code{gnatbind}.
8228
8229 @table @code
8230 @item gnatbind hello
8231 The main program @code{Hello} (source program in @file{hello.adb}) is
8232 bound using the standard switch settings. The generated main program is
8233 @file{b~hello.adb}. This is the normal, default use of the binder.
8234
8235 @ifclear vms
8236 @item gnatbind hello -o mainprog.adb
8237 @end ifclear
8238 @ifset vms
8239 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8240 @end ifset
8241 The main program @code{Hello} (source program in @file{hello.adb}) is
8242 bound using the standard switch settings. The generated main program is
8243 @file{mainprog.adb} with the associated spec in
8244 @file{mainprog.ads}. Note that you must specify the body here not the
8245 spec, in the case where the output is in Ada. Note that if this option
8246 is used, then linking must be done manually, since gnatlink will not
8247 be able to find the generated file.
8248
8249 @ifclear vms
8250 @item gnatbind main -C -o mainprog.c -x
8251 @end ifclear
8252 @ifset vms
8253 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8254 @end ifset
8255 The main program @code{Main} (source program in
8256 @file{main.adb}) is bound, excluding source files from the
8257 consistency checking, generating
8258 the file @file{mainprog.c}.
8259
8260 @ifclear vms
8261 @item gnatbind -x main_program -C -o mainprog.c
8262 This command is exactly the same as the previous example. Switches may
8263 appear anywhere in the command line, and single letter switches may be
8264 combined into a single switch.
8265 @end ifclear
8266
8267 @ifclear vms
8268 @item gnatbind -n math dbase -C -o ada-control.c
8269 @end ifclear
8270 @ifset vms
8271 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8272 @end ifset
8273 The main program is in a language other than Ada, but calls to
8274 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8275 to @code{gnatbind} generates the file @file{ada-control.c} containing
8276 the @code{adainit} and @code{adafinal} routines to be called before and
8277 after accessing the Ada units.
8278 @end table
8279
8280 @c ------------------------------------
8281 @node Linking Using gnatlink
8282 @chapter Linking Using @command{gnatlink}
8283 @c ------------------------------------
8284 @findex gnatlink
8285
8286 @noindent
8287 This chapter discusses @command{gnatlink}, a tool that links
8288 an Ada program and builds an executable file. This utility
8289 invokes the system linker ^(via the @command{gcc} command)^^
8290 with a correct list of object files and library references.
8291 @command{gnatlink} automatically determines the list of files and
8292 references for the Ada part of a program. It uses the binder file
8293 generated by the @command{gnatbind} to determine this list.
8294
8295 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8296 driver (see @ref{The GNAT Driver and Project Files}).
8297
8298 @menu
8299 * Running gnatlink::
8300 * Switches for gnatlink::
8301 @end menu
8302
8303 @node Running gnatlink
8304 @section Running @command{gnatlink}
8305
8306 @noindent
8307 The form of the @command{gnatlink} command is
8308
8309 @smallexample
8310 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
8311            [@var{non-Ada objects}] [@var{linker options}]
8312 @end smallexample
8313
8314 @noindent
8315 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8316 non-Ada objects
8317 or linker options) may be in any order, provided that no non-Ada object may
8318 be mistaken for a main @file{ALI} file.
8319 Any file name @file{F} without the @file{.ali}
8320 extension will be taken as the main @file{ALI} file if a file exists
8321 whose name is the concatenation of @file{F} and @file{.ali}.
8322
8323 @noindent
8324 @file{@var{mainprog}.ali} references the ALI file of the main program.
8325 The @file{.ali} extension of this file can be omitted. From this
8326 reference, @command{gnatlink} locates the corresponding binder file
8327 @file{b~@var{mainprog}.adb} and, using the information in this file along
8328 with the list of non-Ada objects and linker options, constructs a
8329 linker command file to create the executable.
8330
8331 The arguments other than the @command{gnatlink} switches and the main
8332 @file{ALI} file are passed to the linker uninterpreted.
8333 They typically include the names of
8334 object files for units written in other languages than Ada and any library
8335 references required to resolve references in any of these foreign language
8336 units, or in @code{Import} pragmas in any Ada units.
8337
8338 @var{linker options} is an optional list of linker specific
8339 switches.
8340 The default linker called by gnatlink is @command{gcc} which in
8341 turn calls the appropriate system linker.
8342 Standard options for the linker such as @option{-lmy_lib} or
8343 @option{-Ldir} can be added as is.
8344 For options that are not recognized by
8345 @command{gcc} as linker options, use the @command{gcc} switches
8346 @option{-Xlinker} or @option{-Wl,}.
8347 Refer to the GCC documentation for
8348 details. Here is an example showing how to generate a linker map:
8349
8350 @smallexample
8351 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8352 @end smallexample
8353
8354 Using @var{linker options} it is possible to set the program stack and
8355 heap size.
8356 @ifclear vms
8357 See @ref{Setting Stack Size from gnatlink} and
8358 @ref{Setting Heap Size from gnatlink}.
8359 @end ifclear
8360
8361 @command{gnatlink} determines the list of objects required by the Ada
8362 program and prepends them to the list of objects passed to the linker.
8363 @command{gnatlink} also gathers any arguments set by the use of
8364 @code{pragma Linker_Options} and adds them to the list of arguments
8365 presented to the linker.
8366
8367 @ifset vms
8368 @command{gnatlink} accepts the following types of extra files on the command
8369 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8370 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8371 handled according to their extension.
8372 @end ifset
8373
8374 @node Switches for gnatlink
8375 @section Switches for @command{gnatlink}
8376
8377 @noindent
8378 The following switches are available with the @command{gnatlink} utility:
8379
8380 @table @option
8381 @c !sort!
8382
8383 @item --version
8384 @cindex @option{--version} @command{gnatlink}
8385 Display Copyright and version, then exit disregarding all other options.
8386
8387 @item --help
8388 @cindex @option{--help} @command{gnatlink}
8389 If @option{--version} was not used, display usage, then exit disregarding
8390 all other options.
8391
8392 @item ^-A^/BIND_FILE=ADA^
8393 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8394 The binder has generated code in Ada. This is the default.
8395
8396 @item ^-C^/BIND_FILE=C^
8397 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8398 If instead of generating a file in Ada, the binder has generated one in
8399 C, then the linker needs to know about it. Use this switch to signal
8400 to @command{gnatlink} that the binder has generated C code rather than
8401 Ada code.
8402
8403 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8404 @cindex Command line length
8405 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8406 On some targets, the command line length is limited, and @command{gnatlink}
8407 will generate a separate file for the linker if the list of object files
8408 is too long.
8409 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8410 to be generated even if
8411 the limit is not exceeded. This is useful in some cases to deal with
8412 special situations where the command line length is exceeded.
8413
8414 @item ^-g^/DEBUG^
8415 @cindex Debugging information, including
8416 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8417 The option to include debugging information causes the Ada bind file (in
8418 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8419 @option{^-g^/DEBUG^}.
8420 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8421 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8422 Without @option{^-g^/DEBUG^}, the binder removes these files by
8423 default. The same procedure apply if a C bind file was generated using
8424 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8425 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8426
8427 @item ^-n^/NOCOMPILE^
8428 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8429 Do not compile the file generated by the binder. This may be used when
8430 a link is rerun with different options, but there is no need to recompile
8431 the binder file.
8432
8433 @item ^-v^/VERBOSE^
8434 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8435 Causes additional information to be output, including a full list of the
8436 included object files. This switch option is most useful when you want
8437 to see what set of object files are being used in the link step.
8438
8439 @item ^-v -v^/VERBOSE/VERBOSE^
8440 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8441 Very verbose mode. Requests that the compiler operate in verbose mode when
8442 it compiles the binder file, and that the system linker run in verbose mode.
8443
8444 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8445 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8446 @var{exec-name} specifies an alternate name for the generated
8447 executable program. If this switch is omitted, the executable has the same
8448 name as the main unit. For example, @code{gnatlink try.ali} creates
8449 an executable called @file{^try^TRY.EXE^}.
8450
8451 @ifclear vms
8452 @item -b @var{target}
8453 @cindex @option{-b} (@command{gnatlink})
8454 Compile your program to run on @var{target}, which is the name of a
8455 system configuration. You must have a GNAT cross-compiler built if
8456 @var{target} is not the same as your host system.
8457
8458 @item -B@var{dir}
8459 @cindex @option{-B} (@command{gnatlink})
8460 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8461 from @var{dir} instead of the default location. Only use this switch
8462 when multiple versions of the GNAT compiler are available. See the
8463 @command{gcc} manual page for further details. You would normally use the
8464 @option{-b} or @option{-V} switch instead.
8465
8466 @item --GCC=@var{compiler_name}
8467 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8468 Program used for compiling the binder file. The default is
8469 @command{gcc}. You need to use quotes around @var{compiler_name} if
8470 @code{compiler_name} contains spaces or other separator characters.
8471 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8472 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8473 inserted after your command name. Thus in the above example the compiler
8474 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8475 A limitation of this syntax is that the name and path name of the executable
8476 itself must not include any embedded spaces. If several
8477 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8478 is taken into account. However, all the additional switches are also taken
8479 into account. Thus,
8480 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8481 @option{--GCC="bar -x -y -z -t"}.
8482
8483 @item --LINK=@var{name}
8484 @cindex @option{--LINK=} (@command{gnatlink})
8485 @var{name} is the name of the linker to be invoked. This is especially
8486 useful in mixed language programs since languages such as C++ require
8487 their own linker to be used. When this switch is omitted, the default
8488 name for the linker is @command{gcc}. When this switch is used, the
8489 specified linker is called instead of @command{gcc} with exactly the same
8490 parameters that would have been passed to @command{gcc} so if the desired
8491 linker requires different parameters it is necessary to use a wrapper
8492 script that massages the parameters before invoking the real linker. It
8493 may be useful to control the exact invocation by using the verbose
8494 switch.
8495
8496 @end ifclear
8497
8498 @ifset vms
8499 @item /DEBUG=TRACEBACK
8500 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8501 This qualifier causes sufficient information to be included in the
8502 executable file to allow a traceback, but does not include the full
8503 symbol information needed by the debugger.
8504
8505 @item /IDENTIFICATION="<string>"
8506 @code{"<string>"} specifies the string to be stored in the image file
8507 identification field in the image header.
8508 It overrides any pragma @code{Ident} specified string.
8509
8510 @item /NOINHIBIT-EXEC
8511 Generate the executable file even if there are linker warnings.
8512
8513 @item /NOSTART_FILES
8514 Don't link in the object file containing the ``main'' transfer address.
8515 Used when linking with a foreign language main program compiled with an
8516 HP compiler.
8517
8518 @item /STATIC
8519 Prefer linking with object libraries over sharable images, even without
8520 /DEBUG.
8521 @end ifset
8522
8523 @end table
8524
8525 @node The GNAT Make Program gnatmake
8526 @chapter The GNAT Make Program @command{gnatmake}
8527 @findex gnatmake
8528
8529 @menu
8530 * Running gnatmake::
8531 * Switches for gnatmake::
8532 * Mode Switches for gnatmake::
8533 * Notes on the Command Line::
8534 * How gnatmake Works::
8535 * Examples of gnatmake Usage::
8536 @end menu
8537 @noindent
8538 A typical development cycle when working on an Ada program consists of
8539 the following steps:
8540
8541 @enumerate
8542 @item
8543 Edit some sources to fix bugs.
8544
8545 @item
8546 Add enhancements.
8547
8548 @item
8549 Compile all sources affected.
8550
8551 @item
8552 Rebind and relink.
8553
8554 @item
8555 Test.
8556 @end enumerate
8557
8558 @noindent
8559 The third step can be tricky, because not only do the modified files
8560 @cindex Dependency rules
8561 have to be compiled, but any files depending on these files must also be
8562 recompiled. The dependency rules in Ada can be quite complex, especially
8563 in the presence of overloading, @code{use} clauses, generics and inlined
8564 subprograms.
8565
8566 @command{gnatmake} automatically takes care of the third and fourth steps
8567 of this process. It determines which sources need to be compiled,
8568 compiles them, and binds and links the resulting object files.
8569
8570 Unlike some other Ada make programs, the dependencies are always
8571 accurately recomputed from the new sources. The source based approach of
8572 the GNAT compilation model makes this possible. This means that if
8573 changes to the source program cause corresponding changes in
8574 dependencies, they will always be tracked exactly correctly by
8575 @command{gnatmake}.
8576
8577 @node Running gnatmake
8578 @section Running @command{gnatmake}
8579
8580 @noindent
8581 The usual form of the @command{gnatmake} command is
8582
8583 @smallexample
8584 $ gnatmake [@var{switches}] @var{file_name}
8585       [@var{file_names}] [@var{mode_switches}]
8586 @end smallexample
8587
8588 @noindent
8589 The only required argument is one @var{file_name}, which specifies
8590 a compilation unit that is a main program. Several @var{file_names} can be
8591 specified: this will result in several executables being built.
8592 If @code{switches} are present, they can be placed before the first
8593 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8594 If @var{mode_switches} are present, they must always be placed after
8595 the last @var{file_name} and all @code{switches}.
8596
8597 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
8598 extension may be omitted from the @var{file_name} arguments. However, if
8599 you are using non-standard extensions, then it is required that the
8600 extension be given. A relative or absolute directory path can be
8601 specified in a @var{file_name}, in which case, the input source file will
8602 be searched for in the specified directory only. Otherwise, the input
8603 source file will first be searched in the directory where
8604 @command{gnatmake} was invoked and if it is not found, it will be search on
8605 the source path of the compiler as described in
8606 @ref{Search Paths and the Run-Time Library (RTL)}.
8607
8608 All @command{gnatmake} output (except when you specify
8609 @option{^-M^/DEPENDENCIES_LIST^}) is to
8610 @file{stderr}. The output produced by the
8611 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8612 @file{stdout}.
8613
8614 @node Switches for gnatmake
8615 @section Switches for @command{gnatmake}
8616
8617 @noindent
8618 You may specify any of the following switches to @command{gnatmake}:
8619
8620 @table @option
8621 @c !sort!
8622
8623 @item --version
8624 @cindex @option{--version} @command{gnatmake}
8625 Display Copyright and version, then exit disregarding all other options.
8626
8627 @item --help
8628 @cindex @option{--help} @command{gnatmake}
8629 If @option{--version} was not used, display usage, then exit disregarding
8630 all other options.
8631
8632 @ifclear vms
8633 @item --GCC=@var{compiler_name}
8634 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8635 Program used for compiling. The default is `@command{gcc}'. You need to use
8636 quotes around @var{compiler_name} if @code{compiler_name} contains
8637 spaces or other separator characters. As an example @option{--GCC="foo -x
8638 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8639 compiler. A limitation of this syntax is that the name and path name of
8640 the executable itself must not include any embedded spaces. Note that
8641 switch @option{-c} is always inserted after your command name. Thus in the
8642 above example the compiler command that will be used by @command{gnatmake}
8643 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
8644 used, only the last @var{compiler_name} is taken into account. However,
8645 all the additional switches are also taken into account. Thus,
8646 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8647 @option{--GCC="bar -x -y -z -t"}.
8648
8649 @item --GNATBIND=@var{binder_name}
8650 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8651 Program used for binding. The default is `@code{gnatbind}'. You need to
8652 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8653 or other separator characters. As an example @option{--GNATBIND="bar -x
8654 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8655 binder. Binder switches that are normally appended by @command{gnatmake}
8656 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8657 A limitation of this syntax is that the name and path name of the executable
8658 itself must not include any embedded spaces.
8659
8660 @item --GNATLINK=@var{linker_name}
8661 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8662 Program used for linking. The default is `@command{gnatlink}'. You need to
8663 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8664 or other separator characters. As an example @option{--GNATLINK="lan -x
8665 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8666 linker. Linker switches that are normally appended by @command{gnatmake} to
8667 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8668 A limitation of this syntax is that the name and path name of the executable
8669 itself must not include any embedded spaces.
8670
8671 @end ifclear
8672
8673 @item ^-a^/ALL_FILES^
8674 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8675 Consider all files in the make process, even the GNAT internal system
8676 files (for example, the predefined Ada library files), as well as any
8677 locked files. Locked files are files whose ALI file is write-protected.
8678 By default,
8679 @command{gnatmake} does not check these files,
8680 because the assumption is that the GNAT internal files are properly up
8681 to date, and also that any write protected ALI files have been properly
8682 installed. Note that if there is an installation problem, such that one
8683 of these files is not up to date, it will be properly caught by the
8684 binder.
8685 You may have to specify this switch if you are working on GNAT
8686 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8687 in conjunction with @option{^-f^/FORCE_COMPILE^}
8688 if you need to recompile an entire application,
8689 including run-time files, using special configuration pragmas,
8690 such as a @code{Normalize_Scalars} pragma.
8691
8692 By default
8693 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8694 internal files with
8695 @ifclear vms
8696 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8697 @end ifclear
8698 @ifset vms
8699 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8700 @end ifset
8701
8702 @item ^-b^/ACTIONS=BIND^
8703 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8704 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8705 compilation and binding, but no link.
8706 Can be combined with @option{^-l^/ACTIONS=LINK^}
8707 to do binding and linking. When not combined with
8708 @option{^-c^/ACTIONS=COMPILE^}
8709 all the units in the closure of the main program must have been previously
8710 compiled and must be up to date. The root unit specified by @var{file_name}
8711 may be given without extension, with the source extension or, if no GNAT
8712 Project File is specified, with the ALI file extension.
8713
8714 @item ^-c^/ACTIONS=COMPILE^
8715 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8716 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8717 is also specified. Do not perform linking, except if both
8718 @option{^-b^/ACTIONS=BIND^} and
8719  @option{^-l^/ACTIONS=LINK^} are also specified.
8720 If the root unit specified by @var{file_name} is not a main unit, this is the
8721 default. Otherwise @command{gnatmake} will attempt binding and linking
8722 unless all objects are up to date and the executable is more recent than
8723 the objects.
8724
8725 @item ^-C^/MAPPING^
8726 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8727 Use a temporary mapping file. A mapping file is a way to communicate to the
8728 compiler two mappings: from unit names to file names (without any directory
8729 information) and from file names to path names (with full directory
8730 information). These mappings are used by the compiler to short-circuit the path
8731 search. When @command{gnatmake} is invoked with this switch, it will create
8732 a temporary mapping file, initially populated by the project manager,
8733 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8734 Each invocation of the compiler will add the newly accessed sources to the
8735 mapping file. This will improve the source search during the next invocation
8736 of the compiler.
8737
8738 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8739 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8740 Use a specific mapping file. The file, specified as a path name (absolute or
8741 relative) by this switch, should already exist, otherwise the switch is
8742 ineffective. The specified mapping file will be communicated to the compiler.
8743 This switch is not compatible with a project file
8744 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8745 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8746
8747 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8748 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
8749 Put all object files and ALI file in directory @var{dir}.
8750 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8751 and ALI files go in the current working directory.
8752
8753 This switch cannot be used when using a project file.
8754
8755 @ifclear vms
8756 @item -eL
8757 @cindex @option{-eL} (@command{gnatmake})
8758 Follow all symbolic links when processing project files.
8759 @end ifclear
8760
8761 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
8762 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
8763 Output the commands for the compiler, the binder and the linker
8764 on ^standard output^SYS$OUTPUT^,
8765 instead of ^standard error^SYS$ERROR^.
8766
8767 @item ^-f^/FORCE_COMPILE^
8768 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
8769 Force recompilations. Recompile all sources, even though some object
8770 files may be up to date, but don't recompile predefined or GNAT internal
8771 files or locked files (files with a write-protected ALI file),
8772 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8773
8774 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8775 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
8776 When using project files, if some errors or warnings are detected during
8777 parsing and verbose mode is not in effect (no use of switch
8778 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8779 file, rather than its simple file name.
8780
8781 @item ^-g^/DEBUG^
8782 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
8783 Enable debugging. This switch is simply passed to the compiler and to the
8784 linker.
8785
8786 @item ^-i^/IN_PLACE^
8787 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
8788 In normal mode, @command{gnatmake} compiles all object files and ALI files
8789 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8790 then instead object files and ALI files that already exist are overwritten
8791 in place. This means that once a large project is organized into separate
8792 directories in the desired manner, then @command{gnatmake} will automatically
8793 maintain and update this organization. If no ALI files are found on the
8794 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8795 the new object and ALI files are created in the
8796 directory containing the source being compiled. If another organization
8797 is desired, where objects and sources are kept in different directories,
8798 a useful technique is to create dummy ALI files in the desired directories.
8799 When detecting such a dummy file, @command{gnatmake} will be forced to
8800 recompile the corresponding source file, and it will be put the resulting
8801 object and ALI files in the directory where it found the dummy file.
8802
8803 @item ^-j^/PROCESSES=^@var{n}
8804 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
8805 @cindex Parallel make
8806 Use @var{n} processes to carry out the (re)compilations. On a
8807 multiprocessor machine compilations will occur in parallel. In the
8808 event of compilation errors, messages from various compilations might
8809 get interspersed (but @command{gnatmake} will give you the full ordered
8810 list of failing compiles at the end). If this is problematic, rerun
8811 the make process with n set to 1 to get a clean list of messages.
8812
8813 @item ^-k^/CONTINUE_ON_ERROR^
8814 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
8815 Keep going. Continue as much as possible after a compilation error. To
8816 ease the programmer's task in case of compilation errors, the list of
8817 sources for which the compile fails is given when @command{gnatmake}
8818 terminates.
8819
8820 If @command{gnatmake} is invoked with several @file{file_names} and with this
8821 switch, if there are compilation errors when building an executable,
8822 @command{gnatmake} will not attempt to build the following executables.
8823
8824 @item ^-l^/ACTIONS=LINK^
8825 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
8826 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8827 and linking. Linking will not be performed if combined with
8828 @option{^-c^/ACTIONS=COMPILE^}
8829 but not with @option{^-b^/ACTIONS=BIND^}.
8830 When not combined with @option{^-b^/ACTIONS=BIND^}
8831 all the units in the closure of the main program must have been previously
8832 compiled and must be up to date, and the main program needs to have been bound.
8833 The root unit specified by @var{file_name}
8834 may be given without extension, with the source extension or, if no GNAT
8835 Project File is specified, with the ALI file extension.
8836
8837 @item ^-m^/MINIMAL_RECOMPILATION^
8838 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
8839 Specify that the minimum necessary amount of recompilations
8840 be performed. In this mode @command{gnatmake} ignores time
8841 stamp differences when the only
8842 modifications to a source file consist in adding/removing comments,
8843 empty lines, spaces or tabs. This means that if you have changed the
8844 comments in a source file or have simply reformatted it, using this
8845 switch will tell @command{gnatmake} not to recompile files that depend on it
8846 (provided other sources on which these files depend have undergone no
8847 semantic modifications). Note that the debugging information may be
8848 out of date with respect to the sources if the @option{-m} switch causes
8849 a compilation to be switched, so the use of this switch represents a
8850 trade-off between compilation time and accurate debugging information.
8851
8852 @item ^-M^/DEPENDENCIES_LIST^
8853 @cindex Dependencies, producing list
8854 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
8855 Check if all objects are up to date. If they are, output the object
8856 dependences to @file{stdout} in a form that can be directly exploited in
8857 a @file{Makefile}. By default, each source file is prefixed with its
8858 (relative or absolute) directory name. This name is whatever you
8859 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8860 and @option{^-I^/SEARCH^} switches. If you use
8861 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8862 @option{^-q^/QUIET^}
8863 (see below), only the source file names,
8864 without relative paths, are output. If you just specify the
8865 @option{^-M^/DEPENDENCIES_LIST^}
8866 switch, dependencies of the GNAT internal system files are omitted. This
8867 is typically what you want. If you also specify
8868 the @option{^-a^/ALL_FILES^} switch,
8869 dependencies of the GNAT internal files are also listed. Note that
8870 dependencies of the objects in external Ada libraries (see switch
8871 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8872 are never reported.
8873
8874 @item ^-n^/DO_OBJECT_CHECK^
8875 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
8876 Don't compile, bind, or link. Checks if all objects are up to date.
8877 If they are not, the full name of the first file that needs to be
8878 recompiled is printed.
8879 Repeated use of this option, followed by compiling the indicated source
8880 file, will eventually result in recompiling all required units.
8881
8882 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8883 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
8884 Output executable name. The name of the final executable program will be
8885 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8886 name for the executable will be the name of the input file in appropriate form
8887 for an executable file on the host system.
8888
8889 This switch cannot be used when invoking @command{gnatmake} with several
8890 @file{file_names}.
8891
8892 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
8893 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
8894 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
8895 automatically missing object directories, library directories and exec
8896 directories.
8897
8898 @item ^-P^/PROJECT_FILE=^@var{project}
8899 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
8900 Use project file @var{project}. Only one such switch can be used.
8901 @xref{gnatmake and Project Files}.
8902
8903 @item ^-q^/QUIET^
8904 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
8905 Quiet. When this flag is not set, the commands carried out by
8906 @command{gnatmake} are displayed.
8907
8908 @item ^-s^/SWITCH_CHECK/^
8909 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
8910 Recompile if compiler switches have changed since last compilation.
8911 All compiler switches but -I and -o are taken into account in the
8912 following way:
8913 orders between different ``first letter'' switches are ignored, but
8914 orders between same switches are taken into account. For example,
8915 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8916 is equivalent to @option{-O -g}.
8917
8918 This switch is recommended when Integrated Preprocessing is used.
8919
8920 @item ^-u^/UNIQUE^
8921 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
8922 Unique. Recompile at most the main files. It implies -c. Combined with
8923 -f, it is equivalent to calling the compiler directly. Note that using
8924 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8925 (@pxref{Project Files and Main Subprograms}).
8926
8927 @item ^-U^/ALL_PROJECTS^
8928 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
8929 When used without a project file or with one or several mains on the command
8930 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8931 on the command line, all sources of all project files are checked and compiled
8932 if not up to date, and libraries are rebuilt, if necessary.
8933
8934 @item ^-v^/REASONS^
8935 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
8936 Verbose. Display the reason for all recompilations @command{gnatmake}
8937 decides are necessary, with the highest verbosity level.
8938
8939 @item ^-vl^/LOW_VERBOSITY^
8940 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
8941 Verbosity level Low. Display fewer lines than in verbosity Medium.
8942
8943 @item ^-vm^/MEDIUM_VERBOSITY^
8944 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
8945 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
8946
8947 @item ^-vh^/HIGH_VERBOSITY^
8948 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
8949 Verbosity level High. Equivalent to ^-v^/REASONS^.
8950
8951 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8952 Indicate the verbosity of the parsing of GNAT project files.
8953 @xref{Switches Related to Project Files}.
8954
8955 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8956 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
8957 Indicate that sources that are not part of any Project File may be compiled.
8958 Normally, when using Project Files, only sources that are part of a Project
8959 File may be compile. When this switch is used, a source outside of all Project
8960 Files may be compiled. The ALI file and the object file will be put in the
8961 object directory of the main Project. The compilation switches used will only
8962 be those specified on the command line.
8963
8964 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8965 Indicate that external variable @var{name} has the value @var{value}.
8966 The Project Manager will use this value for occurrences of
8967 @code{external(name)} when parsing the project file.
8968 @xref{Switches Related to Project Files}.
8969
8970 @item ^-z^/NOMAIN^
8971 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
8972 No main subprogram. Bind and link the program even if the unit name
8973 given on the command line is a package name. The resulting executable
8974 will execute the elaboration routines of the package and its closure,
8975 then the finalization routines.
8976
8977 @end table
8978
8979 @table @asis
8980 @item @command{gcc} @asis{switches}
8981 @ifclear vms
8982 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
8983 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
8984 @end ifclear
8985 @ifset vms
8986 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8987 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8988 automatically treated as a compiler switch, and passed on to all
8989 compilations that are carried out.
8990 @end ifset
8991 @end table
8992
8993 @noindent
8994 Source and library search path switches:
8995
8996 @table @option
8997 @c !sort!
8998 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8999 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9000 When looking for source files also look in directory @var{dir}.
9001 The order in which source files search is undertaken is
9002 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9003
9004 @item ^-aL^/SKIP_MISSING=^@var{dir}
9005 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9006 Consider @var{dir} as being an externally provided Ada library.
9007 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9008 files have been located in directory @var{dir}. This allows you to have
9009 missing bodies for the units in @var{dir} and to ignore out of date bodies
9010 for the same units. You still need to specify
9011 the location of the specs for these units by using the switches
9012 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9013 or @option{^-I^/SEARCH=^@var{dir}}.
9014 Note: this switch is provided for compatibility with previous versions
9015 of @command{gnatmake}. The easier method of causing standard libraries
9016 to be excluded from consideration is to write-protect the corresponding
9017 ALI files.
9018
9019 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9020 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9021 When searching for library and object files, look in directory
9022 @var{dir}. The order in which library files are searched is described in
9023 @ref{Search Paths for gnatbind}.
9024
9025 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9026 @cindex Search paths, for @command{gnatmake}
9027 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9028 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9029 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9030
9031 @item ^-I^/SEARCH=^@var{dir}
9032 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9033 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9034 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9035
9036 @item ^-I-^/NOCURRENT_DIRECTORY^
9037 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9038 @cindex Source files, suppressing search
9039 Do not look for source files in the directory containing the source
9040 file named in the command line.
9041 Do not look for ALI or object files in the directory
9042 where @command{gnatmake} was invoked.
9043
9044 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9045 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9046 @cindex Linker libraries
9047 Add directory @var{dir} to the list of directories in which the linker
9048 will search for libraries. This is equivalent to
9049 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9050 @ifclear vms
9051 Furthermore, under Windows, the sources pointed to by the libraries path
9052 set in the registry are not searched for.
9053 @end ifclear
9054
9055 @item -nostdinc
9056 @cindex @option{-nostdinc} (@command{gnatmake})
9057 Do not look for source files in the system default directory.
9058
9059 @item -nostdlib
9060 @cindex @option{-nostdlib} (@command{gnatmake})
9061 Do not look for library files in the system default directory.
9062
9063 @item --RTS=@var{rts-path}
9064 @cindex @option{--RTS} (@command{gnatmake})
9065 Specifies the default location of the runtime library. GNAT looks for the
9066 runtime
9067 in the following directories, and stops as soon as a valid runtime is found
9068 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9069 @file{ada_object_path} present):
9070
9071 @itemize @bullet
9072 @item <current directory>/$rts_path
9073
9074 @item <default-search-dir>/$rts_path
9075
9076 @item <default-search-dir>/rts-$rts_path
9077 @end itemize
9078
9079 @noindent
9080 The selected path is handled like a normal RTS path.
9081
9082 @end table
9083
9084 @node Mode Switches for gnatmake
9085 @section Mode Switches for @command{gnatmake}
9086
9087 @noindent
9088 The mode switches (referred to as @code{mode_switches}) allow the
9089 inclusion of switches that are to be passed to the compiler itself, the
9090 binder or the linker. The effect of a mode switch is to cause all
9091 subsequent switches up to the end of the switch list, or up to the next
9092 mode switch, to be interpreted as switches to be passed on to the
9093 designated component of GNAT.
9094
9095 @table @option
9096 @c !sort!
9097 @item -cargs @var{switches}
9098 @cindex @option{-cargs} (@command{gnatmake})
9099 Compiler switches. Here @var{switches} is a list of switches
9100 that are valid switches for @command{gcc}. They will be passed on to
9101 all compile steps performed by @command{gnatmake}.
9102
9103 @item -bargs @var{switches}
9104 @cindex @option{-bargs} (@command{gnatmake})
9105 Binder switches. Here @var{switches} is a list of switches
9106 that are valid switches for @code{gnatbind}. They will be passed on to
9107 all bind steps performed by @command{gnatmake}.
9108
9109 @item -largs @var{switches}
9110 @cindex @option{-largs} (@command{gnatmake})
9111 Linker switches. Here @var{switches} is a list of switches
9112 that are valid switches for @command{gnatlink}. They will be passed on to
9113 all link steps performed by @command{gnatmake}.
9114
9115 @item -margs @var{switches}
9116 @cindex @option{-margs} (@command{gnatmake})
9117 Make switches. The switches are directly interpreted by @command{gnatmake},
9118 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9119 or @option{-largs}.
9120 @end table
9121
9122 @node Notes on the Command Line
9123 @section Notes on the Command Line
9124
9125 @noindent
9126 This section contains some additional useful notes on the operation
9127 of the @command{gnatmake} command.
9128
9129 @itemize @bullet
9130 @item
9131 @cindex Recompilation, by @command{gnatmake}
9132 If @command{gnatmake} finds no ALI files, it recompiles the main program
9133 and all other units required by the main program.
9134 This means that @command{gnatmake}
9135 can be used for the initial compile, as well as during subsequent steps of
9136 the development cycle.
9137
9138 @item
9139 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9140 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9141 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9142 warning.
9143
9144 @item
9145 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9146 is used to specify both source and
9147 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9148 instead if you just want to specify
9149 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9150 if you want to specify library paths
9151 only.
9152
9153 @item
9154 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9155 This may conveniently be used to exclude standard libraries from
9156 consideration and in particular it means that the use of the
9157 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9158 unless @option{^-a^/ALL_FILES^} is also specified.
9159
9160 @item
9161 @command{gnatmake} has been designed to make the use of Ada libraries
9162 particularly convenient. Assume you have an Ada library organized
9163 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9164 of your Ada compilation units,
9165 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9166 specs of these units, but no bodies. Then to compile a unit
9167 stored in @code{main.adb}, which uses this Ada library you would just type
9168
9169 @smallexample
9170 @ifclear vms
9171 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9172 @end ifclear
9173 @ifset vms
9174 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9175            /SKIP_MISSING=@i{[OBJ_DIR]} main
9176 @end ifset
9177 @end smallexample
9178
9179 @item
9180 Using @command{gnatmake} along with the
9181 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9182 switch provides a mechanism for avoiding unnecessary recompilations. Using
9183 this switch,
9184 you can update the comments/format of your
9185 source files without having to recompile everything. Note, however, that
9186 adding or deleting lines in a source files may render its debugging
9187 info obsolete. If the file in question is a spec, the impact is rather
9188 limited, as that debugging info will only be useful during the
9189 elaboration phase of your program. For bodies the impact can be more
9190 significant. In all events, your debugger will warn you if a source file
9191 is more recent than the corresponding object, and alert you to the fact
9192 that the debugging information may be out of date.
9193 @end itemize
9194
9195 @node How gnatmake Works
9196 @section How @command{gnatmake} Works
9197
9198 @noindent
9199 Generally @command{gnatmake} automatically performs all necessary
9200 recompilations and you don't need to worry about how it works. However,
9201 it may be useful to have some basic understanding of the @command{gnatmake}
9202 approach and in particular to understand how it uses the results of
9203 previous compilations without incorrectly depending on them.
9204
9205 First a definition: an object file is considered @dfn{up to date} if the
9206 corresponding ALI file exists and if all the source files listed in the
9207 dependency section of this ALI file have time stamps matching those in
9208 the ALI file. This means that neither the source file itself nor any
9209 files that it depends on have been modified, and hence there is no need
9210 to recompile this file.
9211
9212 @command{gnatmake} works by first checking if the specified main unit is up
9213 to date. If so, no compilations are required for the main unit. If not,
9214 @command{gnatmake} compiles the main program to build a new ALI file that
9215 reflects the latest sources. Then the ALI file of the main unit is
9216 examined to find all the source files on which the main program depends,
9217 and @command{gnatmake} recursively applies the above procedure on all these
9218 files.
9219
9220 This process ensures that @command{gnatmake} only trusts the dependencies
9221 in an existing ALI file if they are known to be correct. Otherwise it
9222 always recompiles to determine a new, guaranteed accurate set of
9223 dependencies. As a result the program is compiled ``upside down'' from what may
9224 be more familiar as the required order of compilation in some other Ada
9225 systems. In particular, clients are compiled before the units on which
9226 they depend. The ability of GNAT to compile in any order is critical in
9227 allowing an order of compilation to be chosen that guarantees that
9228 @command{gnatmake} will recompute a correct set of new dependencies if
9229 necessary.
9230
9231 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9232 imported by several of the executables, it will be recompiled at most once.
9233
9234 Note: when using non-standard naming conventions
9235 (@pxref{Using Other File Names}), changing through a configuration pragmas
9236 file the version of a source and invoking @command{gnatmake} to recompile may
9237 have no effect, if the previous version of the source is still accessible
9238 by @command{gnatmake}. It may be necessary to use the switch
9239 ^-f^/FORCE_COMPILE^.
9240
9241 @node Examples of gnatmake Usage
9242 @section Examples of @command{gnatmake} Usage
9243
9244 @table @code
9245 @item gnatmake hello.adb
9246 Compile all files necessary to bind and link the main program
9247 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9248 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9249
9250 @item gnatmake main1 main2 main3
9251 Compile all files necessary to bind and link the main programs
9252 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9253 (containing unit @code{Main2}) and @file{main3.adb}
9254 (containing unit @code{Main3}) and bind and link the resulting object files
9255 to generate three executable files @file{^main1^MAIN1.EXE^},
9256 @file{^main2^MAIN2.EXE^}
9257 and @file{^main3^MAIN3.EXE^}.
9258
9259 @ifclear vms
9260 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9261 @end ifclear
9262
9263 @ifset vms
9264 @item gnatmake Main_Unit /QUIET
9265    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9266    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9267 @end ifset
9268 Compile all files necessary to bind and link the main program unit
9269 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9270 be done with optimization level 2 and the order of elaboration will be
9271 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9272 displaying commands it is executing.
9273 @end table
9274
9275 @c *************************
9276 @node Improving Performance
9277 @chapter Improving Performance
9278 @cindex Improving performance
9279
9280 @noindent
9281 This chapter presents several topics related to program performance.
9282 It first describes some of the tradeoffs that need to be considered
9283 and some of the techniques for making your program run faster.
9284 It then documents the @command{gnatelim} tool and unused subprogram/data
9285 elimination feature, which can reduce the size of program executables.
9286
9287 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9288 driver (see @ref{The GNAT Driver and Project Files}).
9289
9290 @ifnottex
9291 @menu
9292 * Performance Considerations::
9293 * Reducing Size of Ada Executables with gnatelim::
9294 * Reducing Size of Executables with unused subprogram/data elimination::
9295 @end menu
9296 @end ifnottex
9297
9298 @c *****************************
9299 @node Performance Considerations
9300 @section Performance Considerations
9301
9302 @noindent
9303 The GNAT system provides a number of options that allow a trade-off
9304 between
9305
9306 @itemize @bullet
9307 @item
9308 performance of the generated code
9309
9310 @item
9311 speed of compilation
9312
9313 @item
9314 minimization of dependences and recompilation
9315
9316 @item
9317 the degree of run-time checking.
9318 @end itemize
9319
9320 @noindent
9321 The defaults (if no options are selected) aim at improving the speed
9322 of compilation and minimizing dependences, at the expense of performance
9323 of the generated code:
9324
9325 @itemize @bullet
9326 @item
9327 no optimization
9328
9329 @item
9330 no inlining of subprogram calls
9331
9332 @item
9333 all run-time checks enabled except overflow and elaboration checks
9334 @end itemize
9335
9336 @noindent
9337 These options are suitable for most program development purposes. This
9338 chapter describes how you can modify these choices, and also provides
9339 some guidelines on debugging optimized code.
9340
9341 @menu
9342 * Controlling Run-Time Checks::
9343 * Use of Restrictions::
9344 * Optimization Levels::
9345 * Debugging Optimized Code::
9346 * Inlining of Subprograms::
9347 * Other Optimization Switches::
9348 * Optimization and Strict Aliasing::
9349
9350 @ifset vms
9351 * Coverage Analysis::
9352 @end ifset
9353 @end menu
9354
9355 @node Controlling Run-Time Checks
9356 @subsection Controlling Run-Time Checks
9357
9358 @noindent
9359 By default, GNAT generates all run-time checks, except arithmetic overflow
9360 checking for integer operations and checks for access before elaboration on
9361 subprogram calls. The latter are not required in default mode, because all
9362 necessary checking is done at compile time.
9363 @cindex @option{-gnatp} (@command{gcc})
9364 @cindex @option{-gnato} (@command{gcc})
9365 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9366 be modified. @xref{Run-Time Checks}.
9367
9368 Our experience is that the default is suitable for most development
9369 purposes.
9370
9371 We treat integer overflow specially because these
9372 are quite expensive and in our experience are not as important as other
9373 run-time checks in the development process. Note that division by zero
9374 is not considered an overflow check, and divide by zero checks are
9375 generated where required by default.
9376
9377 Elaboration checks are off by default, and also not needed by default, since
9378 GNAT uses a static elaboration analysis approach that avoids the need for
9379 run-time checking. This manual contains a full chapter discussing the issue
9380 of elaboration checks, and if the default is not satisfactory for your use,
9381 you should read this chapter.
9382
9383 For validity checks, the minimal checks required by the Ada Reference
9384 Manual (for case statements and assignments to array elements) are on
9385 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9386 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9387 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9388 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9389 are also suppressed entirely if @option{-gnatp} is used.
9390
9391 @cindex Overflow checks
9392 @cindex Checks, overflow
9393 @findex Suppress
9394 @findex Unsuppress
9395 @cindex pragma Suppress
9396 @cindex pragma Unsuppress
9397 Note that the setting of the switches controls the default setting of
9398 the checks. They may be modified using either @code{pragma Suppress} (to
9399 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9400 checks) in the program source.
9401
9402 @node Use of Restrictions
9403 @subsection Use of Restrictions
9404
9405 @noindent
9406 The use of pragma Restrictions allows you to control which features are
9407 permitted in your program. Apart from the obvious point that if you avoid
9408 relatively expensive features like finalization (enforceable by the use
9409 of pragma Restrictions (No_Finalization), the use of this pragma does not
9410 affect the generated code in most cases.
9411
9412 One notable exception to this rule is that the possibility of task abort
9413 results in some distributed overhead, particularly if finalization or
9414 exception handlers are used. The reason is that certain sections of code
9415 have to be marked as non-abortable.
9416
9417 If you use neither the @code{abort} statement, nor asynchronous transfer
9418 of control (@code{select @dots{} then abort}), then this distributed overhead
9419 is removed, which may have a general positive effect in improving
9420 overall performance.  Especially code involving frequent use of tasking
9421 constructs and controlled types will show much improved performance.
9422 The relevant restrictions pragmas are
9423
9424 @smallexample @c ada
9425    pragma Restrictions (No_Abort_Statements);
9426    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9427 @end smallexample
9428
9429 @noindent
9430 It is recommended that these restriction pragmas be used if possible. Note
9431 that this also means that you can write code without worrying about the
9432 possibility of an immediate abort at any point.
9433
9434 @node Optimization Levels
9435 @subsection Optimization Levels
9436 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9437
9438 @noindent
9439 The default is optimization off. This results in the fastest compile
9440 times, but GNAT makes absolutely no attempt to optimize, and the
9441 generated programs are considerably larger and slower than when
9442 optimization is enabled. You can use the
9443 @ifclear vms
9444 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9445 @option{-O2}, @option{-O3}, and @option{-Os})
9446 @end ifclear
9447 @ifset vms
9448 @code{OPTIMIZE} qualifier
9449 @end ifset
9450 to @command{gcc} to control the optimization level:
9451
9452 @table @option
9453 @item ^-O0^/OPTIMIZE=NONE^
9454 No optimization (the default);
9455 generates unoptimized code but has
9456 the fastest compilation time.
9457
9458 Note that many other compilers do fairly extensive optimization
9459 even if "no optimization" is specified. When using gcc, it is
9460 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9461 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9462 really does mean no optimization at all. This difference between
9463 gcc and other compilers should be kept in mind when doing
9464 performance comparisons.
9465
9466 @item ^-O1^/OPTIMIZE=SOME^
9467 Moderate optimization;
9468 optimizes reasonably well but does not
9469 degrade compilation time significantly.
9470
9471 @item ^-O2^/OPTIMIZE=ALL^
9472 @ifset vms
9473 @itemx /OPTIMIZE=DEVELOPMENT
9474 @end ifset
9475 Full optimization;
9476 generates highly optimized code and has
9477 the slowest compilation time.
9478
9479 @item ^-O3^/OPTIMIZE=INLINING^
9480 Full optimization as in @option{-O2},
9481 and also attempts automatic inlining of small
9482 subprograms within a unit (@pxref{Inlining of Subprograms}).
9483
9484 @item ^-Os^/OPTIMIZE=SPACE^
9485 Optimize space usage of resulting program.
9486 @end table
9487
9488 @noindent
9489 Higher optimization levels perform more global transformations on the
9490 program and apply more expensive analysis algorithms in order to generate
9491 faster and more compact code. The price in compilation time, and the
9492 resulting improvement in execution time,
9493 both depend on the particular application and the hardware environment.
9494 You should experiment to find the best level for your application.
9495
9496 The @option{^-Os^/OPTIMIZE=SPACE^} switch is independent of the time
9497 optimizations, so you can specify both @option{^-Os^/OPTIMIZE=SPACE^}
9498 and a time optimization on the same compile command.
9499
9500 Since the precise set of optimizations done at each level will vary from
9501 release to release (and sometime from target to target), it is best to think
9502 of the optimization settings in general terms.
9503 The @cite{Using GNU GCC} manual contains details about
9504 ^the @option{-O} settings and a number of @option{-f} options that^how to^
9505 individually enable or disable specific optimizations.
9506
9507 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
9508 been tested extensively at all optimization levels. There are some bugs
9509 which appear only with optimization turned on, but there have also been
9510 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9511 level of optimization does not improve the reliability of the code
9512 generator, which in practice is highly reliable at all optimization
9513 levels.
9514
9515 Note regarding the use of @option{-O3}: The use of this optimization level
9516 is generally discouraged with GNAT, since it often results in larger
9517 executables which run more slowly. See further discussion of this point
9518 in @ref{Inlining of Subprograms}.
9519
9520 @node Debugging Optimized Code
9521 @subsection Debugging Optimized Code
9522 @cindex Debugging optimized code
9523 @cindex Optimization and debugging
9524
9525 @noindent
9526 Although it is possible to do a reasonable amount of debugging at
9527 @ifclear vms
9528 nonzero optimization levels,
9529 the higher the level the more likely that
9530 @end ifclear
9531 @ifset vms
9532 @option{/OPTIMIZE} settings other than @code{NONE},
9533 such settings will make it more likely that
9534 @end ifset
9535 source-level constructs will have been eliminated by optimization.
9536 For example, if a loop is strength-reduced, the loop
9537 control variable may be completely eliminated and thus cannot be
9538 displayed in the debugger.
9539 This can only happen at @option{-O2} or @option{-O3}.
9540 Explicit temporary variables that you code might be eliminated at
9541 ^level^setting^ @option{-O1} or higher.
9542
9543 The use of the @option{^-g^/DEBUG^} switch,
9544 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9545 which is needed for source-level debugging,
9546 affects the size of the program executable on disk,
9547 and indeed the debugging information can be quite large.
9548 However, it has no effect on the generated code (and thus does not
9549 degrade performance)
9550
9551 Since the compiler generates debugging tables for a compilation unit before
9552 it performs optimizations, the optimizing transformations may invalidate some
9553 of the debugging data.  You therefore need to anticipate certain
9554 anomalous situations that may arise while debugging optimized code.
9555 These are the most common cases:
9556
9557 @enumerate
9558 @item
9559 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
9560 commands show
9561 the PC bouncing back and forth in the code.  This may result from any of
9562 the following optimizations:
9563
9564 @itemize @bullet
9565 @item
9566 @i{Common subexpression elimination:} using a single instance of code for a
9567 quantity that the source computes several times.  As a result you
9568 may not be able to stop on what looks like a statement.
9569
9570 @item
9571 @i{Invariant code motion:} moving an expression that does not change within a
9572 loop, to the beginning of the loop.
9573
9574 @item
9575 @i{Instruction scheduling:} moving instructions so as to
9576 overlap loads and stores (typically) with other code, or in
9577 general to move computations of values closer to their uses. Often
9578 this causes you to pass an assignment statement without the assignment
9579 happening and then later bounce back to the statement when the
9580 value is actually needed.  Placing a breakpoint on a line of code
9581 and then stepping over it may, therefore, not always cause all the
9582 expected side-effects.
9583 @end itemize
9584
9585 @item
9586 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9587 two identical pieces of code are merged and the program counter suddenly
9588 jumps to a statement that is not supposed to be executed, simply because
9589 it (and the code following) translates to the same thing as the code
9590 that @emph{was} supposed to be executed.  This effect is typically seen in
9591 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9592 a @code{break} in a C @code{^switch^switch^} statement.
9593
9594 @item
9595 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9596 There are various reasons for this effect:
9597
9598 @itemize @bullet
9599 @item
9600 In a subprogram prologue, a parameter may not yet have been moved to its
9601 ``home''.
9602
9603 @item
9604 A variable may be dead, and its register re-used.  This is
9605 probably the most common cause.
9606
9607 @item
9608 As mentioned above, the assignment of a value to a variable may
9609 have been moved.
9610
9611 @item
9612 A variable may be eliminated entirely by value propagation or
9613 other means.  In this case, GCC may incorrectly generate debugging
9614 information for the variable
9615 @end itemize
9616
9617 @noindent
9618 In general, when an unexpected value appears for a local variable or parameter
9619 you should first ascertain if that value was actually computed by
9620 your program, as opposed to being incorrectly reported by the debugger.
9621 Record fields or
9622 array elements in an object designated by an access value
9623 are generally less of a problem, once you have ascertained that the access
9624 value is sensible.
9625 Typically, this means checking variables in the preceding code and in the
9626 calling subprogram to verify that the value observed is explainable from other
9627 values (one must apply the procedure recursively to those
9628 other values); or re-running the code and stopping a little earlier
9629 (perhaps before the call) and stepping to better see how the variable obtained
9630 the value in question; or continuing to step @emph{from} the point of the
9631 strange value to see if code motion had simply moved the variable's
9632 assignments later.
9633 @end enumerate
9634
9635 @noindent
9636 In light of such anomalies, a recommended technique is to use @option{-O0}
9637 early in the software development cycle, when extensive debugging capabilities
9638 are most needed, and then move to @option{-O1} and later @option{-O2} as
9639 the debugger becomes less critical.
9640 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9641 a release management issue.
9642 @ifclear vms
9643 Note that if you use @option{-g} you can then use the @command{strip} program
9644 on the resulting executable,
9645 which removes both debugging information and global symbols.
9646 @end ifclear
9647
9648 @node Inlining of Subprograms
9649 @subsection Inlining of Subprograms
9650
9651 @noindent
9652 A call to a subprogram in the current unit is inlined if all the
9653 following conditions are met:
9654
9655 @itemize @bullet
9656 @item
9657 The optimization level is at least @option{-O1}.
9658
9659 @item
9660 The called subprogram is suitable for inlining: It must be small enough
9661 and not contain nested subprograms or anything else that @command{gcc}
9662 cannot support in inlined subprograms.
9663
9664 @item
9665 The call occurs after the definition of the body of the subprogram.
9666
9667 @item
9668 @cindex pragma Inline
9669 @findex Inline
9670 Either @code{pragma Inline} applies to the subprogram or it is
9671 small and automatic inlining (optimization level @option{-O3}) is
9672 specified.
9673 @end itemize
9674
9675 @noindent
9676 Calls to subprograms in @code{with}'ed units are normally not inlined.
9677 To achieve actual inlining (that is, replacement of the call by the code
9678 in the body of the subprogram), the following conditions must all be true.
9679
9680 @itemize @bullet
9681 @item
9682 The optimization level is at least @option{-O1}.
9683
9684 @item
9685 The called subprogram is suitable for inlining: It must be small enough
9686 and not contain nested subprograms or anything else @command{gcc} cannot
9687 support in inlined subprograms.
9688
9689 @item
9690 The call appears in a body (not in a package spec).
9691
9692 @item
9693 There is a @code{pragma Inline} for the subprogram.
9694
9695 @item
9696 @cindex @option{-gnatn} (@command{gcc})
9697 The @option{^-gnatn^/INLINE^} switch
9698 is used in the @command{gcc} command line
9699 @end itemize
9700
9701 Even if all these conditions are met, it may not be possible for
9702 the compiler to inline the call, due to the length of the body,
9703 or features in the body that make it impossible for the compiler
9704 to do the inlining.
9705
9706 Note that specifying the @option{-gnatn} switch causes additional
9707 compilation dependencies. Consider the following:
9708
9709 @smallexample @c ada
9710 @cartouche
9711 package R is
9712    procedure Q;
9713    pragma Inline (Q);
9714 end R;
9715 package body R is
9716    @dots{}
9717 end R;
9718
9719 with R;
9720 procedure Main is
9721 begin
9722    @dots{}
9723    R.Q;
9724 end Main;
9725 @end cartouche
9726 @end smallexample
9727
9728 @noindent
9729 With the default behavior (no @option{-gnatn} switch specified), the
9730 compilation of the @code{Main} procedure depends only on its own source,
9731 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9732 means that editing the body of @code{R} does not require recompiling
9733 @code{Main}.
9734
9735 On the other hand, the call @code{R.Q} is not inlined under these
9736 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9737 is compiled, the call will be inlined if the body of @code{Q} is small
9738 enough, but now @code{Main} depends on the body of @code{R} in
9739 @file{r.adb} as well as on the spec. This means that if this body is edited,
9740 the main program must be recompiled. Note that this extra dependency
9741 occurs whether or not the call is in fact inlined by @command{gcc}.
9742
9743 The use of front end inlining with @option{-gnatN} generates similar
9744 additional dependencies.
9745
9746 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
9747 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9748 can be used to prevent
9749 all inlining. This switch overrides all other conditions and ensures
9750 that no inlining occurs. The extra dependences resulting from
9751 @option{-gnatn} will still be active, even if
9752 this switch is used to suppress the resulting inlining actions.
9753
9754 Note regarding the use of @option{-O3}: There is no difference in inlining
9755 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9756 pragma @code{Inline} assuming the use of @option{-gnatn}
9757 or @option{-gnatN} (the switches that activate inlining). If you have used
9758 pragma @code{Inline} in appropriate cases, then it is usually much better
9759 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9760 in this case only has the effect of inlining subprograms you did not
9761 think should be inlined. We often find that the use of @option{-O3} slows
9762 down code by performing excessive inlining, leading to increased instruction
9763 cache pressure from the increased code size. So the bottom line here is
9764 that you should not automatically assume that @option{-O3} is better than
9765 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9766 it actually improves performance.
9767
9768 @node Other Optimization Switches
9769 @subsection Other Optimization Switches
9770 @cindex Optimization Switches
9771
9772 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
9773 @command{gcc} optimization switches are potentially usable. These switches
9774 have not been extensively tested with GNAT but can generally be expected
9775 to work. Examples of switches in this category are
9776 @option{-funroll-loops} and
9777 the various target-specific @option{-m} options (in particular, it has been
9778 observed that @option{-march=pentium4} can significantly improve performance
9779 on appropriate machines). For full details of these switches, see the
9780 @command{gcc} manual.
9781
9782 @node Optimization and Strict Aliasing
9783 @subsection Optimization and Strict Aliasing
9784 @cindex Aliasing
9785 @cindex Strict Aliasing
9786 @cindex No_Strict_Aliasing
9787
9788 @noindent
9789 The strong typing capabilities of Ada allow an optimizer to generate
9790 efficient code in situations where other languages would be forced to
9791 make worst case assumptions preventing such optimizations. Consider
9792 the following example:
9793
9794 @smallexample @c ada
9795 @cartouche
9796 procedure R is
9797    type Int1 is new Integer;
9798    type Int2 is new Integer;
9799    type Int1A is access Int1;
9800    type Int2A is access Int2;
9801    Int1V : Int1A;
9802    Int2V : Int2A;
9803    @dots{}
9804
9805 begin
9806    @dots{}
9807    for J in Data'Range loop
9808       if Data (J) = Int1V.all then
9809          Int2V.all := Int2V.all + 1;
9810       end if;
9811    end loop;
9812    @dots{}
9813 end R;
9814 @end cartouche
9815 @end smallexample
9816
9817 @noindent
9818 In this example, since the variable @code{Int1V} can only access objects
9819 of type @code{Int1}, and @code{Int2V} can only access objects of type
9820 @code{Int2}, there is no possibility that the assignment to
9821 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9822 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9823 for all iterations of the loop and avoid the extra memory reference
9824 required to dereference it each time through the loop.
9825
9826 This kind of optimization, called strict aliasing analysis, is
9827 triggered by specifying an optimization level of @option{-O2} or
9828 higher and allows @code{GNAT} to generate more efficient code
9829 when access values are involved.
9830
9831 However, although this optimization is always correct in terms of
9832 the formal semantics of the Ada Reference Manual, difficulties can
9833 arise if features like @code{Unchecked_Conversion} are used to break
9834 the typing system. Consider the following complete program example:
9835
9836 @smallexample @c ada
9837 @cartouche
9838 package p1 is
9839    type int1 is new integer;
9840    type int2 is new integer;
9841    type a1 is access int1;
9842    type a2 is access int2;
9843 end p1;
9844
9845 with p1; use p1;
9846 package p2 is
9847    function to_a2 (Input : a1) return a2;
9848 end p2;
9849
9850 with Unchecked_Conversion;
9851 package body p2 is
9852    function to_a2 (Input : a1) return a2 is
9853       function to_a2u is
9854         new Unchecked_Conversion (a1, a2);
9855    begin
9856       return to_a2u (Input);
9857    end to_a2;
9858 end p2;
9859
9860 with p2; use p2;
9861 with p1; use p1;
9862 with Text_IO; use Text_IO;
9863 procedure m is
9864    v1 : a1 := new int1;
9865    v2 : a2 := to_a2 (v1);
9866 begin
9867    v1.all := 1;
9868    v2.all := 0;
9869    put_line (int1'image (v1.all));
9870 end;
9871 @end cartouche
9872 @end smallexample
9873
9874 @noindent
9875 This program prints out 0 in @option{-O0} or @option{-O1}
9876 mode, but it prints out 1 in @option{-O2} mode. That's
9877 because in strict aliasing mode, the compiler can and
9878 does assume that the assignment to @code{v2.all} could not
9879 affect the value of @code{v1.all}, since different types
9880 are involved.
9881
9882 This behavior is not a case of non-conformance with the standard, since
9883 the Ada RM specifies that an unchecked conversion where the resulting
9884 bit pattern is not a correct value of the target type can result in an
9885 abnormal value and attempting to reference an abnormal value makes the
9886 execution of a program erroneous.  That's the case here since the result
9887 does not point to an object of type @code{int2}.  This means that the
9888 effect is entirely unpredictable.
9889
9890 However, although that explanation may satisfy a language
9891 lawyer, in practice an applications programmer expects an
9892 unchecked conversion involving pointers to create true
9893 aliases and the behavior of printing 1 seems plain wrong.
9894 In this case, the strict aliasing optimization is unwelcome.
9895
9896 Indeed the compiler recognizes this possibility, and the
9897 unchecked conversion generates a warning:
9898
9899 @smallexample
9900 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9901 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9902 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9903 @end smallexample
9904
9905 @noindent
9906 Unfortunately the problem is recognized when compiling the body of
9907 package @code{p2}, but the actual "bad" code is generated while
9908 compiling the body of @code{m} and this latter compilation does not see
9909 the suspicious @code{Unchecked_Conversion}.
9910
9911 As implied by the warning message, there are approaches you can use to
9912 avoid the unwanted strict aliasing optimization in a case like this.
9913
9914 One possibility is to simply avoid the use of @option{-O2}, but
9915 that is a bit drastic, since it throws away a number of useful
9916 optimizations that do not involve strict aliasing assumptions.
9917
9918 A less drastic approach is to compile the program using the
9919 option @option{-fno-strict-aliasing}. Actually it is only the
9920 unit containing the dereferencing of the suspicious pointer
9921 that needs to be compiled. So in this case, if we compile
9922 unit @code{m} with this switch, then we get the expected
9923 value of zero printed. Analyzing which units might need
9924 the switch can be painful, so a more reasonable approach
9925 is to compile the entire program with options @option{-O2}
9926 and @option{-fno-strict-aliasing}. If the performance is
9927 satisfactory with this combination of options, then the
9928 advantage is that the entire issue of possible "wrong"
9929 optimization due to strict aliasing is avoided.
9930
9931 To avoid the use of compiler switches, the configuration
9932 pragma @code{No_Strict_Aliasing} with no parameters may be
9933 used to specify that for all access types, the strict
9934 aliasing optimization should be suppressed.
9935
9936 However, these approaches are still overkill, in that they causes
9937 all manipulations of all access values to be deoptimized. A more
9938 refined approach is to concentrate attention on the specific
9939 access type identified as problematic.
9940
9941 First, if a careful analysis of uses of the pointer shows
9942 that there are no possible problematic references, then
9943 the warning can be suppressed by bracketing the
9944 instantiation of @code{Unchecked_Conversion} to turn
9945 the warning off:
9946
9947 @smallexample @c ada
9948    pragma Warnings (Off);
9949    function to_a2u is
9950      new Unchecked_Conversion (a1, a2);
9951    pragma Warnings (On);
9952 @end smallexample
9953
9954 @noindent
9955 Of course that approach is not appropriate for this particular
9956 example, since indeed there is a problematic reference. In this
9957 case we can take one of two other approaches.
9958
9959 The first possibility is to move the instantiation of unchecked
9960 conversion to the unit in which the type is declared. In
9961 this example, we would move the instantiation of
9962 @code{Unchecked_Conversion} from the body of package
9963 @code{p2} to the spec of package @code{p1}. Now the
9964 warning disappears. That's because any use of the
9965 access type knows there is a suspicious unchecked
9966 conversion, and the strict aliasing optimization
9967 is automatically suppressed for the type.
9968
9969 If it is not practical to move the unchecked conversion to the same unit
9970 in which the destination access type is declared (perhaps because the
9971 source type is not visible in that unit), you may use pragma
9972 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9973 same declarative sequence as the declaration of the access type:
9974
9975 @smallexample @c ada
9976    type a2 is access int2;
9977    pragma No_Strict_Aliasing (a2);
9978 @end smallexample
9979
9980 @noindent
9981 Here again, the compiler now knows that the strict aliasing optimization
9982 should be suppressed for any reference to type @code{a2} and the
9983 expected behavior is obtained.
9984
9985 Finally, note that although the compiler can generate warnings for
9986 simple cases of unchecked conversions, there are tricker and more
9987 indirect ways of creating type incorrect aliases which the compiler
9988 cannot detect. Examples are the use of address overlays and unchecked
9989 conversions involving composite types containing access types as
9990 components. In such cases, no warnings are generated, but there can
9991 still be aliasing problems. One safe coding practice is to forbid the
9992 use of address clauses for type overlaying, and to allow unchecked
9993 conversion only for primitive types. This is not really a significant
9994 restriction since any possible desired effect can be achieved by
9995 unchecked conversion of access values.
9996
9997 @ifset vms
9998 @node Coverage Analysis
9999 @subsection Coverage Analysis
10000
10001 @noindent
10002 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10003 the user to determine the distribution of execution time across a program,
10004 @pxref{Profiling} for details of usage.
10005 @end ifset
10006
10007 @node Reducing Size of Ada Executables with gnatelim
10008 @section Reducing Size of Ada Executables with @code{gnatelim}
10009 @findex gnatelim
10010
10011 @noindent
10012 This section describes @command{gnatelim}, a tool which detects unused
10013 subprograms and helps the compiler to create a smaller executable for your
10014 program.
10015
10016 @menu
10017 * About gnatelim::
10018 * Running gnatelim::
10019 * Correcting the List of Eliminate Pragmas::
10020 * Making Your Executables Smaller::
10021 * Summary of the gnatelim Usage Cycle::
10022 @end menu
10023
10024 @node About gnatelim
10025 @subsection About @code{gnatelim}
10026
10027 @noindent
10028 When a program shares a set of Ada
10029 packages with other programs, it may happen that this program uses
10030 only a fraction of the subprograms defined in these packages. The code
10031 created for these unused subprograms increases the size of the executable.
10032
10033 @code{gnatelim} tracks unused subprograms in an Ada program and
10034 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10035 subprograms that are declared but never called. By placing the list of
10036 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10037 recompiling your program, you may decrease the size of its executable,
10038 because the compiler will not generate the code for 'eliminated' subprograms.
10039 See GNAT Reference Manual for more information about this pragma.
10040
10041 @code{gnatelim} needs as its input data the name of the main subprogram
10042 and a bind file for a main subprogram.
10043
10044 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10045 the main subprogram. @code{gnatelim} can work with both Ada and C
10046 bind files; when both are present, it uses the Ada bind file.
10047 The following commands will build the program and create the bind file:
10048
10049 @smallexample
10050 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10051 $ gnatbind main_prog
10052 @end smallexample
10053
10054 Note that @code{gnatelim} needs neither object nor ALI files.
10055
10056 @node Running gnatelim
10057 @subsection Running @code{gnatelim}
10058
10059 @noindent
10060 @code{gnatelim} has the following command-line interface:
10061
10062 @smallexample
10063 $ gnatelim [options] name
10064 @end smallexample
10065
10066 @noindent
10067 @code{name} should be a name of a source file that contains the main subprogram
10068 of a program (partition).
10069
10070 @code{gnatelim} has the following switches:
10071
10072 @table @option
10073 @c !sort!
10074 @item ^-q^/QUIET^
10075 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10076 Quiet mode: by default @code{gnatelim} outputs to the standard error
10077 stream the number of program units left to be processed. This option turns
10078 this trace off.
10079
10080 @item ^-v^/VERBOSE^
10081 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10082 Verbose mode: @code{gnatelim} version information is printed as Ada
10083 comments to the standard output stream. Also, in addition to the number of
10084 program units left @code{gnatelim} will output the name of the current unit
10085 being processed.
10086
10087 @item ^-a^/ALL^
10088 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10089 Also look for subprograms from the GNAT run time that can be eliminated. Note
10090 that when @file{gnat.adc} is produced using this switch, the entire program
10091 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10092
10093 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10094 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10095 When looking for source files also look in directory @var{dir}. Specifying
10096 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10097 sources in the current directory.
10098
10099 @item ^-b^/BIND_FILE=^@var{bind_file}
10100 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10101 Specifies @var{bind_file} as the bind file to process. If not set, the name
10102 of the bind file is computed from the full expanded Ada name
10103 of a main subprogram.
10104
10105 @item ^-C^/CONFIG_FILE=^@var{config_file}
10106 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10107 Specifies a file @var{config_file} that contains configuration pragmas. The
10108 file must be specified with full path.
10109
10110 @item ^--GCC^/COMPILER^=@var{compiler_name}
10111 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10112 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10113 available on the path.
10114
10115 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10116 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10117 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10118 available on the path.
10119 @end table
10120
10121 @noindent
10122 @code{gnatelim} sends its output to the standard output stream, and all the
10123 tracing and debug information is sent to the standard error stream.
10124 In order to produce a proper GNAT configuration file
10125 @file{gnat.adc}, redirection must be used:
10126
10127 @smallexample
10128 @ifset vms
10129 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10130 @end ifset
10131 @ifclear vms
10132 $ gnatelim main_prog.adb > gnat.adc
10133 @end ifclear
10134 @end smallexample
10135
10136 @ifclear vms
10137 @noindent
10138 or
10139
10140 @smallexample
10141 $ gnatelim main_prog.adb >> gnat.adc
10142 @end smallexample
10143
10144 @noindent
10145 in order to append the @code{gnatelim} output to the existing contents of
10146 @file{gnat.adc}.
10147 @end ifclear
10148
10149 @node Correcting the List of Eliminate Pragmas
10150 @subsection Correcting the List of Eliminate Pragmas
10151
10152 @noindent
10153 In some rare cases @code{gnatelim} may try to eliminate
10154 subprograms that are actually called in the program. In this case, the
10155 compiler will generate an error message of the form:
10156
10157 @smallexample
10158 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10159 @end smallexample
10160
10161 @noindent
10162 You will need to manually remove the wrong @code{Eliminate} pragmas from
10163 the @file{gnat.adc} file. You should recompile your program
10164 from scratch after that, because you need a consistent @file{gnat.adc} file
10165 during the entire compilation.
10166
10167 @node Making Your Executables Smaller
10168 @subsection Making Your Executables Smaller
10169
10170 @noindent
10171 In order to get a smaller executable for your program you now have to
10172 recompile the program completely with the new @file{gnat.adc} file
10173 created by @code{gnatelim} in your current directory:
10174
10175 @smallexample
10176 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10177 @end smallexample
10178
10179 @noindent
10180 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10181 recompile everything
10182 with the set of pragmas @code{Eliminate} that you have obtained with
10183 @command{gnatelim}).
10184
10185 Be aware that the set of @code{Eliminate} pragmas is specific to each
10186 program. It is not recommended to merge sets of @code{Eliminate}
10187 pragmas created for different programs in one @file{gnat.adc} file.
10188
10189 @node Summary of the gnatelim Usage Cycle
10190 @subsection Summary of the gnatelim Usage Cycle
10191
10192 @noindent
10193 Here is a quick summary of the steps to be taken in order to reduce
10194 the size of your executables with @code{gnatelim}. You may use
10195 other GNAT options to control the optimization level,
10196 to produce the debugging information, to set search path, etc.
10197
10198 @enumerate
10199 @item
10200 Produce a bind file
10201
10202 @smallexample
10203 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10204 $ gnatbind main_prog
10205 @end smallexample
10206
10207 @item
10208 Generate a list of @code{Eliminate} pragmas
10209 @smallexample
10210 @ifset vms
10211 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10212 @end ifset
10213 @ifclear vms
10214 $ gnatelim main_prog >[>] gnat.adc
10215 @end ifclear
10216 @end smallexample
10217
10218 @item
10219 Recompile the application
10220
10221 @smallexample
10222 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10223 @end smallexample
10224
10225 @end enumerate
10226
10227 @node Reducing Size of Executables with unused subprogram/data elimination
10228 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10229 @findex unused subprogram/data elimination
10230
10231 @noindent
10232 This section describes how you can eliminate unused subprograms and data from
10233 your executable just by setting options at compilation time.
10234
10235 @menu
10236 * About unused subprogram/data elimination::
10237 * Compilation options::
10238 * Example of unused subprogram/data elimination::
10239 @end menu
10240
10241 @node About unused subprogram/data elimination
10242 @subsection About unused subprogram/data elimination
10243
10244 @noindent
10245 By default, an executable contains all code and data of its composing objects
10246 (directly linked or coming from statically linked libraries), even data or code
10247 never used by this executable.
10248
10249 This feature will allow you to eliminate such unused code from your
10250 executable, making it smaller (in disk and in memory).
10251
10252 This functionality is available on all Linux platforms except for the IA-64
10253 architecture and on all cross platforms using the ELF binary file format.
10254 In both cases GNU binutils version 2.16 or later are required to enable it.
10255
10256 @node Compilation options
10257 @subsection Compilation options
10258
10259 @noindent
10260 The operation of eliminating the unused code and data from the final executable
10261 is directly performed by the linker.
10262
10263 In order to do this, it has to work with objects compiled with the
10264 following options:
10265 @option{-ffunction-sections} @option{-fdata-sections}.
10266 @cindex @option{-ffunction-sections} (@command{gcc})
10267 @cindex @option{-fdata-sections} (@command{gcc})
10268 These options are usable with C and Ada files.
10269 They will place respectively each
10270 function or data in a separate section in the resulting object file.
10271
10272 Once the objects and static libraries are created with these options, the
10273 linker can perform the dead code elimination. You can do this by setting
10274 the @option{-Wl,--gc-sections} option to gcc command or in the
10275 @option{-largs} section of @command{gnatmake}. This will perform a
10276 garbage collection of code and data never referenced.
10277
10278 If the linker performs a partial link (@option{-r} ld linker option), then you
10279 will need to provide one or several entry point using the
10280 @option{-e} / @option{--entry} ld option.
10281
10282 Note that objects compiled without the @option{-ffunction-sections} and
10283 @option{-fdata-sections} options can still be linked with the executable.
10284 However, no dead code elimination will be performed on those objects (they will
10285 be linked as is).
10286
10287 The GNAT static library is now compiled with -ffunction-sections and
10288 -fdata-sections on some platforms. This allows you to eliminate the unused code
10289 and data of the GNAT library from your executable.
10290
10291 @node Example of unused subprogram/data elimination
10292 @subsection Example of unused subprogram/data elimination
10293
10294 @noindent
10295 Here is a simple example:
10296
10297 @smallexample @c ada
10298 with Aux;
10299
10300 procedure Test is
10301 begin
10302    Aux.Used (10);
10303 end Test;
10304
10305 package Aux is
10306    Used_Data   : Integer;
10307    Unused_Data : Integer;
10308
10309    procedure Used   (Data : Integer);
10310    procedure Unused (Data : Integer);
10311 end Aux;
10312
10313 package body Aux is
10314    procedure Used (Data : Integer) is
10315    begin
10316       Used_Data := Data;
10317    end Used;
10318
10319    procedure Unused (Data : Integer) is
10320    begin
10321       Unused_Data := Data;
10322    end Unused;
10323 end Aux;
10324 @end smallexample
10325
10326 @noindent
10327 @code{Unused} and @code{Unused_Data} are never referenced in this code
10328 excerpt, and hence they may be safely removed from the final executable.
10329
10330 @smallexample
10331 $ gnatmake test
10332
10333 $ nm test | grep used
10334 020015f0 T aux__unused
10335 02005d88 B aux__unused_data
10336 020015cc T aux__used
10337 02005d84 B aux__used_data
10338
10339 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10340      -largs -Wl,--gc-sections
10341
10342 $ nm test | grep used
10343 02005350 T aux__used
10344 0201ffe0 B aux__used_data
10345 @end smallexample
10346
10347 @noindent
10348 It can be observed that the procedure @code{Unused} and the object
10349 @code{Unused_Data} are removed by the linker when using the
10350 appropriate options.
10351
10352 @c ********************************
10353 @node Renaming Files Using gnatchop
10354 @chapter Renaming Files Using @code{gnatchop}
10355 @findex gnatchop
10356
10357 @noindent
10358 This chapter discusses how to handle files with multiple units by using
10359 the @code{gnatchop} utility. This utility is also useful in renaming
10360 files to meet the standard GNAT default file naming conventions.
10361
10362 @menu
10363 * Handling Files with Multiple Units::
10364 * Operating gnatchop in Compilation Mode::
10365 * Command Line for gnatchop::
10366 * Switches for gnatchop::
10367 * Examples of gnatchop Usage::
10368 @end menu
10369
10370 @node Handling Files with Multiple Units
10371 @section Handling Files with Multiple Units
10372
10373 @noindent
10374 The basic compilation model of GNAT requires that a file submitted to the
10375 compiler have only one unit and there be a strict correspondence
10376 between the file name and the unit name.
10377
10378 The @code{gnatchop} utility allows both of these rules to be relaxed,
10379 allowing GNAT to process files which contain multiple compilation units
10380 and files with arbitrary file names. @code{gnatchop}
10381 reads the specified file and generates one or more output files,
10382 containing one unit per file. The unit and the file name correspond,
10383 as required by GNAT.
10384
10385 If you want to permanently restructure a set of ``foreign'' files so that
10386 they match the GNAT rules, and do the remaining development using the
10387 GNAT structure, you can simply use @command{gnatchop} once, generate the
10388 new set of files and work with them from that point on.
10389
10390 Alternatively, if you want to keep your files in the ``foreign'' format,
10391 perhaps to maintain compatibility with some other Ada compilation
10392 system, you can set up a procedure where you use @command{gnatchop} each
10393 time you compile, regarding the source files that it writes as temporary
10394 files that you throw away.
10395
10396 @node Operating gnatchop in Compilation Mode
10397 @section Operating gnatchop in Compilation Mode
10398
10399 @noindent
10400 The basic function of @code{gnatchop} is to take a file with multiple units
10401 and split it into separate files. The boundary between files is reasonably
10402 clear, except for the issue of comments and pragmas. In default mode, the
10403 rule is that any pragmas between units belong to the previous unit, except
10404 that configuration pragmas always belong to the following unit. Any comments
10405 belong to the following unit. These rules
10406 almost always result in the right choice of
10407 the split point without needing to mark it explicitly and most users will
10408 find this default to be what they want. In this default mode it is incorrect to
10409 submit a file containing only configuration pragmas, or one that ends in
10410 configuration pragmas, to @code{gnatchop}.
10411
10412 However, using a special option to activate ``compilation mode'',
10413 @code{gnatchop}
10414 can perform another function, which is to provide exactly the semantics
10415 required by the RM for handling of configuration pragmas in a compilation.
10416 In the absence of configuration pragmas (at the main file level), this
10417 option has no effect, but it causes such configuration pragmas to be handled
10418 in a quite different manner.
10419
10420 First, in compilation mode, if @code{gnatchop} is given a file that consists of
10421 only configuration pragmas, then this file is appended to the
10422 @file{gnat.adc} file in the current directory. This behavior provides
10423 the required behavior described in the RM for the actions to be taken
10424 on submitting such a file to the compiler, namely that these pragmas
10425 should apply to all subsequent compilations in the same compilation
10426 environment. Using GNAT, the current directory, possibly containing a
10427 @file{gnat.adc} file is the representation
10428 of a compilation environment. For more information on the
10429 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
10430
10431 Second, in compilation mode, if @code{gnatchop}
10432 is given a file that starts with
10433 configuration pragmas, and contains one or more units, then these
10434 configuration pragmas are prepended to each of the chopped files. This
10435 behavior provides the required behavior described in the RM for the
10436 actions to be taken on compiling such a file, namely that the pragmas
10437 apply to all units in the compilation, but not to subsequently compiled
10438 units.
10439
10440 Finally, if configuration pragmas appear between units, they are appended
10441 to the previous unit. This results in the previous unit being illegal,
10442 since the compiler does not accept configuration pragmas that follow
10443 a unit. This provides the required RM behavior that forbids configuration
10444 pragmas other than those preceding the first compilation unit of a
10445 compilation.
10446
10447 For most purposes, @code{gnatchop} will be used in default mode. The
10448 compilation mode described above is used only if you need exactly
10449 accurate behavior with respect to compilations, and you have files
10450 that contain multiple units and configuration pragmas. In this
10451 circumstance the use of @code{gnatchop} with the compilation mode
10452 switch provides the required behavior, and is for example the mode
10453 in which GNAT processes the ACVC tests.
10454
10455 @node Command Line for gnatchop
10456 @section Command Line for @code{gnatchop}
10457
10458 @noindent
10459 The @code{gnatchop} command has the form:
10460
10461 @smallexample
10462 $ gnatchop switches @var{file name} [@var{file name} @var{file name} @dots{}]
10463       [@var{directory}]
10464 @end smallexample
10465
10466 @noindent
10467 The only required argument is the file name of the file to be chopped.
10468 There are no restrictions on the form of this file name. The file itself
10469 contains one or more Ada units, in normal GNAT format, concatenated
10470 together. As shown, more than one file may be presented to be chopped.
10471
10472 When run in default mode, @code{gnatchop} generates one output file in
10473 the current directory for each unit in each of the files.
10474
10475 @var{directory}, if specified, gives the name of the directory to which
10476 the output files will be written. If it is not specified, all files are
10477 written to the current directory.
10478
10479 For example, given a
10480 file called @file{hellofiles} containing
10481
10482 @smallexample @c ada
10483 @group
10484 @cartouche
10485 procedure hello;
10486
10487 with Text_IO; use Text_IO;
10488 procedure hello is
10489 begin
10490    Put_Line ("Hello");
10491 end hello;
10492 @end cartouche
10493 @end group
10494 @end smallexample
10495
10496 @noindent
10497 the command
10498
10499 @smallexample
10500 $ gnatchop ^hellofiles^HELLOFILES.^
10501 @end smallexample
10502
10503 @noindent
10504 generates two files in the current directory, one called
10505 @file{hello.ads} containing the single line that is the procedure spec,
10506 and the other called @file{hello.adb} containing the remaining text. The
10507 original file is not affected. The generated files can be compiled in
10508 the normal manner.
10509
10510 @noindent
10511 When gnatchop is invoked on a file that is empty or that contains only empty
10512 lines and/or comments, gnatchop will not fail, but will not produce any
10513 new sources.
10514
10515 For example, given a
10516 file called @file{toto.txt} containing
10517
10518 @smallexample @c ada
10519 @group
10520 @cartouche
10521 --  Just a comment
10522 @end cartouche
10523 @end group
10524 @end smallexample
10525
10526 @noindent
10527 the command
10528
10529 @smallexample
10530 $ gnatchop ^toto.txt^TOT.TXT^
10531 @end smallexample
10532
10533 @noindent
10534 will not produce any new file and will result in the following warnings:
10535
10536 @smallexample
10537 toto.txt:1:01: warning: empty file, contains no compilation units
10538 no compilation units found
10539 no source files written
10540 @end smallexample
10541
10542 @node Switches for gnatchop
10543 @section Switches for @code{gnatchop}
10544
10545 @noindent
10546 @command{gnatchop} recognizes the following switches:
10547
10548 @table @option
10549 @c !sort!
10550
10551 @item --version
10552 @cindex @option{--version} @command{gnatchop}
10553 Display Copyright and version, then exit disregarding all other options.
10554
10555 @item --help
10556 @cindex @option{--help} @command{gnatchop}
10557 If @option{--version} was not used, display usage, then exit disregarding
10558 all other options.
10559
10560 @item ^-c^/COMPILATION^
10561 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
10562 Causes @code{gnatchop} to operate in compilation mode, in which
10563 configuration pragmas are handled according to strict RM rules. See
10564 previous section for a full description of this mode.
10565
10566 @ifclear vms
10567 @item -gnatxxx
10568 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
10569 used to parse the given file. Not all @code{xxx} options make sense,
10570 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
10571 process a source file that uses Latin-2 coding for identifiers.
10572 @end ifclear
10573
10574 @item ^-h^/HELP^
10575 Causes @code{gnatchop} to generate a brief help summary to the standard
10576 output file showing usage information.
10577
10578 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
10579 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
10580 Limit generated file names to the specified number @code{mm}
10581 of characters.
10582 This is useful if the
10583 resulting set of files is required to be interoperable with systems
10584 which limit the length of file names.
10585 @ifset vms
10586 If no value is given, or
10587 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
10588 a default of 39, suitable for OpenVMS Alpha
10589 Systems, is assumed
10590 @end ifset
10591 @ifclear vms
10592 No space is allowed between the @option{-k} and the numeric value. The numeric
10593 value may be omitted in which case a default of @option{-k8},
10594 suitable for use
10595 with DOS-like file systems, is used. If no @option{-k} switch
10596 is present then
10597 there is no limit on the length of file names.
10598 @end ifclear
10599
10600 @item ^-p^/PRESERVE^
10601 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
10602 Causes the file ^modification^creation^ time stamp of the input file to be
10603 preserved and used for the time stamp of the output file(s). This may be
10604 useful for preserving coherency of time stamps in an environment where
10605 @code{gnatchop} is used as part of a standard build process.
10606
10607 @item ^-q^/QUIET^
10608 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
10609 Causes output of informational messages indicating the set of generated
10610 files to be suppressed. Warnings and error messages are unaffected.
10611
10612 @item ^-r^/REFERENCE^
10613 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
10614 @findex Source_Reference
10615 Generate @code{Source_Reference} pragmas. Use this switch if the output
10616 files are regarded as temporary and development is to be done in terms
10617 of the original unchopped file. This switch causes
10618 @code{Source_Reference} pragmas to be inserted into each of the
10619 generated files to refers back to the original file name and line number.
10620 The result is that all error messages refer back to the original
10621 unchopped file.
10622 In addition, the debugging information placed into the object file (when
10623 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
10624 specified)
10625 also refers back to this original file so that tools like profilers and
10626 debuggers will give information in terms of the original unchopped file.
10627
10628 If the original file to be chopped itself contains
10629 a @code{Source_Reference}
10630 pragma referencing a third file, then gnatchop respects
10631 this pragma, and the generated @code{Source_Reference} pragmas
10632 in the chopped file refer to the original file, with appropriate
10633 line numbers. This is particularly useful when @code{gnatchop}
10634 is used in conjunction with @code{gnatprep} to compile files that
10635 contain preprocessing statements and multiple units.
10636
10637 @item ^-v^/VERBOSE^
10638 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
10639 Causes @code{gnatchop} to operate in verbose mode. The version
10640 number and copyright notice are output, as well as exact copies of
10641 the gnat1 commands spawned to obtain the chop control information.
10642
10643 @item ^-w^/OVERWRITE^
10644 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
10645 Overwrite existing file names. Normally @code{gnatchop} regards it as a
10646 fatal error if there is already a file with the same name as a
10647 file it would otherwise output, in other words if the files to be
10648 chopped contain duplicated units. This switch bypasses this
10649 check, and causes all but the last instance of such duplicated
10650 units to be skipped.
10651
10652 @ifclear vms
10653 @item --GCC=xxxx
10654 @cindex @option{--GCC=} (@code{gnatchop})
10655 Specify the path of the GNAT parser to be used. When this switch is used,
10656 no attempt is made to add the prefix to the GNAT parser executable.
10657 @end ifclear
10658 @end table
10659
10660 @node Examples of gnatchop Usage
10661 @section Examples of @code{gnatchop} Usage
10662
10663 @table @code
10664 @ifset vms
10665 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
10666 @end ifset
10667 @ifclear vms
10668 @item gnatchop -w hello_s.ada prerelease/files
10669 @end ifclear
10670
10671 Chops the source file @file{hello_s.ada}. The output files will be
10672 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
10673 overwriting any
10674 files with matching names in that directory (no files in the current
10675 directory are modified).
10676
10677 @item gnatchop ^archive^ARCHIVE.^
10678 Chops the source file @file{^archive^ARCHIVE.^}
10679 into the current directory. One
10680 useful application of @code{gnatchop} is in sending sets of sources
10681 around, for example in email messages. The required sources are simply
10682 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
10683 command), and then
10684 @command{gnatchop} is used at the other end to reconstitute the original
10685 file names.
10686
10687 @item gnatchop file1 file2 file3 direc
10688 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
10689 the resulting files in the directory @file{direc}. Note that if any units
10690 occur more than once anywhere within this set of files, an error message
10691 is generated, and no files are written. To override this check, use the
10692 @option{^-w^/OVERWRITE^} switch,
10693 in which case the last occurrence in the last file will
10694 be the one that is output, and earlier duplicate occurrences for a given
10695 unit will be skipped.
10696 @end table
10697
10698 @node Configuration Pragmas
10699 @chapter Configuration Pragmas
10700 @cindex Configuration pragmas
10701 @cindex Pragmas, configuration
10702
10703 @noindent
10704 Configuration pragmas include those pragmas described as
10705 such in the Ada Reference Manual, as well as
10706 implementation-dependent pragmas that are configuration pragmas. See the
10707 individual descriptions of pragmas in the @cite{GNAT Reference Manual} for
10708 details on these additional GNAT-specific configuration pragmas. Most
10709 notably, the pragma @code{Source_File_Name}, which allows
10710 specifying non-default names for source files, is a configuration
10711 pragma. The following is a complete list of configuration pragmas
10712 recognized by GNAT:
10713
10714 @smallexample
10715    Ada_83
10716    Ada_95
10717    Ada_05
10718    C_Pass_By_Copy
10719    Component_Alignment
10720    Detect_Blocking
10721    Discard_Names
10722    Elaboration_Checks
10723    Eliminate
10724    Extend_System
10725    External_Name_Casing
10726    Float_Representation
10727    Initialize_Scalars
10728    Interrupt_State
10729    License
10730    Locking_Policy
10731    Long_Float
10732    Normalize_Scalars
10733    Persistent_BSS
10734    Polling
10735    Profile
10736    Profile_Warnings
10737    Propagate_Exceptions
10738    Queuing_Policy
10739    Ravenscar
10740    Restricted_Run_Time
10741    Restrictions
10742    Restrictions_Warnings
10743    Reviewable
10744    Source_File_Name
10745    Style_Checks
10746    Suppress
10747    Task_Dispatching_Policy
10748    Universal_Data
10749    Unsuppress
10750    Use_VADS_Size
10751    Warnings
10752    Validity_Checks
10753 @end smallexample
10754
10755 @menu
10756 * Handling of Configuration Pragmas::
10757 * The Configuration Pragmas Files::
10758 @end menu
10759
10760 @node Handling of Configuration Pragmas
10761 @section Handling of Configuration Pragmas
10762
10763 Configuration pragmas may either appear at the start of a compilation
10764 unit, in which case they apply only to that unit, or they may apply to
10765 all compilations performed in a given compilation environment.
10766
10767 GNAT also provides the @code{gnatchop} utility to provide an automatic
10768 way to handle configuration pragmas following the semantics for
10769 compilations (that is, files with multiple units), described in the RM.
10770 See @ref{Operating gnatchop in Compilation Mode} for details.
10771 However, for most purposes, it will be more convenient to edit the
10772 @file{gnat.adc} file that contains configuration pragmas directly,
10773 as described in the following section.
10774
10775 @node The Configuration Pragmas Files
10776 @section The Configuration Pragmas Files
10777 @cindex @file{gnat.adc}
10778
10779 @noindent
10780 In GNAT a compilation environment is defined by the current
10781 directory at the time that a compile command is given. This current
10782 directory is searched for a file whose name is @file{gnat.adc}. If
10783 this file is present, it is expected to contain one or more
10784 configuration pragmas that will be applied to the current compilation.
10785 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10786 considered.
10787
10788 Configuration pragmas may be entered into the @file{gnat.adc} file
10789 either by running @code{gnatchop} on a source file that consists only of
10790 configuration pragmas, or more conveniently  by
10791 direct editing of the @file{gnat.adc} file, which is a standard format
10792 source file.
10793
10794 In addition to @file{gnat.adc}, additional files containing configuration
10795 pragmas may be applied to the current compilation using the switch
10796 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10797 contains only configuration pragmas. These configuration pragmas are
10798 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10799 is present and switch @option{-gnatA} is not used).
10800
10801 It is allowed to specify several switches @option{-gnatec}, all of which
10802 will be taken into account.
10803
10804 If you are using project file, a separate mechanism is provided using
10805 project attributes, see @ref{Specifying Configuration Pragmas} for more
10806 details.
10807
10808 @ifset vms
10809 Of special interest to GNAT OpenVMS Alpha is the following
10810 configuration pragma:
10811
10812 @smallexample @c ada
10813 @cartouche
10814 pragma Extend_System (Aux_DEC);
10815 @end cartouche
10816 @end smallexample
10817
10818 @noindent
10819 In the presence of this pragma, GNAT adds to the definition of the
10820 predefined package SYSTEM all the additional types and subprograms that are
10821 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
10822 @end ifset
10823
10824 @node Handling Arbitrary File Naming Conventions Using gnatname
10825 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10826 @cindex Arbitrary File Naming Conventions
10827
10828 @menu
10829 * Arbitrary File Naming Conventions::
10830 * Running gnatname::
10831 * Switches for gnatname::
10832 * Examples of gnatname Usage::
10833 @end menu
10834
10835 @node Arbitrary File Naming Conventions
10836 @section Arbitrary File Naming Conventions
10837
10838 @noindent
10839 The GNAT compiler must be able to know the source file name of a compilation
10840 unit.  When using the standard GNAT default file naming conventions
10841 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10842 does not need additional information.
10843
10844 @noindent
10845 When the source file names do not follow the standard GNAT default file naming
10846 conventions, the GNAT compiler must be given additional information through
10847 a configuration pragmas file (@pxref{Configuration Pragmas})
10848 or a project file.
10849 When the non-standard file naming conventions are well-defined,
10850 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10851 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
10852 if the file naming conventions are irregular or arbitrary, a number
10853 of pragma @code{Source_File_Name} for individual compilation units
10854 must be defined.
10855 To help maintain the correspondence between compilation unit names and
10856 source file names within the compiler,
10857 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10858 set of files.
10859
10860 @node Running gnatname
10861 @section Running @code{gnatname}
10862
10863 @noindent
10864 The usual form of the @code{gnatname} command is
10865
10866 @smallexample
10867 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10868 @end smallexample
10869
10870 @noindent
10871 All of the arguments are optional. If invoked without any argument,
10872 @code{gnatname} will display its usage.
10873
10874 @noindent
10875 When used with at least one naming pattern, @code{gnatname} will attempt to
10876 find all the compilation units in files that follow at least one of the
10877 naming patterns. To find these compilation units,
10878 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10879 regular files.
10880
10881 @noindent
10882 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10883 Each Naming Pattern is enclosed between double quotes.
10884 A Naming Pattern is a regular expression similar to the wildcard patterns
10885 used in file names by the Unix shells or the DOS prompt.
10886
10887 @noindent
10888 Examples of Naming Patterns are
10889
10890 @smallexample
10891    "*.[12].ada"
10892    "*.ad[sb]*"
10893    "body_*"    "spec_*"
10894 @end smallexample
10895
10896 @noindent
10897 For a more complete description of the syntax of Naming Patterns,
10898 see the second kind of regular expressions described in @file{g-regexp.ads}
10899 (the ``Glob'' regular expressions).
10900
10901 @noindent
10902 When invoked with no switches, @code{gnatname} will create a configuration
10903 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10904 @code{Source_File_Name} for each file that contains a valid Ada unit.
10905
10906 @node Switches for gnatname
10907 @section Switches for @code{gnatname}
10908
10909 @noindent
10910 Switches for @code{gnatname} must precede any specified Naming Pattern.
10911
10912 @noindent
10913 You may specify any of the following switches to @code{gnatname}:
10914
10915 @table @option
10916 @c !sort!
10917
10918 @item --version
10919 @cindex @option{--version} @command{gnatname}
10920 Display Copyright and version, then exit disregarding all other options.
10921
10922 @item --help
10923 @cindex @option{--help} @command{gnatname}
10924 If @option{--version} was not used, display usage, then exit disregarding
10925 all other options.
10926
10927 @item ^-c^/CONFIG_FILE=^@file{file}
10928 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10929 Create a configuration pragmas file @file{file} (instead of the default
10930 @file{gnat.adc}).
10931 @ifclear vms
10932 There may be zero, one or more space between @option{-c} and
10933 @file{file}.
10934 @end ifclear
10935 @file{file} may include directory information. @file{file} must be
10936 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10937 When a switch @option{^-c^/CONFIG_FILE^} is
10938 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10939
10940 @item ^-d^/SOURCE_DIRS=^@file{dir}
10941 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10942 Look for source files in directory @file{dir}. There may be zero, one or more
10943 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10944 When a switch @option{^-d^/SOURCE_DIRS^}
10945 is specified, the current working directory will not be searched for source
10946 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10947 or @option{^-D^/DIR_FILES^} switch.
10948 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10949 If @file{dir} is a relative path, it is relative to the directory of
10950 the configuration pragmas file specified with switch
10951 @option{^-c^/CONFIG_FILE^},
10952 or to the directory of the project file specified with switch
10953 @option{^-P^/PROJECT_FILE^} or,
10954 if neither switch @option{^-c^/CONFIG_FILE^}
10955 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10956 current working directory. The directory
10957 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10958
10959 @item ^-D^/DIRS_FILE=^@file{file}
10960 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10961 Look for source files in all directories listed in text file @file{file}.
10962 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10963 and @file{file}.
10964 @file{file} must be an existing, readable text file.
10965 Each nonempty line in @file{file} must be a directory.
10966 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10967 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
10968 @file{file}.
10969
10970 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10971 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10972 Foreign patterns. Using this switch, it is possible to add sources of languages
10973 other than Ada to the list of sources of a project file.
10974 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10975 For example,
10976 @smallexample
10977 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10978 @end smallexample
10979 @noindent
10980 will look for Ada units in all files with the @file{.ada} extension,
10981 and will add to the list of file for project @file{prj.gpr} the C files
10982 with extension @file{.^c^C^}.
10983
10984 @item ^-h^/HELP^
10985 @cindex @option{^-h^/HELP^} (@code{gnatname})
10986 Output usage (help) information. The output is written to @file{stdout}.
10987
10988 @item ^-P^/PROJECT_FILE=^@file{proj}
10989 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10990 Create or update project file @file{proj}. There may be zero, one or more space
10991 between @option{-P} and @file{proj}. @file{proj} may include directory
10992 information. @file{proj} must be writable.
10993 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10994 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10995 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10996
10997 @item ^-v^/VERBOSE^
10998 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10999 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11000 This includes name of the file written, the name of the directories to search
11001 and, for each file in those directories whose name matches at least one of
11002 the Naming Patterns, an indication of whether the file contains a unit,
11003 and if so the name of the unit.
11004
11005 @item ^-v -v^/VERBOSE /VERBOSE^
11006 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11007 Very Verbose mode. In addition to the output produced in verbose mode,
11008 for each file in the searched directories whose name matches none of
11009 the Naming Patterns, an indication is given that there is no match.
11010
11011 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11012 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11013 Excluded patterns. Using this switch, it is possible to exclude some files
11014 that would match the name patterns. For example,
11015 @smallexample
11016 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11017 @end smallexample
11018 @noindent
11019 will look for Ada units in all files with the @file{.ada} extension,
11020 except those whose names end with @file{_nt.ada}.
11021
11022 @end table
11023
11024 @node Examples of gnatname Usage
11025 @section Examples of @code{gnatname} Usage
11026
11027 @ifset vms
11028 @smallexample
11029 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11030 @end smallexample
11031 @end ifset
11032
11033 @ifclear vms
11034 @smallexample
11035 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11036 @end smallexample
11037 @end ifclear
11038
11039 @noindent
11040 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11041 and be writable. In addition, the directory
11042 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11043 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11044
11045 @ifclear vms
11046 Note the optional spaces after @option{-c} and @option{-d}.
11047 @end ifclear
11048
11049 @smallexample
11050 @ifclear vms
11051 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11052   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11053 @end ifclear
11054 @ifset vms
11055 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11056   /EXCLUDED_PATTERN=*_nt_body.ada
11057   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11058   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11059 @end ifset
11060 @end smallexample
11061
11062 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11063 even in conjunction with one or several switches
11064 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11065 are used in this example.
11066
11067 @c *****************************************
11068 @c * G N A T  P r o j e c t  M a n a g e r *
11069 @c *****************************************
11070 @node GNAT Project Manager
11071 @chapter GNAT Project Manager
11072
11073 @menu
11074 * Introduction::
11075 * Examples of Project Files::
11076 * Project File Syntax::
11077 * Objects and Sources in Project Files::
11078 * Importing Projects::
11079 * Project Extension::
11080 * Project Hierarchy Extension::
11081 * External References in Project Files::
11082 * Packages in Project Files::
11083 * Variables from Imported Projects::
11084 * Naming Schemes::
11085 * Library Projects::
11086 * Stand-alone Library Projects::
11087 * Switches Related to Project Files::
11088 * Tools Supporting Project Files::
11089 * An Extended Example::
11090 * Project File Complete Syntax::
11091 @end menu
11092
11093 @c ****************
11094 @c * Introduction *
11095 @c ****************
11096
11097 @node Introduction
11098 @section Introduction
11099
11100 @noindent
11101 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11102 you to manage complex builds involving a number of source files, directories,
11103 and compilation options for different system configurations. In particular,
11104 project files allow you to specify:
11105 @itemize @bullet
11106 @item
11107 The directory or set of directories containing the source files, and/or the
11108 names of the specific source files themselves
11109 @item
11110 The directory in which the compiler's output
11111 (@file{ALI} files, object files, tree files) is to be placed
11112 @item
11113 The directory in which the executable programs is to be placed
11114 @item
11115 ^Switch^Switch^ settings for any of the project-enabled tools
11116 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11117 @code{gnatfind}); you can apply these settings either globally or to individual
11118 compilation units.
11119 @item
11120 The source files containing the main subprogram(s) to be built
11121 @item
11122 The source programming language(s) (currently Ada and/or C)
11123 @item
11124 Source file naming conventions; you can specify these either globally or for
11125 individual compilation units
11126 @end itemize
11127
11128 @menu
11129 * Project Files::
11130 @end menu
11131
11132 @node Project Files
11133 @subsection Project Files
11134
11135 @noindent
11136 Project files are written in a syntax close to that of Ada, using  familiar
11137 notions such as packages, context clauses, declarations, default values,
11138 assignments, and inheritance. Finally, project files can be built
11139 hierarchically from other project files, simplifying complex system
11140 integration and project reuse.
11141
11142 A @dfn{project} is a specific set of values for various compilation properties.
11143 The settings for a given project are described by means of
11144 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11145 Property values in project files are either strings or lists of strings.
11146 Properties that are not explicitly set receive default values.  A project
11147 file may interrogate the values of @dfn{external variables} (user-defined
11148 command-line switches or environment variables), and it may specify property
11149 settings conditionally, based on the value of such variables.
11150
11151 In simple cases, a project's source files depend only on other source files
11152 in the same project, or on the predefined libraries.  (@emph{Dependence} is
11153 used in
11154 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
11155 the Project Manager also allows more sophisticated arrangements,
11156 where the source files in one project depend on source files in other
11157 projects:
11158 @itemize @bullet
11159 @item
11160 One project can @emph{import} other projects containing needed source files.
11161 @item
11162 You can organize GNAT projects in a hierarchy: a @emph{child} project
11163 can extend a @emph{parent} project, inheriting the parent's source files and
11164 optionally overriding any of them with alternative versions
11165 @end itemize
11166
11167 @noindent
11168 More generally, the Project Manager lets you structure large development
11169 efforts into hierarchical subsystems, where build decisions are delegated
11170 to the subsystem level, and thus different compilation environments
11171 (^switch^switch^ settings) used for different subsystems.
11172
11173 The Project Manager is invoked through the
11174 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11175 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11176 @ifclear vms
11177 There may be zero, one or more spaces between @option{-P} and
11178 @option{@emph{projectfile}}.
11179 @end ifclear
11180 If you want to define (on the command line) an external variable that is
11181 queried by the project file, you must use the
11182 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11183 The Project Manager parses and interprets the project file, and drives the
11184 invoked tool based on the project settings.
11185
11186 The Project Manager supports a wide range of development strategies,
11187 for systems of all sizes.  Here are some typical practices that are
11188 easily handled:
11189 @itemize @bullet
11190 @item
11191 Using a common set of source files, but generating object files in different
11192 directories via different ^switch^switch^ settings
11193 @item
11194 Using a mostly-shared set of source files, but with different versions of
11195 some unit or units
11196 @end itemize
11197
11198 @noindent
11199 The destination of an executable can be controlled inside a project file
11200 using the @option{^-o^-o^}
11201 ^switch^switch^.
11202 In the absence of such a ^switch^switch^ either inside
11203 the project file or on the command line, any executable files generated by
11204 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11205 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11206 in the object directory of the project.
11207
11208 You can use project files to achieve some of the effects of a source
11209 versioning system (for example, defining separate projects for
11210 the different sets of sources that comprise different releases) but the
11211 Project Manager is independent of any source configuration management tools
11212 that might be used by the developers.
11213
11214 The next section introduces the main features of GNAT's project facility
11215 through a sequence of examples; subsequent sections will present the syntax
11216 and semantics in more detail. A more formal description of the project
11217 facility appears in the GNAT Reference Manual.
11218
11219 @c *****************************
11220 @c * Examples of Project Files *
11221 @c *****************************
11222
11223 @node Examples of Project Files
11224 @section Examples of Project Files
11225 @noindent
11226 This section illustrates some of the typical uses of project files and
11227 explains their basic structure and behavior.
11228
11229 @menu
11230 * Common Sources with Different ^Switches^Switches^ and Directories::
11231 * Using External Variables::
11232 * Importing Other Projects::
11233 * Extending a Project::
11234 @end menu
11235
11236 @node Common Sources with Different ^Switches^Switches^ and Directories
11237 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11238
11239 @menu
11240 * Source Files::
11241 * Specifying the Object Directory::
11242 * Specifying the Exec Directory::
11243 * Project File Packages::
11244 * Specifying ^Switch^Switch^ Settings::
11245 * Main Subprograms::
11246 * Executable File Names::
11247 * Source File Naming Conventions::
11248 * Source Language(s)::
11249 @end menu
11250
11251 @noindent
11252 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11253 @file{proc.adb} are in the @file{/common} directory.  The file
11254 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11255 package @code{Pack}.  We want to compile these source files under two sets
11256 of ^switches^switches^:
11257 @itemize @bullet
11258 @item
11259 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11260 and the @option{^-gnata^-gnata^},
11261 @option{^-gnato^-gnato^},
11262 and @option{^-gnatE^-gnatE^} switches to the
11263 compiler; the compiler's output is to appear in @file{/common/debug}
11264 @item
11265 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11266 to the compiler; the compiler's output is to appear in @file{/common/release}
11267 @end itemize
11268
11269 @noindent
11270 The GNAT project files shown below, respectively @file{debug.gpr} and
11271 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11272
11273 Schematically:
11274 @smallexample
11275 @group
11276 ^/common^[COMMON]^
11277   debug.gpr
11278   release.gpr
11279   pack.ads
11280   pack.adb
11281   proc.adb
11282 @end group
11283 @group
11284 ^/common/debug^[COMMON.DEBUG]^
11285   proc.ali, proc.o
11286   pack.ali, pack.o
11287 @end group
11288 @group
11289 ^/common/release^[COMMON.RELEASE]^
11290   proc.ali, proc.o
11291   pack.ali, pack.o
11292 @end group
11293 @end smallexample
11294 Here are the corresponding project files:
11295
11296 @smallexample @c projectfile
11297 @group
11298 project Debug is
11299   for Object_Dir use "debug";
11300   for Main use ("proc");
11301
11302   package Builder is
11303     for ^Default_Switches^Default_Switches^ ("Ada")
11304         use ("^-g^-g^");
11305     for Executable ("proc.adb") use "proc1";
11306   end Builder;
11307 @end group
11308
11309 @group
11310   package Compiler is
11311     for ^Default_Switches^Default_Switches^ ("Ada")
11312        use ("-fstack-check",
11313             "^-gnata^-gnata^",
11314             "^-gnato^-gnato^",
11315             "^-gnatE^-gnatE^");
11316   end Compiler;
11317 end Debug;
11318 @end group
11319 @end smallexample
11320
11321 @smallexample @c projectfile
11322 @group
11323 project Release is
11324   for Object_Dir use "release";
11325   for Exec_Dir use ".";
11326   for Main use ("proc");
11327
11328   package Compiler is
11329     for ^Default_Switches^Default_Switches^ ("Ada")
11330         use ("^-O2^-O2^");
11331   end Compiler;
11332 end Release;
11333 @end group
11334 @end smallexample
11335
11336 @noindent
11337 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11338 insensitive), and analogously the project defined by @file{release.gpr} is
11339 @code{"Release"}.  For consistency the file should have the same name as the
11340 project, and the project file's extension should be @code{"gpr"}. These
11341 conventions are not required, but a warning is issued if they are not followed.
11342
11343 If the current directory is @file{^/temp^[TEMP]^}, then the command
11344 @smallexample
11345 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11346 @end smallexample
11347
11348 @noindent
11349 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11350 as well as the @code{^proc1^PROC1.EXE^} executable,
11351 using the ^switch^switch^ settings defined in the project file.
11352
11353 Likewise, the command
11354 @smallexample
11355 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11356 @end smallexample
11357
11358 @noindent
11359 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11360 and the @code{^proc^PROC.EXE^}
11361 executable in @file{^/common^[COMMON]^},
11362 using the ^switch^switch^ settings from the project file.
11363
11364 @node Source Files
11365 @unnumberedsubsubsec Source Files
11366
11367 @noindent
11368 If a project file does not explicitly specify a set of source directories or
11369 a set of source files, then by default the project's source files are the
11370 Ada source files in the project file directory.  Thus @file{pack.ads},
11371 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11372
11373 @node Specifying the Object Directory
11374 @unnumberedsubsubsec Specifying the Object Directory
11375
11376 @noindent
11377 Several project properties are modeled by Ada-style @emph{attributes};
11378 a property is defined by supplying the equivalent of an Ada attribute
11379 definition clause in the project file.
11380 A project's object directory is another such a property; the corresponding
11381 attribute is @code{Object_Dir}, and its value is also a string expression,
11382 specified either as absolute or relative. In the later case,
11383 it is relative to the project file directory. Thus the compiler's
11384 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
11385 (for the @code{Debug} project)
11386 and to @file{^/common/release^[COMMON.RELEASE]^}
11387 (for the @code{Release} project).
11388 If @code{Object_Dir} is not specified, then the default is the project file
11389 directory itself.
11390
11391 @node Specifying the Exec Directory
11392 @unnumberedsubsubsec Specifying the Exec Directory
11393
11394 @noindent
11395 A project's exec directory is another property; the corresponding
11396 attribute is @code{Exec_Dir}, and its value is also a string expression,
11397 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
11398 then the default is the object directory (which may also be the project file
11399 directory if attribute @code{Object_Dir} is not specified). Thus the executable
11400 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
11401 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
11402 and in @file{^/common^[COMMON]^} for the @code{Release} project.
11403
11404 @node Project File Packages
11405 @unnumberedsubsubsec Project File Packages
11406
11407 @noindent
11408 A GNAT tool that is integrated with the Project Manager is modeled by a
11409 corresponding package in the project file. In the example above,
11410 The @code{Debug} project defines the packages @code{Builder}
11411 (for @command{gnatmake}) and @code{Compiler};
11412 the @code{Release} project defines only the @code{Compiler} package.
11413
11414 The Ada-like package syntax is not to be taken literally.  Although packages in
11415 project files bear a surface resemblance to packages in Ada source code, the
11416 notation is simply a way to convey a grouping of properties for a named
11417 entity.  Indeed, the package names permitted in project files are restricted
11418 to a predefined set, corresponding to the project-aware tools, and the contents
11419 of packages are limited to a small set of constructs.
11420 The packages in the example above contain attribute definitions.
11421
11422 @node Specifying ^Switch^Switch^ Settings
11423 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
11424
11425 @noindent
11426 ^Switch^Switch^ settings for a project-aware tool can be specified through
11427 attributes in the package that corresponds to the tool.
11428 The example above illustrates one of the relevant attributes,
11429 @code{^Default_Switches^Default_Switches^}, which is defined in packages
11430 in both project files.
11431 Unlike simple attributes like @code{Source_Dirs},
11432 @code{^Default_Switches^Default_Switches^} is
11433 known as an @emph{associative array}.  When you define this attribute, you must
11434 supply an ``index'' (a literal string), and the effect of the attribute
11435 definition is to set the value of the array at the specified index.
11436 For the @code{^Default_Switches^Default_Switches^} attribute,
11437 the index is a programming language (in our case, Ada),
11438 and the value specified (after @code{use}) must be a list
11439 of string expressions.
11440
11441 The attributes permitted in project files are restricted to a predefined set.
11442 Some may appear at project level, others in packages.
11443 For any attribute that is an associative array, the index must always be a
11444 literal string, but the restrictions on this string (e.g., a file name or a
11445 language name) depend on the individual attribute.
11446 Also depending on the attribute, its specified value will need to be either a
11447 string or a string list.
11448
11449 In the @code{Debug} project, we set the switches for two tools,
11450 @command{gnatmake} and the compiler, and thus we include the two corresponding
11451 packages; each package defines the @code{^Default_Switches^Default_Switches^}
11452 attribute with index @code{"Ada"}.
11453 Note that the package corresponding to
11454 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
11455 similar, but only includes the @code{Compiler} package.
11456
11457 In project @code{Debug} above, the ^switches^switches^ starting with
11458 @option{-gnat} that are specified in package @code{Compiler}
11459 could have been placed in package @code{Builder}, since @command{gnatmake}
11460 transmits all such ^switches^switches^ to the compiler.
11461
11462 @node Main Subprograms
11463 @unnumberedsubsubsec Main Subprograms
11464
11465 @noindent
11466 One of the specifiable properties of a project is a list of files that contain
11467 main subprograms.  This property is captured in the @code{Main} attribute,
11468 whose value is a list of strings.  If a project defines the @code{Main}
11469 attribute, it is not necessary to identify the main subprogram(s) when
11470 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
11471
11472 @node Executable File Names
11473 @unnumberedsubsubsec Executable File Names
11474
11475 @noindent
11476 By default, the executable file name corresponding to a main source is
11477 deduced from the main source file name. Through the attributes
11478 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
11479 it is possible to change this default.
11480 In project @code{Debug} above, the executable file name
11481 for main source @file{^proc.adb^PROC.ADB^} is
11482 @file{^proc1^PROC1.EXE^}.
11483 Attribute @code{Executable_Suffix}, when specified, may change the suffix
11484 of the executable files, when no attribute @code{Executable} applies:
11485 its value replace the platform-specific executable suffix.
11486 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
11487 specify a non-default executable file name when several mains are built at once
11488 in a single @command{gnatmake} command.
11489
11490 @node Source File Naming Conventions
11491 @unnumberedsubsubsec Source File Naming Conventions
11492
11493 @noindent
11494 Since the project files above do not specify any source file naming
11495 conventions, the GNAT defaults are used.  The mechanism for defining source
11496 file naming conventions -- a package named @code{Naming} --
11497 is described below (@pxref{Naming Schemes}).
11498
11499 @node Source Language(s)
11500 @unnumberedsubsubsec Source Language(s)
11501
11502 @noindent
11503 Since the project files do not specify a @code{Languages} attribute, by
11504 default the GNAT tools assume that the language of the project file is Ada.
11505 More generally, a project can comprise source files
11506 in Ada, C, and/or other languages.
11507
11508 @node Using External Variables
11509 @subsection Using External Variables
11510
11511 @noindent
11512 Instead of supplying different project files for debug and release, we can
11513 define a single project file that queries an external variable (set either
11514 on the command line or via an ^environment variable^logical name^) in order to
11515 conditionally define the appropriate settings.  Again, assume that the
11516 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
11517 located in directory @file{^/common^[COMMON]^}.  The following project file,
11518 @file{build.gpr}, queries the external variable named @code{STYLE} and
11519 defines an object directory and ^switch^switch^ settings based on whether
11520 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
11521 the default is @code{"deb"}.
11522
11523 @smallexample @c projectfile
11524 @group
11525 project Build is
11526   for Main use ("proc");
11527
11528   type Style_Type is ("deb", "rel");
11529   Style : Style_Type := external ("STYLE", "deb");
11530
11531   case Style is
11532     when "deb" =>
11533       for Object_Dir use "debug";
11534
11535     when "rel" =>
11536       for Object_Dir use "release";
11537       for Exec_Dir use ".";
11538   end case;
11539 @end group
11540
11541 @group
11542   package Builder is
11543
11544     case Style is
11545       when "deb" =>
11546         for ^Default_Switches^Default_Switches^ ("Ada")
11547             use ("^-g^-g^");
11548         for Executable ("proc") use "proc1";
11549       when others =>
11550         null;
11551     end case;
11552
11553   end Builder;
11554 @end group
11555
11556 @group
11557   package Compiler is
11558
11559     case Style is
11560       when "deb" =>
11561         for ^Default_Switches^Default_Switches^ ("Ada")
11562             use ("^-gnata^-gnata^",
11563                  "^-gnato^-gnato^",
11564                  "^-gnatE^-gnatE^");
11565
11566       when "rel" =>
11567         for ^Default_Switches^Default_Switches^ ("Ada")
11568             use ("^-O2^-O2^");
11569     end case;
11570
11571   end Compiler;
11572
11573 end Build;
11574 @end group
11575 @end smallexample
11576
11577 @noindent
11578 @code{Style_Type} is an example of a @emph{string type}, which is the project
11579 file analog of an Ada enumeration type but whose components are string literals
11580 rather than identifiers.  @code{Style} is declared as a variable of this type.
11581
11582 The form @code{external("STYLE", "deb")} is known as an
11583 @emph{external reference}; its first argument is the name of an
11584 @emph{external variable}, and the second argument is a default value to be
11585 used if the external variable doesn't exist.  You can define an external
11586 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
11587 or you can use ^an environment variable^a logical name^
11588 as an external variable.
11589
11590 Each @code{case} construct is expanded by the Project Manager based on the
11591 value of @code{Style}. Thus the command
11592 @ifclear vms
11593 @smallexample
11594 gnatmake -P/common/build.gpr -XSTYLE=deb
11595 @end smallexample
11596 @end ifclear
11597
11598 @ifset vms
11599 @smallexample
11600 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
11601 @end smallexample
11602 @end ifset
11603
11604 @noindent
11605 is equivalent to the @command{gnatmake} invocation using the project file
11606 @file{debug.gpr} in the earlier example.  So is the command
11607 @smallexample
11608 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
11609 @end smallexample
11610
11611 @noindent
11612 since @code{"deb"} is the default for @code{STYLE}.
11613
11614 Analogously,
11615
11616 @ifclear vms
11617 @smallexample
11618 gnatmake -P/common/build.gpr -XSTYLE=rel
11619 @end smallexample
11620 @end ifclear
11621
11622 @ifset vms
11623 @smallexample
11624 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
11625 @end smallexample
11626 @end ifset
11627
11628 @noindent
11629 is equivalent to the @command{gnatmake} invocation using the project file
11630 @file{release.gpr} in the earlier example.
11631
11632 @node Importing Other Projects
11633 @subsection Importing Other Projects
11634 @cindex @code{ADA_PROJECT_PATH}
11635
11636 @noindent
11637 A compilation unit in a source file in one project may depend on compilation
11638 units in source files in other projects.  To compile this unit under
11639 control of a project file, the
11640 dependent project must @emph{import} the projects containing the needed source
11641 files.
11642 This effect is obtained using syntax similar to an Ada @code{with} clause,
11643 but where @code{with}ed entities are strings that denote project files.
11644
11645 As an example, suppose that the two projects @code{GUI_Proj} and
11646 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
11647 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
11648 and @file{^/comm^[COMM]^}, respectively.
11649 Suppose that the source files for @code{GUI_Proj} are
11650 @file{gui.ads} and @file{gui.adb}, and that the source files for
11651 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
11652 files is located in its respective project file directory.  Schematically:
11653
11654 @smallexample
11655 @group
11656 ^/gui^[GUI]^
11657   gui_proj.gpr
11658   gui.ads
11659   gui.adb
11660 @end group
11661
11662 @group
11663 ^/comm^[COMM]^
11664   comm_proj.gpr
11665   comm.ads
11666   comm.adb
11667 @end group
11668 @end smallexample
11669
11670 @noindent
11671 We want to develop an application in directory @file{^/app^[APP]^} that
11672 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
11673 the corresponding project files (e.g.@: the ^switch^switch^ settings
11674 and object directory).
11675 Skeletal code for a main procedure might be something like the following:
11676
11677 @smallexample @c ada
11678 @group
11679 with GUI, Comm;
11680 procedure App_Main is
11681    @dots{}
11682 begin
11683    @dots{}
11684 end App_Main;
11685 @end group
11686 @end smallexample
11687
11688 @noindent
11689 Here is a project file, @file{app_proj.gpr}, that achieves the desired
11690 effect:
11691
11692 @smallexample @c projectfile
11693 @group
11694 with "/gui/gui_proj", "/comm/comm_proj";
11695 project App_Proj is
11696    for Main use ("app_main");
11697 end App_Proj;
11698 @end group
11699 @end smallexample
11700
11701 @noindent
11702 Building an executable is achieved through the command:
11703 @smallexample
11704 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
11705 @end smallexample
11706 @noindent
11707 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
11708 in the directory where @file{app_proj.gpr} resides.
11709
11710 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
11711 (as illustrated above) the @code{with} clause can omit the extension.
11712
11713 Our example specified an absolute path for each imported project file.
11714 Alternatively, the directory name of an imported object can be omitted
11715 if either
11716 @itemize @bullet
11717 @item
11718 The imported project file is in the same directory as the importing project
11719 file, or
11720 @item
11721 You have defined ^an environment variable^a logical name^
11722 that includes the directory containing
11723 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
11724 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
11725 directory names separated by colons (semicolons on Windows).
11726 @end itemize
11727
11728 @noindent
11729 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
11730 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
11731 as follows:
11732
11733 @smallexample @c projectfile
11734 @group
11735 with "gui_proj", "comm_proj";
11736 project App_Proj is
11737    for Main use ("app_main");
11738 end App_Proj;
11739 @end group
11740 @end smallexample
11741
11742 @noindent
11743 Importing other projects can create ambiguities.
11744 For example, the same unit might be present in different imported projects, or
11745 it might be present in both the importing project and in an imported project.
11746 Both of these conditions are errors.  Note that in the current version of
11747 the Project Manager, it is illegal to have an ambiguous unit even if the
11748 unit is never referenced by the importing project.  This restriction may be
11749 relaxed in a future release.
11750
11751 @node Extending a Project
11752 @subsection Extending a Project
11753
11754 @noindent
11755 In large software systems it is common to have multiple
11756 implementations of a common interface; in Ada terms, multiple versions of a
11757 package body for the same specification.  For example, one implementation
11758 might be safe for use in tasking programs, while another might only be used
11759 in sequential applications.  This can be modeled in GNAT using the concept
11760 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
11761 another project (the ``parent'') then by default all source files of the
11762 parent project are inherited by the child, but the child project can
11763 override any of the parent's source files with new versions, and can also
11764 add new files.  This facility is the project analog of a type extension in
11765 Object-Oriented Programming.  Project hierarchies are permitted (a child
11766 project may be the parent of yet another project), and a project that
11767 inherits one project can also import other projects.
11768
11769 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11770 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11771 @file{pack.adb}, and @file{proc.adb}:
11772
11773 @smallexample
11774 @group
11775 ^/seq^[SEQ]^
11776   pack.ads
11777   pack.adb
11778   proc.adb
11779   seq_proj.gpr
11780 @end group
11781 @end smallexample
11782
11783 @noindent
11784 Note that the project file can simply be empty (that is, no attribute or
11785 package is defined):
11786
11787 @smallexample @c projectfile
11788 @group
11789 project Seq_Proj is
11790 end Seq_Proj;
11791 @end group
11792 @end smallexample
11793
11794 @noindent
11795 implying that its source files are all the Ada source files in the project
11796 directory.
11797
11798 Suppose we want to supply an alternate version of @file{pack.adb}, in
11799 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11800 @file{pack.ads} and @file{proc.adb}.  We can define a project
11801 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11802
11803 @smallexample
11804 @group
11805 ^/tasking^[TASKING]^
11806   pack.adb
11807   tasking_proj.gpr
11808 @end group
11809
11810 @group
11811 project Tasking_Proj extends "/seq/seq_proj" is
11812 end Tasking_Proj;
11813 @end group
11814 @end smallexample
11815
11816 @noindent
11817 The version of @file{pack.adb} used in a build depends on which project file
11818 is specified.
11819
11820 Note that we could have obtained the desired behavior using project import
11821 rather than project inheritance; a @code{base} project would contain the
11822 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11823 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11824 would import @code{base} and add a different version of @file{pack.adb}.  The
11825 choice depends on whether other sources in the original project need to be
11826 overridden.  If they do, then project extension is necessary, otherwise,
11827 importing is sufficient.
11828
11829 @noindent
11830 In a project file that extends another project file, it is possible to
11831 indicate that an inherited source is not part of the sources of the extending
11832 project. This is necessary sometimes when a package spec has been overloaded
11833 and no longer requires a body: in this case, it is necessary to indicate that
11834 the inherited body is not part of the sources of the project, otherwise there
11835 will be a compilation error when compiling the spec.
11836
11837 For that purpose, the attribute @code{Excluded_Source_Files} is used.
11838 Its value is a string list: a list of file names.
11839
11840 @smallexample @c @projectfile
11841 project B extends "a" is
11842    for Source_Files use ("pkg.ads");
11843    --  New spec of Pkg does not need a completion
11844    for Excluded_Source_Files use ("pkg.adb");
11845 end B;
11846 @end smallexample
11847
11848 Attribute @code{Excluded_Source_Files} may also be used to check if a source
11849 is still needed: if it is possible to build using @command{gnatmake} when such
11850 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
11851 it is possible to remove the source completely from a system that includes
11852 project P.
11853
11854 @c ***********************
11855 @c * Project File Syntax *
11856 @c ***********************
11857
11858 @node Project File Syntax
11859 @section Project File Syntax
11860
11861 @menu
11862 * Basic Syntax::
11863 * Packages::
11864 * Expressions::
11865 * String Types::
11866 * Variables::
11867 * Attributes::
11868 * Associative Array Attributes::
11869 * case Constructions::
11870 @end menu
11871
11872 @noindent
11873 This section describes the structure of project files.
11874
11875 A project may be an @emph{independent project}, entirely defined by a single
11876 project file. Any Ada source file in an independent project depends only
11877 on the predefined library and other Ada source files in the same project.
11878
11879 @noindent
11880 A project may also @dfn{depend on} other projects, in either or both of
11881 the following ways:
11882 @itemize @bullet
11883 @item It may import any number of projects
11884 @item It may extend at most one other project
11885 @end itemize
11886
11887 @noindent
11888 The dependence relation is a directed acyclic graph (the subgraph reflecting
11889 the ``extends'' relation is a tree).
11890
11891 A project's @dfn{immediate sources} are the source files directly defined by
11892 that project, either implicitly by residing in the project file's directory,
11893 or explicitly through any of the source-related attributes described below.
11894 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11895 of @var{proj} together with the immediate sources (unless overridden) of any
11896 project on which @var{proj} depends (either directly or indirectly).
11897
11898 @node Basic Syntax
11899 @subsection Basic Syntax
11900
11901 @noindent
11902 As seen in the earlier examples, project files have an Ada-like syntax.
11903 The minimal project file is:
11904 @smallexample @c projectfile
11905 @group
11906 project Empty is
11907
11908 end Empty;
11909 @end group
11910 @end smallexample
11911
11912 @noindent
11913 The identifier @code{Empty} is the name of the project.
11914 This project name must be present after the reserved
11915 word @code{end} at the end of the project file, followed by a semi-colon.
11916
11917 Any name in a project file, such as the project name or a variable name,
11918 has the same syntax as an Ada identifier.
11919
11920 The reserved words of project files are the Ada reserved words plus
11921 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11922 reserved words currently used in project file syntax are:
11923
11924 @itemize @bullet
11925 @item
11926 @code{case}
11927 @item
11928 @code{end}
11929 @item
11930 @code{for}
11931 @item
11932 @code{is}
11933 @item
11934 @code{others}
11935 @item
11936 @code{package}
11937 @item
11938 @code{renames}
11939 @item
11940 @code{type}
11941 @item
11942 @code{use}
11943 @item
11944 @code{when}
11945 @item
11946 @code{with}
11947 @end itemize
11948
11949 @noindent
11950 Comments in project files have the same syntax as in Ada, two consecutive
11951 hyphens through the end of the line.
11952
11953 @node Packages
11954 @subsection Packages
11955
11956 @noindent
11957 A project file may contain @emph{packages}. The name of a package must be one
11958 of the identifiers from the following list. A package
11959 with a given name may only appear once in a project file. Package names are
11960 case insensitive. The following package names are legal:
11961
11962 @itemize @bullet
11963 @item
11964 @code{Naming}
11965 @item
11966 @code{Builder}
11967 @item
11968 @code{Compiler}
11969 @item
11970 @code{Binder}
11971 @item
11972 @code{Linker}
11973 @item
11974 @code{Finder}
11975 @item
11976 @code{Cross_Reference}
11977 @item
11978 @code{Eliminate}
11979 @item
11980 @code{Pretty_Printer}
11981 @item
11982 @code{Metrics}
11983 @item
11984 @code{gnatls}
11985 @item
11986 @code{gnatstub}
11987 @item
11988 @code{IDE}
11989 @item
11990 @code{Language_Processing}
11991 @end itemize
11992
11993 @noindent
11994 In its simplest form, a package may be empty:
11995
11996 @smallexample @c projectfile
11997 @group
11998 project Simple is
11999   package Builder is
12000   end Builder;
12001 end Simple;
12002 @end group
12003 @end smallexample
12004
12005 @noindent
12006 A package may contain @emph{attribute declarations},
12007 @emph{variable declarations} and @emph{case constructions}, as will be
12008 described below.
12009
12010 When there is ambiguity between a project name and a package name,
12011 the name always designates the project. To avoid possible confusion, it is
12012 always a good idea to avoid naming a project with one of the
12013 names allowed for packages or any name that starts with @code{gnat}.
12014
12015 @node Expressions
12016 @subsection Expressions
12017
12018 @noindent
12019 An @emph{expression} is either a @emph{string expression} or a
12020 @emph{string list expression}.
12021
12022 A @emph{string expression} is either a @emph{simple string expression} or a
12023 @emph{compound string expression}.
12024
12025 A @emph{simple string expression} is one of the following:
12026 @itemize @bullet
12027 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12028 @item A string-valued variable reference (@pxref{Variables})
12029 @item A string-valued attribute reference (@pxref{Attributes})
12030 @item An external reference (@pxref{External References in Project Files})
12031 @end itemize
12032
12033 @noindent
12034 A @emph{compound string expression} is a concatenation of string expressions,
12035 using the operator @code{"&"}
12036 @smallexample
12037        Path & "/" & File_Name & ".ads"
12038 @end smallexample
12039
12040 @noindent
12041 A @emph{string list expression} is either a
12042 @emph{simple string list expression} or a
12043 @emph{compound string list expression}.
12044
12045 A @emph{simple string list expression} is one of the following:
12046 @itemize @bullet
12047 @item A parenthesized list of zero or more string expressions,
12048 separated by commas
12049 @smallexample
12050    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12051    Empty_List := ();
12052 @end smallexample
12053 @item A string list-valued variable reference
12054 @item A string list-valued attribute reference
12055 @end itemize
12056
12057 @noindent
12058 A @emph{compound string list expression} is the concatenation (using
12059 @code{"&"}) of a simple string list expression and an expression.  Note that
12060 each term in a compound string list expression, except the first, may be
12061 either a string expression or a string list expression.
12062
12063 @smallexample @c projectfile
12064 @group
12065    File_Name_List := () & File_Name; --  One string in this list
12066    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12067    --  Two strings
12068    Big_List := File_Name_List & Extended_File_Name_List;
12069    --  Concatenation of two string lists: three strings
12070    Illegal_List := "gnat.adc" & Extended_File_Name_List;
12071    --  Illegal: must start with a string list
12072 @end group
12073 @end smallexample
12074
12075 @node String Types
12076 @subsection String Types
12077
12078 @noindent
12079 A @emph{string type declaration} introduces a discrete set of string literals.
12080 If a string variable is declared to have this type, its value
12081 is restricted to the given set of literals.
12082
12083 Here is an example of a string type declaration:
12084
12085 @smallexample @c projectfile
12086    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12087 @end smallexample
12088
12089 @noindent
12090 Variables of a string type are called @emph{typed variables}; all other
12091 variables are called @emph{untyped variables}. Typed variables are
12092 particularly useful in @code{case} constructions, to support conditional
12093 attribute declarations.
12094 (@pxref{case Constructions}).
12095
12096 The string literals in the list are case sensitive and must all be different.
12097 They may include any graphic characters allowed in Ada, including spaces.
12098
12099 A string type may only be declared at the project level, not inside a package.
12100
12101 A string type may be referenced by its name if it has been declared in the same
12102 project file, or by an expanded name whose prefix is the name of the project
12103 in which it is declared.
12104
12105 @node Variables
12106 @subsection Variables
12107
12108 @noindent
12109 A variable may be declared at the project file level, or within a package.
12110 Here are some examples of variable declarations:
12111
12112 @smallexample @c projectfile
12113 @group
12114    This_OS : OS := external ("OS"); --  a typed variable declaration
12115    That_OS := "GNU/Linux";          --  an untyped variable declaration
12116 @end group
12117 @end smallexample
12118
12119 @noindent
12120 The syntax of a @emph{typed variable declaration} is identical to the Ada
12121 syntax for an object declaration. By contrast, the syntax of an untyped
12122 variable declaration is identical to an Ada assignment statement. In fact,
12123 variable declarations in project files have some of the characteristics of
12124 an assignment, in that successive declarations for the same variable are
12125 allowed. Untyped variable declarations do establish the expected kind of the
12126 variable (string or string list), and successive declarations for it must
12127 respect the initial kind.
12128
12129 @noindent
12130 A string variable declaration (typed or untyped) declares a variable
12131 whose value is a string. This variable may be used as a string expression.
12132 @smallexample @c projectfile
12133    File_Name       := "readme.txt";
12134    Saved_File_Name := File_Name & ".saved";
12135 @end smallexample
12136
12137 @noindent
12138 A string list variable declaration declares a variable whose value is a list
12139 of strings. The list may contain any number (zero or more) of strings.
12140
12141 @smallexample @c projectfile
12142    Empty_List := ();
12143    List_With_One_Element := ("^-gnaty^-gnaty^");
12144    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12145    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12146                  "pack2.ada", "util_.ada", "util.ada");
12147 @end smallexample
12148
12149 @noindent
12150 The same typed variable may not be declared more than once at project level,
12151 and it may not be declared more than once in any package; it is in effect
12152 a constant.
12153
12154 The same untyped variable may be declared several times. Declarations are
12155 elaborated in the order in which they appear, so  the new value replaces
12156 the old one, and any subsequent reference to the variable uses the new value.
12157 However, as noted above, if a variable has been declared as a string, all
12158 subsequent
12159 declarations must give it a string value. Similarly, if a variable has
12160 been declared as a string list, all subsequent declarations
12161 must give it a string list value.
12162
12163 A @emph{variable reference} may take several forms:
12164
12165 @itemize @bullet
12166 @item The simple variable name, for a variable in the current package (if any)
12167 or in the current project
12168 @item An expanded name, whose prefix is a context name.
12169 @end itemize
12170
12171 @noindent
12172 A @emph{context} may be one of the following:
12173
12174 @itemize @bullet
12175 @item The name of an existing package in the current project
12176 @item The name of an imported project of the current project
12177 @item The name of an ancestor project (i.e., a project extended by the current
12178 project, either directly or indirectly)
12179 @item An expanded name whose prefix is an imported/parent project name, and
12180 whose selector is a package name in that project.
12181 @end itemize
12182
12183 @noindent
12184 A variable reference may be used in an expression.
12185
12186 @node Attributes
12187 @subsection Attributes
12188
12189 @noindent
12190 A project (and its packages) may have @emph{attributes} that define
12191 the project's properties.  Some attributes have values that are strings;
12192 others have values that are string lists.
12193
12194 There are two categories of attributes: @emph{simple attributes}
12195 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12196
12197 Legal project attribute names, and attribute names for each legal package are
12198 listed below. Attributes names are case-insensitive.
12199
12200 The following attributes are defined on projects (all are simple attributes):
12201
12202 @multitable @columnfractions .4 .3
12203 @item @emph{Attribute Name}
12204 @tab @emph{Value}
12205 @item @code{Source_Files}
12206 @tab string list
12207 @item @code{Source_Dirs}
12208 @tab string list
12209 @item @code{Source_List_File}
12210 @tab string
12211 @item @code{Object_Dir}
12212 @tab string
12213 @item @code{Exec_Dir}
12214 @tab string
12215 @item @code{Excluded_Source_Dirs}
12216 @tab string list
12217 @item @code{Excluded_Source_Files}
12218 @tab string list
12219 @item @code{Languages}
12220 @tab string list
12221 @item @code{Main}
12222 @tab string list
12223 @item @code{Library_Dir}
12224 @tab string
12225 @item @code{Library_Name}
12226 @tab string
12227 @item @code{Library_Kind}
12228 @tab string
12229 @item @code{Library_Version}
12230 @tab string
12231 @item @code{Library_Interface}
12232 @tab string
12233 @item @code{Library_Auto_Init}
12234 @tab string
12235 @item @code{Library_Options}
12236 @tab string list
12237 @item @code{Library_Src_Dir}
12238 @tab string
12239 @item @code{Library_ALI_Dir}
12240 @tab string
12241 @item @code{Library_GCC}
12242 @tab string
12243 @item @code{Library_Symbol_File}
12244 @tab string
12245 @item @code{Library_Symbol_Policy}
12246 @tab string
12247 @item @code{Library_Reference_Symbol_File}
12248 @tab string
12249 @item @code{Externally_Built}
12250 @tab string
12251 @end multitable
12252
12253 @noindent
12254 The following attributes are defined for package  @code{Naming}
12255 (@pxref{Naming Schemes}):
12256
12257 @multitable @columnfractions .4 .2 .2 .2
12258 @item Attribute Name @tab Category @tab Index @tab Value
12259 @item @code{Spec_Suffix}
12260 @tab associative array
12261 @tab language name
12262 @tab string
12263 @item @code{Body_Suffix}
12264 @tab associative array
12265 @tab language name
12266 @tab string
12267 @item @code{Separate_Suffix}
12268 @tab simple attribute
12269 @tab n/a
12270 @tab string
12271 @item @code{Casing}
12272 @tab simple attribute
12273 @tab n/a
12274 @tab string
12275 @item @code{Dot_Replacement}
12276 @tab simple attribute
12277 @tab n/a
12278 @tab string
12279 @item @code{Spec}
12280 @tab associative array
12281 @tab Ada unit name
12282 @tab string
12283 @item @code{Body}
12284 @tab associative array
12285 @tab Ada unit name
12286 @tab string
12287 @item @code{Specification_Exceptions}
12288 @tab associative array
12289 @tab language name
12290 @tab string list
12291 @item @code{Implementation_Exceptions}
12292 @tab associative array
12293 @tab language name
12294 @tab string list
12295 @end multitable
12296
12297 @noindent
12298 The following attributes are defined for packages @code{Builder},
12299 @code{Compiler}, @code{Binder},
12300 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12301 (@pxref{^Switches^Switches^ and Project Files}).
12302
12303 @multitable @columnfractions .4 .2 .2 .2
12304 @item Attribute Name @tab Category @tab Index @tab Value
12305 @item @code{^Default_Switches^Default_Switches^}
12306 @tab associative array
12307 @tab language name
12308 @tab string list
12309 @item @code{^Switches^Switches^}
12310 @tab associative array
12311 @tab file name
12312 @tab string list
12313 @end multitable
12314
12315 @noindent
12316 In addition, package @code{Compiler} has a single string attribute
12317 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12318 string attribute @code{Global_Configuration_Pragmas}.
12319
12320 @noindent
12321 Each simple attribute has a default value: the empty string (for string-valued
12322 attributes) and the empty list (for string list-valued attributes).
12323
12324 An attribute declaration defines a new value for an attribute.
12325
12326 Examples of simple attribute declarations:
12327
12328 @smallexample @c projectfile
12329    for Object_Dir use "objects";
12330    for Source_Dirs use ("units", "test/drivers");
12331 @end smallexample
12332
12333 @noindent
12334 The syntax of a @dfn{simple attribute declaration} is similar to that of an
12335 attribute definition clause in Ada.
12336
12337 Attributes references may be appear in expressions.
12338 The general form for such a reference is @code{<entity>'<attribute>}:
12339 Associative array attributes are functions. Associative
12340 array attribute references must have an argument that is a string literal.
12341
12342 Examples are:
12343
12344 @smallexample @c projectfile
12345   project'Object_Dir
12346   Naming'Dot_Replacement
12347   Imported_Project'Source_Dirs
12348   Imported_Project.Naming'Casing
12349   Builder'^Default_Switches^Default_Switches^("Ada")
12350 @end smallexample
12351
12352 @noindent
12353 The prefix of an attribute may be:
12354 @itemize @bullet
12355 @item @code{project} for an attribute of the current project
12356 @item The name of an existing package of the current project
12357 @item The name of an imported project
12358 @item The name of a parent project that is extended by the current project
12359 @item An expanded name whose prefix is imported/parent project name,
12360       and whose selector is a package name
12361 @end itemize
12362
12363 @noindent
12364 Example:
12365 @smallexample @c projectfile
12366 @group
12367    project Prj is
12368      for Source_Dirs use project'Source_Dirs & "units";
12369      for Source_Dirs use project'Source_Dirs & "test/drivers"
12370    end Prj;
12371 @end group
12372 @end smallexample
12373
12374 @noindent
12375 In the first attribute declaration, initially the attribute @code{Source_Dirs}
12376 has the default value: an empty string list. After this declaration,
12377 @code{Source_Dirs} is a string list of one element: @code{"units"}.
12378 After the second attribute declaration @code{Source_Dirs} is a string list of
12379 two elements: @code{"units"} and @code{"test/drivers"}.
12380
12381 Note: this example is for illustration only. In practice,
12382 the project file would contain only one attribute declaration:
12383
12384 @smallexample @c projectfile
12385    for Source_Dirs use ("units", "test/drivers");
12386 @end smallexample
12387
12388 @node Associative Array Attributes
12389 @subsection Associative Array Attributes
12390
12391 @noindent
12392 Some attributes are defined as @emph{associative arrays}. An associative
12393 array may be regarded as a function that takes a string as a parameter
12394 and delivers a string or string list value as its result.
12395
12396 Here are some examples of single associative array attribute associations:
12397
12398 @smallexample @c projectfile
12399    for Body ("main") use "Main.ada";
12400    for ^Switches^Switches^ ("main.ada")
12401        use ("^-v^-v^",
12402             "^-gnatv^-gnatv^");
12403    for ^Switches^Switches^ ("main.ada")
12404             use Builder'^Switches^Switches^ ("main.ada")
12405               & "^-g^-g^";
12406 @end smallexample
12407
12408 @noindent
12409 Like untyped variables and simple attributes, associative array attributes
12410 may be declared several times. Each declaration supplies a new value for the
12411 attribute, and replaces the previous setting.
12412
12413 @noindent
12414 An associative array attribute may be declared as a full associative array
12415 declaration, with the value of the same attribute in an imported or extended
12416 project.
12417
12418 @smallexample @c projectfile
12419    package Builder is
12420       for Default_Switches use Default.Builder'Default_Switches;
12421    end Builder;
12422 @end smallexample
12423
12424 @noindent
12425 In this example, @code{Default} must be either a project imported by the
12426 current project, or the project that the current project extends. If the
12427 attribute is in a package (in this case, in package @code{Builder}), the same
12428 package needs to be specified.
12429
12430 @noindent
12431 A full associative array declaration replaces any other declaration for the
12432 attribute, including other full associative array declaration. Single
12433 associative array associations may be declare after a full associative
12434 declaration, modifying the value for a single association of the attribute.
12435
12436 @node case Constructions
12437 @subsection @code{case} Constructions
12438
12439 @noindent
12440 A @code{case} construction is used in a project file to effect conditional
12441 behavior.
12442 Here is a typical example:
12443
12444 @smallexample @c projectfile
12445 @group
12446 project MyProj is
12447    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
12448
12449    OS : OS_Type := external ("OS", "GNU/Linux");
12450 @end group
12451
12452 @group
12453    package Compiler is
12454      case OS is
12455        when "GNU/Linux" | "Unix" =>
12456          for ^Default_Switches^Default_Switches^ ("Ada")
12457              use ("^-gnath^-gnath^");
12458        when "NT" =>
12459          for ^Default_Switches^Default_Switches^ ("Ada")
12460              use ("^-gnatP^-gnatP^");
12461        when others =>
12462      end case;
12463    end Compiler;
12464 end MyProj;
12465 @end group
12466 @end smallexample
12467
12468 @noindent
12469 The syntax of a @code{case} construction is based on the Ada case statement
12470 (although there is no @code{null} construction for empty alternatives).
12471
12472 The case expression must be a typed string variable.
12473 Each alternative comprises the reserved word @code{when}, either a list of
12474 literal strings separated by the @code{"|"} character or the reserved word
12475 @code{others},  and the @code{"=>"} token.
12476 Each literal string must belong to the string type that is the type of the
12477 case variable.
12478 An @code{others} alternative, if present, must occur last.
12479
12480 After each @code{=>}, there are zero or more constructions.  The only
12481 constructions allowed in a case construction are other case constructions,
12482 attribute declarations and variable declarations. String type declarations and
12483 package declarations are not allowed. Variable declarations are restricted to
12484 variables that have already been declared before the case construction.
12485
12486 The value of the case variable is often given by an external reference
12487 (@pxref{External References in Project Files}).
12488
12489 @c ****************************************
12490 @c * Objects and Sources in Project Files *
12491 @c ****************************************
12492
12493 @node Objects and Sources in Project Files
12494 @section Objects and Sources in Project Files
12495
12496 @menu
12497 * Object Directory::
12498 * Exec Directory::
12499 * Source Directories::
12500 * Source File Names::
12501 @end menu
12502
12503 @noindent
12504 Each project has exactly one object directory and one or more source
12505 directories. The source directories must contain at least one source file,
12506 unless  the project file explicitly specifies that no source files are present
12507 (@pxref{Source File Names}).
12508
12509 @node Object Directory
12510 @subsection Object Directory
12511
12512 @noindent
12513 The object directory for a project is the directory containing the compiler's
12514 output (such as @file{ALI} files and object files) for the project's immediate
12515 sources.
12516
12517 The object directory is given by the value of the attribute @code{Object_Dir}
12518 in the project file.
12519
12520 @smallexample @c projectfile
12521    for Object_Dir use "objects";
12522 @end smallexample
12523
12524 @noindent
12525 The attribute @code{Object_Dir} has a string value, the path name of the object
12526 directory. The path name may be absolute or relative to the directory of the
12527 project file. This directory must already exist, and be readable and writable.
12528
12529 By default, when the attribute @code{Object_Dir} is not given an explicit value
12530 or when its value is the empty string, the object directory is the same as the
12531 directory containing the project file.
12532
12533 @node Exec Directory
12534 @subsection Exec Directory
12535
12536 @noindent
12537 The exec directory for a project is the directory containing the executables
12538 for the project's main subprograms.
12539
12540 The exec directory is given by the value of the attribute @code{Exec_Dir}
12541 in the project file.
12542
12543 @smallexample @c projectfile
12544    for Exec_Dir use "executables";
12545 @end smallexample
12546
12547 @noindent
12548 The attribute @code{Exec_Dir} has a string value, the path name of the exec
12549 directory. The path name may be absolute or relative to the directory of the
12550 project file. This directory must already exist, and be writable.
12551
12552 By default, when the attribute @code{Exec_Dir} is not given an explicit value
12553 or when its value is the empty string, the exec directory is the same as the
12554 object directory of the project file.
12555
12556 @node Source Directories
12557 @subsection Source Directories
12558
12559 @noindent
12560 The source directories of a project are specified by the project file
12561 attribute @code{Source_Dirs}.
12562
12563 This attribute's value is a string list. If the attribute is not given an
12564 explicit value, then there is only one source directory, the one where the
12565 project file resides.
12566
12567 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
12568 as in
12569
12570 @smallexample @c projectfile
12571     for Source_Dirs use ();
12572 @end smallexample
12573
12574 @noindent
12575 indicates that the project contains no source files.
12576
12577 Otherwise, each string in the string list designates one or more
12578 source directories.
12579
12580 @smallexample @c projectfile
12581    for Source_Dirs use ("sources", "test/drivers");
12582 @end smallexample
12583
12584 @noindent
12585 If a string in the list ends with @code{"/**"},  then the directory whose path
12586 name precedes the two asterisks, as well as all its subdirectories
12587 (recursively), are source directories.
12588
12589 @smallexample @c projectfile
12590    for Source_Dirs use ("/system/sources/**");
12591 @end smallexample
12592
12593 @noindent
12594 Here the directory @code{/system/sources} and all of its subdirectories
12595 (recursively) are source directories.
12596
12597 To specify that the source directories are the directory of the project file
12598 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
12599 @smallexample @c projectfile
12600    for Source_Dirs use ("./**");
12601 @end smallexample
12602
12603 @noindent
12604 Each of the source directories must exist and be readable.
12605
12606 @node Source File Names
12607 @subsection Source File Names
12608
12609 @noindent
12610 In a project that contains source files, their names may be specified by the
12611 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
12612 (a string). Source file names never include any directory information.
12613
12614 If the attribute @code{Source_Files} is given an explicit value, then each
12615 element of the list is a source file name.
12616
12617 @smallexample @c projectfile
12618    for Source_Files use ("main.adb");
12619    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
12620 @end smallexample
12621
12622 @noindent
12623 If the attribute @code{Source_Files} is not given an explicit value,
12624 but the attribute @code{Source_List_File} is given a string value,
12625 then the source file names are contained in the text file whose path name
12626 (absolute or relative to the directory of the project file) is the
12627 value of the attribute @code{Source_List_File}.
12628
12629 Each line in the file that is not empty or is not a comment
12630 contains a source file name.
12631
12632 @smallexample @c projectfile
12633    for Source_List_File use "source_list.txt";
12634 @end smallexample
12635
12636 @noindent
12637 By default, if neither the attribute @code{Source_Files} nor the attribute
12638 @code{Source_List_File} is given an explicit value, then each file in the
12639 source directories that conforms to the project's naming scheme
12640 (@pxref{Naming Schemes}) is an immediate source of the project.
12641
12642 A warning is issued if both attributes @code{Source_Files} and
12643 @code{Source_List_File} are given explicit values. In this case, the attribute
12644 @code{Source_Files} prevails.
12645
12646 Each source file name must be the name of one existing source file
12647 in one of the source directories.
12648
12649 A @code{Source_Files} attribute whose value is an empty list
12650 indicates that there are no source files in the project.
12651
12652 If the order of the source directories is known statically, that is if
12653 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
12654 be several files with the same source file name. In this case, only the file
12655 in the first directory is considered as an immediate source of the project
12656 file. If the order of the source directories is not known statically, it is
12657 an error to have several files with the same source file name.
12658
12659 Projects can be specified to have no Ada source
12660 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
12661 list, or the @code{"Ada"} may be absent from @code{Languages}:
12662
12663 @smallexample @c projectfile
12664    for Source_Dirs use ();
12665    for Source_Files use ();
12666    for Languages use ("C", "C++");
12667 @end smallexample
12668
12669 @noindent
12670 Otherwise, a project must contain at least one immediate source.
12671
12672 Projects with no source files are useful as template packages
12673 (@pxref{Packages in Project Files}) for other projects; in particular to
12674 define a package @code{Naming} (@pxref{Naming Schemes}).
12675
12676 @c ****************************
12677 @c * Importing Projects *
12678 @c ****************************
12679
12680 @node  Importing Projects
12681 @section Importing Projects
12682 @cindex @code{ADA_PROJECT_PATH}
12683
12684 @noindent
12685 An immediate source of a project P may depend on source files that
12686 are neither immediate sources of P nor in the predefined library.
12687 To get this effect, P must @emph{import} the projects that contain the needed
12688 source files.
12689
12690 @smallexample @c projectfile
12691 @group
12692   with "project1", "utilities.gpr";
12693   with "/namings/apex.gpr";
12694   project Main is
12695     @dots{}
12696 @end group
12697 @end smallexample
12698
12699 @noindent
12700 As can be seen in this example, the syntax for importing projects is similar
12701 to the syntax for importing compilation units in Ada. However, project files
12702 use literal strings instead of names, and the @code{with} clause identifies
12703 project files rather than packages.
12704
12705 Each literal string is the file name or path name (absolute or relative) of a
12706 project file. If a string corresponds to a file name, with no path or a
12707 relative path, then its location is determined by the @emph{project path}. The
12708 latter can be queried using @code{gnatls -v}. It contains:
12709
12710 @itemize @bullet
12711 @item
12712 In first position, the directory containing the current project file.
12713 @item
12714 In last position, the default project directory. This default project directory
12715 is part of the GNAT installation and is the standard place to install project
12716 files giving access to standard support libraries.
12717 @ifclear vms
12718 @ref{Installing a library}
12719 @end ifclear
12720
12721 @item
12722 In between, all the directories referenced in the
12723 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
12724 @end itemize
12725
12726 @noindent
12727 If a relative pathname is used, as in
12728
12729 @smallexample @c projectfile
12730   with "tests/proj";
12731 @end smallexample
12732
12733 @noindent
12734 then the full path for the project is constructed by concatenating this
12735 relative path to those in the project path, in order, until a matching file is
12736 found. Any symbolic link will be fully resolved in the directory of the
12737 importing project file before the imported project file is examined.
12738
12739 If the @code{with}'ed project file name does not have an extension,
12740 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
12741 then the file name as specified in the @code{with} clause (no extension) will
12742 be used. In the above example, if a file @code{project1.gpr} is found, then it
12743 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
12744 then it will be used; if neither file exists, this is an error.
12745
12746 A warning is issued if the name of the project file does not match the
12747 name of the project; this check is case insensitive.
12748
12749 Any source file that is an immediate source of the imported project can be
12750 used by the immediate sources of the importing project, transitively. Thus
12751 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
12752 sources of @code{A} may depend on the immediate sources of @code{C}, even if
12753 @code{A} does not import @code{C} explicitly. However, this is not recommended,
12754 because if and when @code{B} ceases to import @code{C}, some sources in
12755 @code{A} will no longer compile.
12756
12757 A side effect of this capability is that normally cyclic dependencies are not
12758 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
12759 is not allowed to import @code{A}. However, there are cases when cyclic
12760 dependencies would be beneficial. For these cases, another form of import
12761 between projects exists, the @code{limited with}: a project @code{A} that
12762 imports a project @code{B} with a straight @code{with} may also be imported,
12763 directly or indirectly, by @code{B} on the condition that imports from @code{B}
12764 to @code{A} include at least one @code{limited with}.
12765
12766 @smallexample @c 0projectfile
12767 with "../b/b.gpr";
12768 with "../c/c.gpr";
12769 project A is
12770 end A;
12771
12772 limited with "../a/a.gpr";
12773 project B is
12774 end B;
12775
12776 with "../d/d.gpr";
12777 project C is
12778 end C;
12779
12780 limited with "../a/a.gpr";
12781 project D is
12782 end D;
12783 @end smallexample
12784
12785 @noindent
12786 In the above legal example, there are two project cycles:
12787 @itemize @bullet
12788 @item A-> B-> A
12789 @item A -> C -> D -> A
12790 @end itemize
12791
12792 @noindent
12793 In each of these cycle there is one @code{limited with}: import of @code{A}
12794 from @code{B} and import of @code{A} from @code{D}.
12795
12796 The difference between straight @code{with} and @code{limited with} is that
12797 the name of a project imported with a @code{limited with} cannot be used in the
12798 project that imports it. In particular, its packages cannot be renamed and
12799 its variables cannot be referred to.
12800
12801 An exception to the above rules for @code{limited with} is that for the main
12802 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12803 @code{limited with} is equivalent to a straight @code{with}. For example,
12804 in the example above, projects @code{B} and @code{D} could not be main
12805 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12806 each have a @code{limited with} that is the only one in a cycle of importing
12807 projects.
12808
12809 @c *********************
12810 @c * Project Extension *
12811 @c *********************
12812
12813 @node Project Extension
12814 @section Project Extension
12815
12816 @noindent
12817 During development of a large system, it is sometimes necessary to use
12818 modified versions of some of the source files, without changing the original
12819 sources. This can be achieved through the @emph{project extension} facility.
12820
12821 @smallexample @c projectfile
12822    project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
12823 @end smallexample
12824
12825 @noindent
12826 A project extension declaration introduces an extending project
12827 (the @emph{child}) and a project being extended (the @emph{parent}).
12828
12829 By default, a child project inherits all the sources of its parent.
12830 However, inherited sources can be overridden: a unit in a parent is hidden
12831 by a unit of the same name in the child.
12832
12833 Inherited sources are considered to be sources (but not immediate sources)
12834 of the child project; see @ref{Project File Syntax}.
12835
12836 An inherited source file retains any switches specified in the parent project.
12837
12838 For example if the project @code{Utilities} contains the specification and the
12839 body of an Ada package @code{Util_IO}, then the project
12840 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12841 The original body of @code{Util_IO} will not be considered in program builds.
12842 However, the package specification will still be found in the project
12843 @code{Utilities}.
12844
12845 A child project can have only one parent but it may import any number of other
12846 projects.
12847
12848 A project is not allowed to import directly or indirectly at the same time a
12849 child project and any of its ancestors.
12850
12851 @c *******************************
12852 @c * Project Hierarchy Extension *
12853 @c *******************************
12854
12855 @node Project Hierarchy Extension
12856 @section Project Hierarchy Extension
12857
12858 @noindent
12859 When extending a large system spanning multiple projects, it is often
12860 inconvenient to extend every project in the hierarchy that is impacted by a
12861 small change introduced. In such cases, it is possible to create a virtual
12862 extension of entire hierarchy using @code{extends all} relationship.
12863
12864 When the project is extended using @code{extends all} inheritance, all projects
12865 that are imported by it, both directly and indirectly, are considered virtually
12866 extended. That is, the Project Manager creates "virtual projects"
12867 that extend every project in the hierarchy; all these virtual projects have
12868 no sources of their own and have as object directory the object directory of
12869 the root of "extending all" project.
12870
12871 It is possible to explicitly extend one or more projects in the hierarchy
12872 in order to modify the sources. These extending projects must be imported by
12873 the "extending all" project, which will replace the corresponding virtual
12874 projects with the explicit ones.
12875
12876 When building such a project hierarchy extension, the Project Manager will
12877 ensure that both modified sources and sources in virtual extending projects
12878 that depend on them, are recompiled.
12879
12880 By means of example, consider the following hierarchy of projects.
12881
12882 @enumerate
12883 @item
12884 project A, containing package P1
12885 @item
12886 project B importing A and containing package P2 which depends on P1
12887 @item
12888 project C importing B and containing package P3 which depends on P2
12889 @end enumerate
12890
12891 @noindent
12892 We want to modify packages P1 and P3.
12893
12894 This project hierarchy will need to be extended as follows:
12895
12896 @enumerate
12897 @item
12898 Create project A1 that extends A, placing modified P1 there:
12899
12900 @smallexample @c 0projectfile
12901 project A1 extends "(@dots{})/A" is
12902 end A1;
12903 @end smallexample
12904
12905 @item
12906 Create project C1 that "extends all" C and imports A1, placing modified
12907 P3 there:
12908
12909 @smallexample @c 0projectfile
12910 with "(@dots{})/A1";
12911 project C1 extends all "(@dots{})/C" is
12912 end C1;
12913 @end smallexample
12914 @end enumerate
12915
12916 When you build project C1, your entire modified project space will be
12917 recompiled, including the virtual project B1 that has been impacted by the
12918 "extending all" inheritance of project C.
12919
12920 Note that if a Library Project in the hierarchy is virtually extended,
12921 the virtual project that extends the Library Project is not a Library Project.
12922
12923 @c ****************************************
12924 @c * External References in Project Files *
12925 @c ****************************************
12926
12927 @node  External References in Project Files
12928 @section External References in Project Files
12929
12930 @noindent
12931 A project file may contain references to external variables; such references
12932 are called @emph{external references}.
12933
12934 An external variable is either defined as part of the environment (an
12935 environment variable in Unix, for example) or else specified on the command
12936 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12937 If both, then the command line value is used.
12938
12939 The value of an external reference is obtained by means of the built-in
12940 function @code{external}, which returns a string value.
12941 This function has two forms:
12942 @itemize @bullet
12943 @item @code{external (external_variable_name)}
12944 @item @code{external (external_variable_name, default_value)}
12945 @end itemize
12946
12947 @noindent
12948 Each parameter must be a string literal.  For example:
12949
12950 @smallexample @c projectfile
12951    external ("USER")
12952    external ("OS", "GNU/Linux")
12953 @end smallexample
12954
12955 @noindent
12956 In the form with one parameter, the function returns the value of
12957 the external variable given as parameter. If this name is not present in the
12958 environment, the function returns an empty string.
12959
12960 In the form with two string parameters, the second argument is
12961 the value returned when the variable given as the first argument is not
12962 present in the environment. In the example above, if @code{"OS"} is not
12963 the name of ^an environment variable^a logical name^ and is not passed on
12964 the command line, then the returned value is @code{"GNU/Linux"}.
12965
12966 An external reference may be part of a string expression or of a string
12967 list expression, and can therefore appear in a variable declaration or
12968 an attribute declaration.
12969
12970 @smallexample @c projectfile
12971 @group
12972    type Mode_Type is ("Debug", "Release");
12973    Mode : Mode_Type := external ("MODE");
12974    case Mode is
12975      when "Debug" =>
12976         @dots{}
12977 @end group
12978 @end smallexample
12979
12980 @c *****************************
12981 @c * Packages in Project Files *
12982 @c *****************************
12983
12984 @node  Packages in Project Files
12985 @section Packages in Project Files
12986
12987 @noindent
12988 A @emph{package} defines the settings for project-aware tools within a
12989 project.
12990 For each such tool one can declare a package; the names for these
12991 packages are preset (@pxref{Packages}).
12992 A package may contain variable declarations, attribute declarations, and case
12993 constructions.
12994
12995 @smallexample @c projectfile
12996 @group
12997    project Proj is
12998       package Builder is  -- used by gnatmake
12999          for ^Default_Switches^Default_Switches^ ("Ada")
13000              use ("^-v^-v^",
13001                   "^-g^-g^");
13002       end Builder;
13003    end Proj;
13004 @end group
13005 @end smallexample
13006
13007 @noindent
13008 The syntax of package declarations mimics that of package in Ada.
13009
13010 Most of the packages have an attribute
13011 @code{^Default_Switches^Default_Switches^}.
13012 This attribute is an associative array, and its value is a string list.
13013 The index of the associative array is the name of a programming language (case
13014 insensitive). This attribute indicates the ^switch^switch^
13015 or ^switches^switches^ to be used
13016 with the corresponding tool.
13017
13018 Some packages also have another attribute, @code{^Switches^Switches^},
13019 an associative array whose value is a string list.
13020 The index is the name of a source file.
13021 This attribute indicates the ^switch^switch^
13022 or ^switches^switches^ to be used by the corresponding
13023 tool when dealing with this specific file.
13024
13025 Further information on these ^switch^switch^-related attributes is found in
13026 @ref{^Switches^Switches^ and Project Files}.
13027
13028 A package may be declared as a @emph{renaming} of another package; e.g., from
13029 the project file for an imported project.
13030
13031 @smallexample @c projectfile
13032 @group
13033   with "/global/apex.gpr";
13034   project Example is
13035     package Naming renames Apex.Naming;
13036     @dots{}
13037   end Example;
13038 @end group
13039 @end smallexample
13040
13041 @noindent
13042 Packages that are renamed in other project files often come from project files
13043 that have no sources: they are just used as templates. Any modification in the
13044 template will be reflected automatically in all the project files that rename
13045 a package from the template.
13046
13047 In addition to the tool-oriented packages, you can also declare a package
13048 named @code{Naming} to establish specialized source file naming conventions
13049 (@pxref{Naming Schemes}).
13050
13051 @c ************************************
13052 @c * Variables from Imported Projects *
13053 @c ************************************
13054
13055 @node Variables from Imported Projects
13056 @section Variables from Imported Projects
13057
13058 @noindent
13059 An attribute or variable defined in an imported or parent project can
13060 be used in expressions in the importing / extending project.
13061 Such an attribute or variable is denoted by an expanded name whose prefix
13062 is either the name of the project or the expanded name of a package within
13063 a project.
13064
13065 @smallexample @c projectfile
13066 @group
13067   with "imported";
13068   project Main extends "base" is
13069      Var1 := Imported.Var;
13070      Var2 := Base.Var & ".new";
13071 @end group
13072
13073 @group
13074      package Builder is
13075         for ^Default_Switches^Default_Switches^ ("Ada")
13076             use Imported.Builder'Ada_^Switches^Switches^ &
13077                 "^-gnatg^-gnatg^" &
13078                 "^-v^-v^";
13079      end Builder;
13080 @end group
13081
13082 @group
13083      package Compiler is
13084         for ^Default_Switches^Default_Switches^ ("Ada")
13085             use Base.Compiler'Ada_^Switches^Switches^;
13086      end Compiler;
13087   end Main;
13088 @end group
13089 @end smallexample
13090
13091 @noindent
13092 In this example:
13093
13094 @itemize @bullet
13095 @item
13096 The value of @code{Var1} is a copy of the variable @code{Var} defined
13097 in the project file @file{"imported.gpr"}
13098 @item
13099 the value of @code{Var2} is a copy of the value of variable @code{Var}
13100 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13101 @item
13102 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13103 @code{Builder} is a string list that includes in its value a copy of the value
13104 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13105 in project file @file{imported.gpr} plus two new elements:
13106 @option{"^-gnatg^-gnatg^"}
13107 and @option{"^-v^-v^"};
13108 @item
13109 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13110 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13111 defined in the @code{Compiler} package in project file @file{base.gpr},
13112 the project being extended.
13113 @end itemize
13114
13115 @c ******************
13116 @c * Naming Schemes *
13117 @c ******************
13118
13119 @node  Naming Schemes
13120 @section Naming Schemes
13121
13122 @noindent
13123 Sometimes an Ada software system is ported from a foreign compilation
13124 environment to GNAT, and the file names do not use the default GNAT
13125 conventions. Instead of changing all the file names (which for a variety
13126 of reasons might not be possible), you can define the relevant file
13127 naming scheme in the @code{Naming} package in your project file.
13128
13129 @noindent
13130 Note that the use of pragmas described in
13131 @ref{Alternative File Naming Schemes} by mean of a configuration
13132 pragmas file is not supported when using project files. You must use
13133 the features described in this paragraph. You can however use specify
13134 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13135
13136 @ifclear vms
13137 For example, the following
13138 package models the Apex file naming rules:
13139
13140 @smallexample @c projectfile
13141 @group
13142   package Naming is
13143     for Casing               use "lowercase";
13144     for Dot_Replacement      use ".";
13145     for Spec_Suffix ("Ada")  use ".1.ada";
13146     for Body_Suffix ("Ada")  use ".2.ada";
13147   end Naming;
13148 @end group
13149 @end smallexample
13150 @end ifclear
13151
13152 @ifset vms
13153 For example, the following package models the HP Ada file naming rules:
13154
13155 @smallexample @c projectfile
13156 @group
13157   package Naming is
13158     for Casing               use "lowercase";
13159     for Dot_Replacement      use "__";
13160     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
13161     for Body_Suffix ("Ada")  use ".^ada^ada^";
13162   end Naming;
13163 @end group
13164 @end smallexample
13165
13166 @noindent
13167 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13168 names in lower case)
13169 @end ifset
13170
13171 @noindent
13172 You can define the following attributes in package @code{Naming}:
13173
13174 @table @code
13175
13176 @item @code{Casing}
13177 This must be a string with one of the three values @code{"lowercase"},
13178 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13179
13180 @noindent
13181 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13182
13183 @item @code{Dot_Replacement}
13184 This must be a string whose value satisfies the following conditions:
13185
13186 @itemize @bullet
13187 @item It must not be empty
13188 @item It cannot start or end with an alphanumeric character
13189 @item It cannot be a single underscore
13190 @item It cannot start with an underscore followed by an alphanumeric
13191 @item It cannot contain a dot @code{'.'} except if the entire string
13192 is @code{"."}
13193 @end itemize
13194
13195 @noindent
13196 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13197
13198 @item @code{Spec_Suffix}
13199 This is an associative array (indexed by the programming language name, case
13200 insensitive) whose value is a string that must satisfy the following
13201 conditions:
13202
13203 @itemize @bullet
13204 @item It must not be empty
13205 @item It must include at least one dot
13206 @end itemize
13207 @noindent
13208 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13209 @code{"^.ads^.ADS^"}.
13210
13211 @item @code{Body_Suffix}
13212 This is an associative array (indexed by the programming language name, case
13213 insensitive) whose value is a string that must satisfy the following
13214 conditions:
13215
13216 @itemize @bullet
13217 @item It must not be empty
13218 @item It must include at least one dot
13219 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13220 @end itemize
13221 @noindent
13222 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13223 same string, then a file name that ends with the longest of these two suffixes
13224 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13225 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13226
13227 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13228 @code{"^.adb^.ADB^"}.
13229
13230 @item @code{Separate_Suffix}
13231 This must be a string whose value satisfies the same conditions as
13232 @code{Body_Suffix}. The same "longest suffix" rules apply.
13233
13234 @noindent
13235 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13236 value as @code{Body_Suffix ("Ada")}.
13237
13238 @item @code{Spec}
13239 @noindent
13240 You can use the associative array attribute @code{Spec}  to define
13241 the source file name for an individual Ada compilation unit's spec. The array
13242 index must be a string literal that identifies the Ada unit (case insensitive).
13243 The value of this attribute must be a string that identifies the file that
13244 contains this unit's spec (case sensitive or insensitive depending on the
13245 operating system).
13246
13247 @smallexample @c projectfile
13248    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13249 @end smallexample
13250
13251 @item @code{Body}
13252
13253 You can use the associative array attribute @code{Body} to
13254 define the source file name for an individual Ada compilation unit's body
13255 (possibly a subunit).  The array index must be a string literal that identifies
13256 the Ada unit (case insensitive).  The value of this attribute must be a string
13257 that identifies the file that contains this unit's body or subunit (case
13258 sensitive or insensitive depending on the operating system).
13259
13260 @smallexample @c projectfile
13261    for Body ("MyPack.MyChild") use "mypack.mychild.body";
13262 @end smallexample
13263 @end table
13264
13265 @c ********************
13266 @c * Library Projects *
13267 @c ********************
13268
13269 @node Library Projects
13270 @section Library Projects
13271
13272 @noindent
13273 @emph{Library projects} are projects whose object code is placed in a library.
13274 (Note that this facility is not yet supported on all platforms)
13275
13276 To create a library project, you need to define in its project file
13277 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
13278 Additionally, you may define other library-related attributes such as
13279 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
13280 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
13281
13282 The @code{Library_Name} attribute has a string value. There is no restriction
13283 on the name of a library. It is the responsibility of the developer to
13284 choose a name that will be accepted by the platform. It is recommended to
13285 choose names that could be Ada identifiers; such names are almost guaranteed
13286 to be acceptable on all platforms.
13287
13288 The @code{Library_Dir} attribute has a string value that designates the path
13289 (absolute or relative) of the directory where the library will reside.
13290 It must designate an existing directory, and this directory must be writable,
13291 different from the project's object directory and from any source directory
13292 in the project tree.
13293
13294 If both @code{Library_Name} and @code{Library_Dir} are specified and
13295 are legal, then the project file defines a library project.  The optional
13296 library-related attributes are checked only for such project files.
13297
13298 The @code{Library_Kind} attribute has a string value that must be one of the
13299 following (case insensitive): @code{"static"}, @code{"dynamic"} or
13300 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
13301 attribute is not specified, the library is a static library, that is
13302 an archive of object files that can be potentially linked into a
13303 static executable. Otherwise, the library may be dynamic or
13304 relocatable, that is a library that is loaded only at the start of execution.
13305
13306 If you need to build both a static and a dynamic library, you should use two
13307 different object directories, since in some cases some extra code needs to
13308 be generated for the latter. For such cases, it is recommended to either use
13309 two different project files, or a single one which uses external variables
13310 to indicate what kind of library should be build.
13311
13312 The @code{Library_ALI_Dir} attribute may be specified to indicate the
13313 directory where the ALI files of the library will be copied. When it is
13314 not specified, the ALI files are copied to the directory specified in
13315 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
13316 must be writable and different from the project's object directory and from
13317 any source directory in the project tree.
13318
13319 The @code{Library_Version} attribute has a string value whose interpretation
13320 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
13321 used only for dynamic/relocatable libraries as the internal name of the
13322 library (the @code{"soname"}). If the library file name (built from the
13323 @code{Library_Name}) is different from the @code{Library_Version}, then the
13324 library file will be a symbolic link to the actual file whose name will be
13325 @code{Library_Version}.
13326
13327 Example (on Unix):
13328
13329 @smallexample @c projectfile
13330 @group
13331 project Plib is
13332
13333    Version := "1";
13334
13335    for Library_Dir use "lib_dir";
13336    for Library_Name use "dummy";
13337    for Library_Kind use "relocatable";
13338    for Library_Version use "libdummy.so." & Version;
13339
13340 end Plib;
13341 @end group
13342 @end smallexample
13343
13344 @noindent
13345 Directory @file{lib_dir} will contain the internal library file whose name
13346 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
13347 @file{libdummy.so.1}.
13348
13349 When @command{gnatmake} detects that a project file
13350 is a library project file, it will check all immediate sources of the project
13351 and rebuild the library if any of the sources have been recompiled.
13352
13353 Standard project files can import library project files. In such cases,
13354 the libraries will only be rebuilt if some of its sources are recompiled
13355 because they are in the closure of some other source in an importing project.
13356 Sources of the library project files that are not in such a closure will
13357 not be checked, unless the full library is checked, because one of its sources
13358 needs to be recompiled.
13359
13360 For instance, assume the project file @code{A} imports the library project file
13361 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
13362 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
13363 @file{l2.ads}, @file{l2.adb}.
13364
13365 If @file{l1.adb} has been modified, then the library associated with @code{L}
13366 will be rebuilt when compiling all the immediate sources of @code{A} only
13367 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
13368 @code{"with L1;"}.
13369
13370 To be sure that all the sources in the library associated with @code{L} are
13371 up to date, and that all the sources of project @code{A} are also up to date,
13372 the following two commands needs to be used:
13373
13374 @smallexample
13375 gnatmake -Pl.gpr
13376 gnatmake -Pa.gpr
13377 @end smallexample
13378
13379 When a library is built or rebuilt, an attempt is made first to delete all
13380 files in the library directory.
13381 All @file{ALI} files will also be copied from the object directory to the
13382 library directory. To build executables, @command{gnatmake} will use the
13383 library rather than the individual object files.
13384
13385 @ifclear vms
13386 It is also possible to create library project files for third-party libraries
13387 that are precompiled and cannot be compiled locally thanks to the
13388 @code{externally_built} attribute. (See @ref{Installing a library}).
13389 @end ifclear
13390
13391 @c *******************************
13392 @c * Stand-alone Library Projects *
13393 @c *******************************
13394
13395 @node Stand-alone Library Projects
13396 @section Stand-alone Library Projects
13397
13398 @noindent
13399 A Stand-alone Library is a library that contains the necessary code to
13400 elaborate the Ada units that are included in the library. A Stand-alone
13401 Library is suitable to be used in an executable when the main is not
13402 in Ada. However, Stand-alone Libraries may also be used with an Ada main
13403 subprogram.
13404
13405 A Stand-alone Library Project is a Library Project where the library is
13406 a Stand-alone Library.
13407
13408 To be a Stand-alone Library Project, in addition to the two attributes
13409 that make a project a Library Project (@code{Library_Name} and
13410 @code{Library_Dir}, see @ref{Library Projects}), the attribute
13411 @code{Library_Interface} must be defined.
13412
13413 @smallexample @c projectfile
13414 @group
13415    for Library_Dir use "lib_dir";
13416    for Library_Name use "dummy";
13417    for Library_Interface use ("int1", "int1.child");
13418 @end group
13419 @end smallexample
13420
13421 Attribute @code{Library_Interface} has a nonempty string list value,
13422 each string in the list designating a unit contained in an immediate source
13423 of the project file.
13424
13425 When a Stand-alone Library is built, first the binder is invoked to build
13426 a package whose name depends on the library name
13427 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
13428 This binder-generated package includes initialization and
13429 finalization procedures whose
13430 names depend on the library name (dummyinit and dummyfinal in the example
13431 above). The object corresponding to this package is included in the library.
13432
13433 A dynamic or relocatable Stand-alone Library is automatically initialized
13434 if automatic initialization of Stand-alone Libraries is supported on the
13435 platform and if attribute @code{Library_Auto_Init} is not specified or
13436 is specified with the value "true". A static Stand-alone Library is never
13437 automatically initialized.
13438
13439 Single string attribute @code{Library_Auto_Init} may be specified with only
13440 two possible values: "false" or "true" (case-insensitive). Specifying
13441 "false" for attribute @code{Library_Auto_Init} will prevent automatic
13442 initialization of dynamic or relocatable libraries.
13443
13444 When a non-automatically initialized Stand-alone Library is used
13445 in an executable, its initialization procedure must be called before
13446 any service of the library is used.
13447 When the main subprogram is in Ada, it may mean that the initialization
13448 procedure has to be called during elaboration of another package.
13449
13450 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
13451 (those that are listed in attribute @code{Library_Interface}) are copied to
13452 the Library Directory. As a consequence, only the Interface Units may be
13453 imported from Ada units outside of the library. If other units are imported,
13454 the binding phase will fail.
13455
13456 When a Stand-Alone Library is bound, the switches that are specified in
13457 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
13458 used in the call to @command{gnatbind}.
13459
13460 The string list attribute @code{Library_Options} may be used to specified
13461 additional switches to the call to @command{gcc} to link the library.
13462
13463 The attribute @code{Library_Src_Dir}, may be specified for a
13464 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
13465 single string value. Its value must be the path (absolute or relative to the
13466 project directory) of an existing directory. This directory cannot be the
13467 object directory or one of the source directories, but it can be the same as
13468 the library directory. The sources of the Interface
13469 Units of the library, necessary to an Ada client of the library, will be
13470 copied to the designated directory, called Interface Copy directory.
13471 These sources includes the specs of the Interface Units, but they may also
13472 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
13473 are used, or when there is a generic units in the spec. Before the sources
13474 are copied to the Interface Copy directory, an attempt is made to delete all
13475 files in the Interface Copy directory.
13476
13477 @c *************************************
13478 @c * Switches Related to Project Files *
13479 @c *************************************
13480 @node Switches Related to Project Files
13481 @section Switches Related to Project Files
13482
13483 @noindent
13484 The following switches are used by GNAT tools that support project files:
13485
13486 @table @option
13487
13488 @item ^-P^/PROJECT_FILE=^@var{project}
13489 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
13490 Indicates the name of a project file. This project file will be parsed with
13491 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
13492 if any, and using the external references indicated
13493 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
13494 @ifclear vms
13495 There may zero, one or more spaces between @option{-P} and @var{project}.
13496 @end ifclear
13497
13498 @noindent
13499 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
13500
13501 @noindent
13502 Since the Project Manager parses the project file only after all the switches
13503 on the command line are checked, the order of the switches
13504 @option{^-P^/PROJECT_FILE^},
13505 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
13506 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
13507
13508 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
13509 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
13510 Indicates that external variable @var{name} has the value @var{value}.
13511 The Project Manager will use this value for occurrences of
13512 @code{external(name)} when parsing the project file.
13513
13514 @ifclear vms
13515 @noindent
13516 If @var{name} or @var{value} includes a space, then @var{name=value} should be
13517 put between quotes.
13518 @smallexample
13519   -XOS=NT
13520   -X"user=John Doe"
13521 @end smallexample
13522 @end ifclear
13523
13524 @noindent
13525 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
13526 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
13527 @var{name}, only the last one is used.
13528
13529 @noindent
13530 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
13531 takes precedence over the value of the same name in the environment.
13532
13533 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
13534 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
13535 @c Previous line uses code vs option command, to stay less than 80 chars
13536 Indicates the verbosity of the parsing of GNAT project files.
13537
13538 @ifclear vms
13539 @option{-vP0} means Default;
13540 @option{-vP1} means Medium;
13541 @option{-vP2} means High.
13542 @end ifclear
13543
13544 @ifset vms
13545 There are three possible options for this qualifier: DEFAULT, MEDIUM and
13546 HIGH.
13547 @end ifset
13548
13549 @noindent
13550 The default is ^Default^DEFAULT^: no output for syntactically correct
13551 project files.
13552 @noindent
13553 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
13554 only the last one is used.
13555
13556 @end table
13557
13558 @c **********************************
13559 @c * Tools Supporting Project Files *
13560 @c **********************************
13561
13562 @node  Tools Supporting Project Files
13563 @section Tools Supporting Project Files
13564
13565 @menu
13566 * gnatmake and Project Files::
13567 * The GNAT Driver and Project Files::
13568 @end menu
13569
13570 @node gnatmake and Project Files
13571 @subsection gnatmake and Project Files
13572
13573 @noindent
13574 This section covers several topics related to @command{gnatmake} and
13575 project files: defining ^switches^switches^ for @command{gnatmake}
13576 and for the tools that it invokes; specifying configuration pragmas;
13577 the use of the @code{Main} attribute; building and rebuilding library project
13578 files.
13579
13580 @menu
13581 * ^Switches^Switches^ and Project Files::
13582 * Specifying Configuration Pragmas::
13583 * Project Files and Main Subprograms::
13584 * Library Project Files::
13585 @end menu
13586
13587 @node ^Switches^Switches^ and Project Files
13588 @subsubsection ^Switches^Switches^ and Project Files
13589
13590 @ifset vms
13591 It is not currently possible to specify VMS style qualifiers in the project
13592 files; only Unix style ^switches^switches^ may be specified.
13593 @end ifset
13594
13595 @noindent
13596 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
13597 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
13598 attribute, a @code{^Switches^Switches^} attribute, or both;
13599 as their names imply, these ^switch^switch^-related
13600 attributes affect the ^switches^switches^ that are used for each of these GNAT
13601 components when
13602 @command{gnatmake} is invoked.  As will be explained below, these
13603 component-specific ^switches^switches^ precede
13604 the ^switches^switches^ provided on the @command{gnatmake} command line.
13605
13606 The @code{^Default_Switches^Default_Switches^} attribute is an associative
13607 array indexed by language name (case insensitive) whose value is a string list.
13608 For example:
13609
13610 @smallexample @c projectfile
13611 @group
13612 package Compiler is
13613   for ^Default_Switches^Default_Switches^ ("Ada")
13614       use ("^-gnaty^-gnaty^",
13615            "^-v^-v^");
13616 end Compiler;
13617 @end group
13618 @end smallexample
13619
13620 @noindent
13621 The @code{^Switches^Switches^} attribute is also an associative array,
13622 indexed by a file name (which may or may not be case sensitive, depending
13623 on the operating system) whose value is a string list.  For example:
13624
13625 @smallexample @c projectfile
13626 @group
13627 package Builder is
13628    for ^Switches^Switches^ ("main1.adb")
13629        use ("^-O2^-O2^");
13630    for ^Switches^Switches^ ("main2.adb")
13631        use ("^-g^-g^");
13632 end Builder;
13633 @end group
13634 @end smallexample
13635
13636 @noindent
13637 For the @code{Builder} package, the file names must designate source files
13638 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
13639 file names must designate @file{ALI} or source files for main subprograms.
13640 In each case just the file name without an explicit extension is acceptable.
13641
13642 For each tool used in a program build (@command{gnatmake}, the compiler, the
13643 binder, and the linker), the corresponding package @dfn{contributes} a set of
13644 ^switches^switches^ for each file on which the tool is invoked, based on the
13645 ^switch^switch^-related attributes defined in the package.
13646 In particular, the ^switches^switches^
13647 that each of these packages contributes for a given file @var{f} comprise:
13648
13649 @itemize @bullet
13650 @item
13651 the value of attribute @code{^Switches^Switches^ (@var{f})},
13652 if it is specified in the package for the given file,
13653 @item
13654 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
13655 if it is specified in the package.
13656 @end itemize
13657
13658 @noindent
13659 If neither of these attributes is defined in the package, then the package does
13660 not contribute any ^switches^switches^ for the given file.
13661
13662 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
13663 two sets, in the following order: those contributed for the file
13664 by the @code{Builder} package;
13665 and the switches passed on the command line.
13666
13667 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
13668 the ^switches^switches^ passed to the tool comprise three sets,
13669 in the following order:
13670
13671 @enumerate
13672 @item
13673 the applicable ^switches^switches^ contributed for the file
13674 by the @code{Builder} package in the project file supplied on the command line;
13675
13676 @item
13677 those contributed for the file by the package (in the relevant project file --
13678 see below) corresponding to the tool; and
13679
13680 @item
13681 the applicable switches passed on the command line.
13682 @end enumerate
13683
13684 @noindent
13685 The term @emph{applicable ^switches^switches^} reflects the fact that
13686 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
13687 tools, depending on the individual ^switch^switch^.
13688
13689 @command{gnatmake} may invoke the compiler on source files from different
13690 projects. The Project Manager will use the appropriate project file to
13691 determine the @code{Compiler} package for each source file being compiled.
13692 Likewise for the @code{Binder} and @code{Linker} packages.
13693
13694 As an example, consider the following package in a project file:
13695
13696 @smallexample @c projectfile
13697 @group
13698 project Proj1 is
13699    package Compiler is
13700       for ^Default_Switches^Default_Switches^ ("Ada")
13701           use ("^-g^-g^");
13702       for ^Switches^Switches^ ("a.adb")
13703           use ("^-O1^-O1^");
13704       for ^Switches^Switches^ ("b.adb")
13705           use ("^-O2^-O2^",
13706                "^-gnaty^-gnaty^");
13707    end Compiler;
13708 end Proj1;
13709 @end group
13710 @end smallexample
13711
13712 @noindent
13713 If @command{gnatmake} is invoked with this project file, and it needs to
13714 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
13715 @file{a.adb} will be compiled with the ^switch^switch^
13716 @option{^-O1^-O1^},
13717 @file{b.adb} with ^switches^switches^
13718 @option{^-O2^-O2^}
13719 and @option{^-gnaty^-gnaty^},
13720 and @file{c.adb} with @option{^-g^-g^}.
13721
13722 The following example illustrates the ordering of the ^switches^switches^
13723 contributed by different packages:
13724
13725 @smallexample @c projectfile
13726 @group
13727 project Proj2 is
13728    package Builder is
13729       for ^Switches^Switches^ ("main.adb")
13730           use ("^-g^-g^",
13731                "^-O1^-)1^",
13732                "^-f^-f^");
13733    end Builder;
13734 @end group
13735
13736 @group
13737    package Compiler is
13738       for ^Switches^Switches^ ("main.adb")
13739           use ("^-O2^-O2^");
13740    end Compiler;
13741 end Proj2;
13742 @end group
13743 @end smallexample
13744
13745 @noindent
13746 If you issue the command:
13747
13748 @smallexample
13749     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
13750 @end smallexample
13751
13752 @noindent
13753 then the compiler will be invoked on @file{main.adb} with the following
13754 sequence of ^switches^switches^
13755
13756 @smallexample
13757    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
13758 @end smallexample
13759
13760 with the last @option{^-O^-O^}
13761 ^switch^switch^ having precedence over the earlier ones;
13762 several other ^switches^switches^
13763 (such as @option{^-c^-c^}) are added implicitly.
13764
13765 The ^switches^switches^
13766 @option{^-g^-g^}
13767 and @option{^-O1^-O1^} are contributed by package
13768 @code{Builder},  @option{^-O2^-O2^} is contributed
13769 by the package @code{Compiler}
13770 and @option{^-O0^-O0^} comes from the command line.
13771
13772 The @option{^-g^-g^}
13773 ^switch^switch^ will also be passed in the invocation of
13774 @command{Gnatlink.}
13775
13776 A final example illustrates switch contributions from packages in different
13777 project files:
13778
13779 @smallexample @c projectfile
13780 @group
13781 project Proj3 is
13782    for Source_Files use ("pack.ads", "pack.adb");
13783    package Compiler is
13784       for ^Default_Switches^Default_Switches^ ("Ada")
13785           use ("^-gnata^-gnata^");
13786    end Compiler;
13787 end Proj3;
13788 @end group
13789
13790 @group
13791 with "Proj3";
13792 project Proj4 is
13793    for Source_Files use ("foo_main.adb", "bar_main.adb");
13794    package Builder is
13795       for ^Switches^Switches^ ("foo_main.adb")
13796           use ("^-s^-s^",
13797                "^-g^-g^");
13798    end Builder;
13799 end Proj4;
13800 @end group
13801
13802 @group
13803 -- Ada source file:
13804 with Pack;
13805 procedure Foo_Main is
13806    @dots{}
13807 end Foo_Main;
13808 @end group
13809 @end smallexample
13810
13811 If the command is
13812 @smallexample
13813 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13814 @end smallexample
13815
13816 @noindent
13817 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13818 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13819 @option{^-gnato^-gnato^} (passed on the command line).
13820 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13821 are @option{^-g^-g^} from @code{Proj4.Builder},
13822 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13823 and @option{^-gnato^-gnato^} from the command line.
13824
13825 @noindent
13826 When using @command{gnatmake} with project files, some ^switches^switches^ or
13827 arguments may be expressed as relative paths. As the working directory where
13828 compilation occurs may change, these relative paths are converted to absolute
13829 paths. For the ^switches^switches^ found in a project file, the relative paths
13830 are relative to the project file directory, for the switches on the command
13831 line, they are relative to the directory where @command{gnatmake} is invoked.
13832 The ^switches^switches^ for which this occurs are:
13833 ^-I^-I^,
13834 ^-A^-A^,
13835 ^-L^-L^,
13836 ^-aO^-aO^,
13837 ^-aL^-aL^,
13838 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13839 ^switch^switch^
13840 ^-o^-o^, object files specified in package @code{Linker} or after
13841 -largs on the command line). The exception to this rule is the ^switch^switch^
13842 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13843
13844 @node Specifying Configuration Pragmas
13845 @subsubsection Specifying Configuration Pragmas
13846
13847 When using @command{gnatmake} with project files, if there exists a file
13848 @file{gnat.adc} that contains configuration pragmas, this file will be
13849 ignored.
13850
13851 Configuration pragmas can be defined by means of the following attributes in
13852 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13853 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13854
13855 Both these attributes are single string attributes. Their values is the path
13856 name of a file containing configuration pragmas. If a path name is relative,
13857 then it is relative to the project directory of the project file where the
13858 attribute is defined.
13859
13860 When compiling a source, the configuration pragmas used are, in order,
13861 those listed in the file designated by attribute
13862 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13863 project file, if it is specified, and those listed in the file designated by
13864 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13865 the project file of the source, if it exists.
13866
13867 @node Project Files and Main Subprograms
13868 @subsubsection Project Files and Main Subprograms
13869
13870 @noindent
13871 When using a project file, you can invoke @command{gnatmake}
13872 with one or several main subprograms, by specifying their source files on the
13873 command line.
13874
13875 @smallexample
13876     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13877 @end smallexample
13878
13879 @noindent
13880 Each of these needs to be a source file of the same project, except
13881 when the switch ^-u^/UNIQUE^ is used.
13882
13883 @noindent
13884 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13885 same project, one of the project in the tree rooted at the project specified
13886 on the command line. The package @code{Builder} of this common project, the
13887 "main project" is the one that is considered by @command{gnatmake}.
13888
13889 @noindent
13890 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13891 imported directly or indirectly by the project specified on the command line.
13892 Note that if such a source file is not part of the project specified on the
13893 command line, the ^switches^switches^ found in package @code{Builder} of the
13894 project specified on the command line, if any, that are transmitted
13895 to the compiler will still be used, not those found in the project file of
13896 the source file.
13897
13898 @noindent
13899 When using a project file, you can also invoke @command{gnatmake} without
13900 explicitly specifying any main, and the effect depends on whether you have
13901 defined the @code{Main} attribute.  This attribute has a string list value,
13902 where each element in the list is the name of a source file (the file
13903 extension is optional) that contains a unit that can be a main subprogram.
13904
13905 If the @code{Main} attribute is defined in a project file as a non-empty
13906 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13907 line, then invoking @command{gnatmake} with this project file but without any
13908 main on the command line is equivalent to invoking @command{gnatmake} with all
13909 the file names in the @code{Main} attribute on the command line.
13910
13911 Example:
13912 @smallexample @c projectfile
13913 @group
13914    project Prj is
13915       for Main use ("main1", "main2", "main3");
13916    end Prj;
13917 @end group
13918 @end smallexample
13919
13920 @noindent
13921 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13922 is equivalent to
13923 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13924
13925 When the project attribute @code{Main} is not specified, or is specified
13926 as an empty string list, or when the switch @option{-u} is used on the command
13927 line, then invoking @command{gnatmake} with no main on the command line will
13928 result in all immediate sources of the project file being checked, and
13929 potentially recompiled. Depending on the presence of the switch @option{-u},
13930 sources from other project files on which the immediate sources of the main
13931 project file depend are also checked and potentially recompiled. In other
13932 words, the @option{-u} switch is applied to all of the immediate sources of the
13933 main project file.
13934
13935 When no main is specified on the command line and attribute @code{Main} exists
13936 and includes several mains, or when several mains are specified on the
13937 command line, the default ^switches^switches^ in package @code{Builder} will
13938 be used for all mains, even if there are specific ^switches^switches^
13939 specified for one or several mains.
13940
13941 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13942 the specific ^switches^switches^ for each main, if they are specified.
13943
13944 @node Library Project Files
13945 @subsubsection Library Project Files
13946
13947 @noindent
13948 When @command{gnatmake} is invoked with a main project file that is a library
13949 project file, it is not allowed to specify one or more mains on the command
13950 line.
13951
13952 @noindent
13953 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13954 ^-l^/ACTION=LINK^ have special meanings.
13955
13956 @itemize @bullet
13957 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13958 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13959 library.
13960
13961 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13962 to @command{gnatmake} that the binder generated file should be compiled
13963 (in the case of a stand-alone library) and that the library should be built.
13964
13965 @end itemize
13966
13967 @node The GNAT Driver and Project Files
13968 @subsection The GNAT Driver and Project Files
13969
13970 @noindent
13971 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13972 can benefit from project files:
13973 @command{^gnatbind^gnatbind^},
13974 @command{^gnatcheck^gnatcheck^}),
13975 @command{^gnatclean^gnatclean^}),
13976 @command{^gnatelim^gnatelim^},
13977 @command{^gnatfind^gnatfind^},
13978 @command{^gnatlink^gnatlink^},
13979 @command{^gnatls^gnatls^},
13980 @command{^gnatmetric^gnatmetric^},
13981 @command{^gnatpp^gnatpp^},
13982 @command{^gnatstub^gnatstub^},
13983 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13984 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13985 They must be invoked through the @command{gnat} driver.
13986
13987 The @command{gnat} driver is a wrapper that accepts a number of commands and
13988 calls the corresponding tool. It was designed initially for VMS platforms (to
13989 convert VMS qualifiers to Unix-style switches), but it is now available on all
13990 GNAT platforms.
13991
13992 On non-VMS platforms, the @command{gnat} driver accepts the following commands
13993 (case insensitive):
13994
13995 @itemize @bullet
13996 @item
13997 BIND to invoke @command{^gnatbind^gnatbind^}
13998 @item
13999 CHOP to invoke @command{^gnatchop^gnatchop^}
14000 @item
14001 CLEAN to invoke @command{^gnatclean^gnatclean^}
14002 @item
14003 COMP or COMPILE to invoke the compiler
14004 @item
14005 ELIM to invoke @command{^gnatelim^gnatelim^}
14006 @item
14007 FIND to invoke @command{^gnatfind^gnatfind^}
14008 @item
14009 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14010 @item
14011 LINK to invoke @command{^gnatlink^gnatlink^}
14012 @item
14013 LS or LIST to invoke @command{^gnatls^gnatls^}
14014 @item
14015 MAKE to invoke @command{^gnatmake^gnatmake^}
14016 @item
14017 NAME to invoke @command{^gnatname^gnatname^}
14018 @item
14019 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14020 @item
14021 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14022 @item
14023 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14024 @item
14025 STUB to invoke @command{^gnatstub^gnatstub^}
14026 @item
14027 XREF to invoke @command{^gnatxref^gnatxref^}
14028 @end itemize
14029
14030 @noindent
14031 (note that the compiler is invoked using the command
14032 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14033
14034 @noindent
14035 On non-VMS platforms, between @command{gnat} and the command, two
14036 special switches may be used:
14037
14038 @itemize @bullet
14039 @item
14040 @command{-v} to display the invocation of the tool.
14041 @item
14042 @command{-dn} to prevent the @command{gnat} driver from removing
14043 the temporary files it has created. These temporary files are
14044 configuration files and temporary file list files.
14045 @end itemize
14046
14047 @noindent
14048 The command may be followed by switches and arguments for the invoked
14049 tool.
14050
14051 @smallexample
14052   gnat bind -C main.ali
14053   gnat ls -a main
14054   gnat chop foo.txt
14055 @end smallexample
14056
14057 @noindent
14058 Switches may also be put in text files, one switch per line, and the text
14059 files may be specified with their path name preceded by '@@'.
14060
14061 @smallexample
14062    gnat bind @@args.txt main.ali
14063 @end smallexample
14064
14065 @noindent
14066 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14067 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14068 (@option{^-P^/PROJECT_FILE^},
14069 @option{^-X^/EXTERNAL_REFERENCE^} and
14070 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14071 the switches of the invoking tool.
14072
14073 @noindent
14074 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14075 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14076 the immediate sources of the specified project file.
14077
14078 @noindent
14079 When GNAT METRIC is used with a project file, but with no source
14080 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14081 with all the immediate sources of the specified project file and with
14082 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14083 of the project.
14084
14085 @noindent
14086 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14087 a project file, no source is specified on the command line and
14088 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14089 the underlying tool (^gnatpp^gnatpp^ or
14090 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14091 not only for the immediate sources of the main project.
14092 @ifclear vms
14093 (-U stands for Universal or Union of the project files of the project tree)
14094 @end ifclear
14095
14096 @noindent
14097 For each of the following commands, there is optionally a corresponding
14098 package in the main project.
14099
14100 @itemize @bullet
14101 @item
14102 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14103
14104 @item
14105 package @code{Check} for command CHECK (invoking
14106 @code{^gnatcheck^gnatcheck^})
14107
14108 @item
14109 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14110
14111 @item
14112 package @code{Cross_Reference} for command XREF (invoking
14113 @code{^gnatxref^gnatxref^})
14114
14115 @item
14116 package @code{Eliminate} for command ELIM (invoking
14117 @code{^gnatelim^gnatelim^})
14118
14119 @item
14120 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14121
14122 @item
14123 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14124
14125 @item
14126 package @code{Gnatstub} for command STUB
14127 (invoking @code{^gnatstub^gnatstub^})
14128
14129 @item
14130 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14131
14132 @item
14133 package @code{Metrics} for command METRIC
14134 (invoking @code{^gnatmetric^gnatmetric^})
14135
14136 @item
14137 package @code{Pretty_Printer} for command PP or PRETTY
14138 (invoking @code{^gnatpp^gnatpp^})
14139
14140 @end itemize
14141
14142 @noindent
14143 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14144 a simple variable with a string list value. It contains ^switches^switches^
14145 for the invocation of @code{^gnatls^gnatls^}.
14146
14147 @smallexample @c projectfile
14148 @group
14149 project Proj1 is
14150    package gnatls is
14151       for ^Switches^Switches^
14152           use ("^-a^-a^",
14153                "^-v^-v^");
14154    end gnatls;
14155 end Proj1;
14156 @end group
14157 @end smallexample
14158
14159 @noindent
14160 All other packages have two attribute @code{^Switches^Switches^} and
14161 @code{^Default_Switches^Default_Switches^}.
14162
14163 @noindent
14164 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14165 source file name, that has a string list value: the ^switches^switches^ to be
14166 used when the tool corresponding to the package is invoked for the specific
14167 source file.
14168
14169 @noindent
14170 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14171 indexed by  the programming language that has a string list value.
14172 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14173 ^switches^switches^ for the invocation of the tool corresponding
14174 to the package, except if a specific @code{^Switches^Switches^} attribute
14175 is specified for the source file.
14176
14177 @smallexample @c projectfile
14178 @group
14179 project Proj is
14180
14181    for Source_Dirs use ("./**");
14182
14183    package gnatls is
14184       for ^Switches^Switches^ use
14185           ("^-a^-a^",
14186            "^-v^-v^");
14187    end gnatls;
14188 @end group
14189 @group
14190
14191    package Compiler is
14192       for ^Default_Switches^Default_Switches^ ("Ada")
14193           use ("^-gnatv^-gnatv^",
14194                "^-gnatwa^-gnatwa^");
14195    end Binder;
14196 @end group
14197 @group
14198
14199    package Binder is
14200       for ^Default_Switches^Default_Switches^ ("Ada")
14201           use ("^-C^-C^",
14202                "^-e^-e^");
14203    end Binder;
14204 @end group
14205 @group
14206
14207    package Linker is
14208       for ^Default_Switches^Default_Switches^ ("Ada")
14209           use ("^-C^-C^");
14210       for ^Switches^Switches^ ("main.adb")
14211           use ("^-C^-C^",
14212                "^-v^-v^",
14213                "^-v^-v^");
14214    end Linker;
14215 @end group
14216 @group
14217
14218    package Finder is
14219       for ^Default_Switches^Default_Switches^ ("Ada")
14220            use ("^-a^-a^",
14221                 "^-f^-f^");
14222    end Finder;
14223 @end group
14224 @group
14225
14226    package Cross_Reference is
14227       for ^Default_Switches^Default_Switches^ ("Ada")
14228           use ("^-a^-a^",
14229                "^-f^-f^",
14230                "^-d^-d^",
14231                "^-u^-u^");
14232    end Cross_Reference;
14233 end Proj;
14234 @end group
14235 @end smallexample
14236
14237 @noindent
14238 With the above project file, commands such as
14239
14240 @smallexample
14241    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
14242    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
14243    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
14244    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
14245    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
14246 @end smallexample
14247
14248 @noindent
14249 will set up the environment properly and invoke the tool with the switches
14250 found in the package corresponding to the tool:
14251 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
14252 except @code{^Switches^Switches^ ("main.adb")}
14253 for @code{^gnatlink^gnatlink^}.
14254 It is also possible to invoke some of the tools,
14255 @code{^gnatcheck^gnatcheck^}),
14256 @code{^gnatmetric^gnatmetric^}),
14257 and @code{^gnatpp^gnatpp^})
14258 on a set of project units thanks to the combination of the switches
14259 @option{-P}, @option{-U} and possibly the main unit when one is interested
14260 in its closure. For instance,
14261 @smallexample
14262 gnat metric -Pproj
14263 @end smallexample
14264 will compute the metrics for all the immediate units of project
14265 @code{proj}.
14266 @smallexample
14267 gnat metric -Pproj -U
14268 @end smallexample
14269 will compute the metrics for all the units of the closure of projects
14270 rooted at @code{proj}.
14271 @smallexample
14272 gnat metric -Pproj -U main_unit
14273 @end smallexample
14274 will compute the metrics for the closure of units rooted at
14275 @code{main_unit}. This last possibility relies implicitly
14276 on @command{gnatbind}'s option @option{-R}.
14277
14278 @c **********************
14279 @node An Extended Example
14280 @section An Extended Example
14281
14282 @noindent
14283 Suppose that we have two programs, @var{prog1} and @var{prog2},
14284 whose sources are in corresponding directories. We would like
14285 to build them with a single @command{gnatmake} command, and we want to place
14286 their object files into @file{build} subdirectories of the source directories.
14287 Furthermore, we want to have to have two separate subdirectories
14288 in @file{build}  -- @file{release} and @file{debug} -- which will contain
14289 the object files compiled with different set of compilation flags.
14290
14291 In other words, we have the following structure:
14292
14293 @smallexample
14294 @group
14295    main
14296      |- prog1
14297      |    |- build
14298      |         | debug
14299      |         | release
14300      |- prog2
14301           |- build
14302                | debug
14303                | release
14304 @end group
14305 @end smallexample
14306
14307 @noindent
14308 Here are the project files that we must place in a directory @file{main}
14309 to maintain this structure:
14310
14311 @enumerate
14312
14313 @item We create a @code{Common} project with a package @code{Compiler} that
14314 specifies the compilation ^switches^switches^:
14315
14316 @smallexample
14317 File "common.gpr":
14318 @group
14319 @b{project} Common @b{is}
14320
14321    @b{for} Source_Dirs @b{use} (); -- No source files
14322 @end group
14323
14324 @group
14325    @b{type} Build_Type @b{is} ("release", "debug");
14326    Build : Build_Type := External ("BUILD", "debug");
14327 @end group
14328 @group
14329    @b{package} Compiler @b{is}
14330       @b{case} Build @b{is}
14331          @b{when} "release" =>
14332            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14333                    @b{use} ("^-O2^-O2^");
14334          @b{when} "debug"   =>
14335            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14336                    @b{use} ("^-g^-g^");
14337       @b{end case};
14338    @b{end} Compiler;
14339
14340 @b{end} Common;
14341 @end group
14342 @end smallexample
14343
14344 @item We create separate projects for the two programs:
14345
14346 @smallexample
14347 @group
14348 File "prog1.gpr":
14349
14350 @b{with} "common";
14351 @b{project} Prog1 @b{is}
14352
14353     @b{for} Source_Dirs @b{use} ("prog1");
14354     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
14355
14356     @b{package} Compiler @b{renames} Common.Compiler;
14357
14358 @b{end} Prog1;
14359 @end group
14360 @end smallexample
14361
14362 @smallexample
14363 @group
14364 File "prog2.gpr":
14365
14366 @b{with} "common";
14367 @b{project} Prog2 @b{is}
14368
14369     @b{for} Source_Dirs @b{use} ("prog2");
14370     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
14371
14372     @b{package} Compiler @b{renames} Common.Compiler;
14373
14374 @end group
14375 @b{end} Prog2;
14376 @end smallexample
14377
14378 @item We create a wrapping project @code{Main}:
14379
14380 @smallexample
14381 @group
14382 File "main.gpr":
14383
14384 @b{with} "common";
14385 @b{with} "prog1";
14386 @b{with} "prog2";
14387 @b{project} Main @b{is}
14388
14389    @b{package} Compiler @b{renames} Common.Compiler;
14390
14391 @b{end} Main;
14392 @end group
14393 @end smallexample
14394
14395 @item Finally we need to create a dummy procedure that @code{with}s (either
14396 explicitly or implicitly) all the sources of our two programs.
14397
14398 @end enumerate
14399
14400 @noindent
14401 Now we can build the programs using the command
14402
14403 @smallexample
14404    gnatmake ^-P^/PROJECT_FILE=^main dummy
14405 @end smallexample
14406
14407 @noindent
14408 for the Debug mode, or
14409
14410 @ifclear vms
14411 @smallexample
14412    gnatmake -Pmain -XBUILD=release
14413 @end smallexample
14414 @end ifclear
14415
14416 @ifset vms
14417 @smallexample
14418    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
14419 @end smallexample
14420 @end ifset
14421
14422 @noindent
14423 for the Release mode.
14424
14425 @c ********************************
14426 @c * Project File Complete Syntax *
14427 @c ********************************
14428
14429 @node Project File Complete Syntax
14430 @section Project File Complete Syntax
14431
14432 @smallexample
14433 project ::=
14434   context_clause project_declaration
14435
14436 context_clause ::=
14437   @{with_clause@}
14438
14439 with_clause ::=
14440   @b{with} path_name @{ , path_name @} ;
14441
14442 path_name ::=
14443    string_literal
14444
14445 project_declaration ::=
14446   simple_project_declaration | project_extension
14447
14448 simple_project_declaration ::=
14449   @b{project} <project_>simple_name @b{is}
14450     @{declarative_item@}
14451   @b{end} <project_>simple_name;
14452
14453 project_extension ::=
14454   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
14455     @{declarative_item@}
14456   @b{end} <project_>simple_name;
14457
14458 declarative_item ::=
14459   package_declaration |
14460   typed_string_declaration |
14461   other_declarative_item
14462
14463 package_declaration ::=
14464   package_specification | package_renaming
14465
14466 package_specification ::=
14467   @b{package} package_identifier @b{is}
14468     @{simple_declarative_item@}
14469   @b{end} package_identifier ;
14470
14471 package_identifier ::=
14472   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
14473   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
14474   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
14475
14476 package_renaming ::==
14477   @b{package} package_identifier @b{renames}
14478        <project_>simple_name.package_identifier ;
14479
14480 typed_string_declaration ::=
14481   @b{type} <typed_string_>_simple_name @b{is}
14482    ( string_literal @{, string_literal@} );
14483
14484 other_declarative_item ::=
14485   attribute_declaration |
14486   typed_variable_declaration |
14487   variable_declaration |
14488   case_construction
14489
14490 attribute_declaration ::=
14491   full_associative_array_declaration |
14492   @b{for} attribute_designator @b{use} expression ;
14493
14494 full_associative_array_declaration ::=
14495   @b{for} <associative_array_attribute_>simple_name @b{use}
14496   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
14497
14498 attribute_designator ::=
14499   <simple_attribute_>simple_name |
14500   <associative_array_attribute_>simple_name ( string_literal )
14501
14502 typed_variable_declaration ::=
14503   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
14504
14505 variable_declaration ::=
14506   <variable_>simple_name := expression;
14507
14508 expression ::=
14509   term @{& term@}
14510
14511 term ::=
14512   literal_string |
14513   string_list |
14514   <variable_>name |
14515   external_value |
14516   attribute_reference
14517
14518 string_literal ::=
14519   (same as Ada)
14520
14521 string_list ::=
14522   ( <string_>expression @{ , <string_>expression @} )
14523
14524 external_value ::=
14525   @b{external} ( string_literal [, string_literal] )
14526
14527 attribute_reference ::=
14528   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
14529
14530 attribute_prefix ::=
14531   @b{project} |
14532   <project_>simple_name | package_identifier |
14533   <project_>simple_name . package_identifier
14534
14535 case_construction ::=
14536   @b{case} <typed_variable_>name @b{is}
14537     @{case_item@}
14538   @b{end case} ;
14539
14540 case_item ::=
14541   @b{when} discrete_choice_list =>
14542       @{case_construction | attribute_declaration@}
14543
14544 discrete_choice_list ::=
14545   string_literal @{| string_literal@} |
14546   @b{others}
14547
14548 name ::=
14549   simple_name @{. simple_name@}
14550
14551 simple_name ::=
14552   identifier (same as Ada)
14553
14554 @end smallexample
14555
14556 @node The Cross-Referencing Tools gnatxref and gnatfind
14557 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
14558 @findex gnatxref
14559 @findex gnatfind
14560
14561 @noindent
14562 The compiler generates cross-referencing information (unless
14563 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
14564 This information indicates where in the source each entity is declared and
14565 referenced. Note that entities in package Standard are not included, but
14566 entities in all other predefined units are included in the output.
14567
14568 Before using any of these two tools, you need to compile successfully your
14569 application, so that GNAT gets a chance to generate the cross-referencing
14570 information.
14571
14572 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
14573 information to provide the user with the capability to easily locate the
14574 declaration and references to an entity. These tools are quite similar,
14575 the difference being that @code{gnatfind} is intended for locating
14576 definitions and/or references to a specified entity or entities, whereas
14577 @code{gnatxref} is oriented to generating a full report of all
14578 cross-references.
14579
14580 To use these tools, you must not compile your application using the
14581 @option{-gnatx} switch on the @command{gnatmake} command line
14582 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
14583 information will not be generated.
14584
14585 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
14586 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14587
14588 @menu
14589 * gnatxref Switches::
14590 * gnatfind Switches::
14591 * Project Files for gnatxref and gnatfind::
14592 * Regular Expressions in gnatfind and gnatxref::
14593 * Examples of gnatxref Usage::
14594 * Examples of gnatfind Usage::
14595 @end menu
14596
14597 @node gnatxref Switches
14598 @section @code{gnatxref} Switches
14599
14600 @noindent
14601 The command invocation for @code{gnatxref} is:
14602 @smallexample
14603 $ gnatxref [switches] sourcefile1 [sourcefile2 @dots{}]
14604 @end smallexample
14605
14606 @noindent
14607 where
14608
14609 @table @code
14610 @item sourcefile1, sourcefile2
14611 identifies the source files for which a report is to be generated. The
14612 ``with''ed units will be processed too. You must provide at least one file.
14613
14614 These file names are considered to be regular expressions, so for instance
14615 specifying @file{source*.adb} is the same as giving every file in the current
14616 directory whose name starts with @file{source} and whose extension is
14617 @file{adb}.
14618
14619 You shouldn't specify any directory name, just base names. @command{gnatxref}
14620 and @command{gnatfind} will be able to locate these files by themselves using
14621 the source path. If you specify directories, no result is produced.
14622
14623 @end table
14624
14625 @noindent
14626 The switches can be:
14627 @table @option
14628 @c !sort!
14629 @item --version
14630 @cindex @option{--version} @command{gnatxref}
14631 Display Copyright and version, then exit disregarding all other options.
14632
14633 @item --help
14634 @cindex @option{--help} @command{gnatxref}
14635 If @option{--version} was not used, display usage, then exit disregarding
14636 all other options.
14637
14638 @item ^-a^/ALL_FILES^
14639 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
14640 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14641 the read-only files found in the library search path. Otherwise, these files
14642 will be ignored. This option can be used to protect Gnat sources or your own
14643 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14644 much faster, and their output much smaller. Read-only here refers to access
14645 or permissions status in the file system for the current user.
14646
14647 @item -aIDIR
14648 @cindex @option{-aIDIR} (@command{gnatxref})
14649 When looking for source files also look in directory DIR. The order in which
14650 source file search is undertaken is the same as for @command{gnatmake}.
14651
14652 @item -aODIR
14653 @cindex @option{-aODIR} (@command{gnatxref})
14654 When searching for library and object files, look in directory
14655 DIR. The order in which library files are searched is the same as for
14656 @command{gnatmake}.
14657
14658 @item -nostdinc
14659 @cindex @option{-nostdinc} (@command{gnatxref})
14660 Do not look for sources in the system default directory.
14661
14662 @item -nostdlib
14663 @cindex @option{-nostdlib} (@command{gnatxref})
14664 Do not look for library files in the system default directory.
14665
14666 @item --RTS=@var{rts-path}
14667 @cindex @option{--RTS} (@command{gnatxref})
14668 Specifies the default location of the runtime library. Same meaning as the
14669 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14670
14671 @item ^-d^/DERIVED_TYPES^
14672 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
14673 If this switch is set @code{gnatxref} will output the parent type
14674 reference for each matching derived types.
14675
14676 @item ^-f^/FULL_PATHNAME^
14677 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
14678 If this switch is set, the output file names will be preceded by their
14679 directory (if the file was found in the search path). If this switch is
14680 not set, the directory will not be printed.
14681
14682 @item ^-g^/IGNORE_LOCALS^
14683 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
14684 If this switch is set, information is output only for library-level
14685 entities, ignoring local entities. The use of this switch may accelerate
14686 @code{gnatfind} and @code{gnatxref}.
14687
14688 @item -IDIR
14689 @cindex @option{-IDIR} (@command{gnatxref})
14690 Equivalent to @samp{-aODIR -aIDIR}.
14691
14692 @item -pFILE
14693 @cindex @option{-pFILE} (@command{gnatxref})
14694 Specify a project file to use @xref{Project Files}.
14695 If you need to use the @file{.gpr}
14696 project files, you should use gnatxref through the GNAT driver
14697 (@command{gnat xref -Pproject}).
14698
14699 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14700 project file in the current directory.
14701
14702 If a project file is either specified or found by the tools, then the content
14703 of the source directory and object directory lines are added as if they
14704 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
14705 and @samp{^-aO^OBJECT_SEARCH^}.
14706 @item ^-u^/UNUSED^
14707 Output only unused symbols. This may be really useful if you give your
14708 main compilation unit on the command line, as @code{gnatxref} will then
14709 display every unused entity and 'with'ed package.
14710
14711 @ifclear vms
14712 @item -v
14713 Instead of producing the default output, @code{gnatxref} will generate a
14714 @file{tags} file that can be used by vi. For examples how to use this
14715 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
14716 to the standard output, thus you will have to redirect it to a file.
14717 @end ifclear
14718
14719 @end table
14720
14721 @noindent
14722 All these switches may be in any order on the command line, and may even
14723 appear after the file names. They need not be separated by spaces, thus
14724 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14725 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14726
14727 @node gnatfind Switches
14728 @section @code{gnatfind} Switches
14729
14730 @noindent
14731 The command line for @code{gnatfind} is:
14732
14733 @smallexample
14734 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
14735       [file1 file2 @dots{}]
14736 @end smallexample
14737
14738 @noindent
14739 where
14740
14741 @table @code
14742 @item pattern
14743 An entity will be output only if it matches the regular expression found
14744 in @samp{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
14745
14746 Omitting the pattern is equivalent to specifying @samp{*}, which
14747 will match any entity. Note that if you do not provide a pattern, you
14748 have to provide both a sourcefile and a line.
14749
14750 Entity names are given in Latin-1, with uppercase/lowercase equivalence
14751 for matching purposes. At the current time there is no support for
14752 8-bit codes other than Latin-1, or for wide characters in identifiers.
14753
14754 @item sourcefile
14755 @code{gnatfind} will look for references, bodies or declarations
14756 of symbols referenced in @file{sourcefile}, at line @samp{line}
14757 and column @samp{column}. See @ref{Examples of gnatfind Usage}
14758 for syntax examples.
14759
14760 @item line
14761 is a decimal integer identifying the line number containing
14762 the reference to the entity (or entities) to be located.
14763
14764 @item column
14765 is a decimal integer identifying the exact location on the
14766 line of the first character of the identifier for the
14767 entity reference. Columns are numbered from 1.
14768
14769 @item file1 file2 @dots{}
14770 The search will be restricted to these source files. If none are given, then
14771 the search will be done for every library file in the search path.
14772 These file must appear only after the pattern or sourcefile.
14773
14774 These file names are considered to be regular expressions, so for instance
14775 specifying @file{source*.adb} is the same as giving every file in the current
14776 directory whose name starts with @file{source} and whose extension is
14777 @file{adb}.
14778
14779 The location of the spec of the entity will always be displayed, even if it
14780 isn't in one of @file{file1}, @file{file2},@enddots{}  The occurrences
14781 of the entity in the separate units of the ones given on the command
14782 line will also be displayed.
14783
14784 Note that if you specify at least one file in this part, @code{gnatfind} may
14785 sometimes not be able to find the body of the subprograms.
14786
14787 @end table
14788
14789 @noindent
14790 At least one of 'sourcefile' or 'pattern' has to be present on
14791 the command line.
14792
14793 The following switches are available:
14794 @table @option
14795 @c !sort!
14796
14797 @cindex @option{--version} @command{gnatfind}
14798 Display Copyright and version, then exit disregarding all other options.
14799
14800 @item --help
14801 @cindex @option{--help} @command{gnatfind}
14802 If @option{--version} was not used, display usage, then exit disregarding
14803 all other options.
14804
14805 @item ^-a^/ALL_FILES^
14806 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
14807 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14808 the read-only files found in the library search path. Otherwise, these files
14809 will be ignored. This option can be used to protect Gnat sources or your own
14810 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14811 much faster, and their output much smaller. Read-only here refers to access
14812 or permission status in the file system for the current user.
14813
14814 @item -aIDIR
14815 @cindex @option{-aIDIR} (@command{gnatfind})
14816 When looking for source files also look in directory DIR. The order in which
14817 source file search is undertaken is the same as for @command{gnatmake}.
14818
14819 @item -aODIR
14820 @cindex @option{-aODIR} (@command{gnatfind})
14821 When searching for library and object files, look in directory
14822 DIR. The order in which library files are searched is the same as for
14823 @command{gnatmake}.
14824
14825 @item -nostdinc
14826 @cindex @option{-nostdinc} (@command{gnatfind})
14827 Do not look for sources in the system default directory.
14828
14829 @item -nostdlib
14830 @cindex @option{-nostdlib} (@command{gnatfind})
14831 Do not look for library files in the system default directory.
14832
14833 @item --RTS=@var{rts-path}
14834 @cindex @option{--RTS} (@command{gnatfind})
14835 Specifies the default location of the runtime library. Same meaning as the
14836 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14837
14838 @item ^-d^/DERIVED_TYPE_INFORMATION^
14839 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
14840 If this switch is set, then @code{gnatfind} will output the parent type
14841 reference for each matching derived types.
14842
14843 @item ^-e^/EXPRESSIONS^
14844 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
14845 By default, @code{gnatfind} accept the simple regular expression set for
14846 @samp{pattern}. If this switch is set, then the pattern will be
14847 considered as full Unix-style regular expression.
14848
14849 @item ^-f^/FULL_PATHNAME^
14850 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14851 If this switch is set, the output file names will be preceded by their
14852 directory (if the file was found in the search path). If this switch is
14853 not set, the directory will not be printed.
14854
14855 @item ^-g^/IGNORE_LOCALS^
14856 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14857 If this switch is set, information is output only for library-level
14858 entities, ignoring local entities. The use of this switch may accelerate
14859 @code{gnatfind} and @code{gnatxref}.
14860
14861 @item -IDIR
14862 @cindex @option{-IDIR} (@command{gnatfind})
14863 Equivalent to @samp{-aODIR -aIDIR}.
14864
14865 @item -pFILE
14866 @cindex @option{-pFILE} (@command{gnatfind})
14867 Specify a project file (@pxref{Project Files}) to use.
14868 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14869 project file in the current directory.
14870
14871 If a project file is either specified or found by the tools, then the content
14872 of the source directory and object directory lines are added as if they
14873 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14874 @samp{^-aO^/OBJECT_SEARCH^}.
14875
14876 @item ^-r^/REFERENCES^
14877 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14878 By default, @code{gnatfind} will output only the information about the
14879 declaration, body or type completion of the entities. If this switch is
14880 set, the @code{gnatfind} will locate every reference to the entities in
14881 the files specified on the command line (or in every file in the search
14882 path if no file is given on the command line).
14883
14884 @item ^-s^/PRINT_LINES^
14885 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14886 If this switch is set, then @code{gnatfind} will output the content
14887 of the Ada source file lines were the entity was found.
14888
14889 @item ^-t^/TYPE_HIERARCHY^
14890 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14891 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14892 the specified type. It act like -d option but recursively from parent
14893 type to parent type. When this switch is set it is not possible to
14894 specify more than one file.
14895
14896 @end table
14897
14898 @noindent
14899 All these switches may be in any order on the command line, and may even
14900 appear after the file names. They need not be separated by spaces, thus
14901 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14902 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14903
14904 As stated previously, gnatfind will search in every directory in the
14905 search path. You can force it to look only in the current directory if
14906 you specify @code{*} at the end of the command line.
14907
14908 @node Project Files for gnatxref and gnatfind
14909 @section Project Files for @command{gnatxref} and @command{gnatfind}
14910
14911 @noindent
14912 Project files allow a programmer to specify how to compile its
14913 application, where to find sources, etc.  These files are used
14914 @ifclear vms
14915 primarily by GPS, but they can also be used
14916 @end ifclear
14917 by the two tools
14918 @code{gnatxref} and @code{gnatfind}.
14919
14920 A project file name must end with @file{.gpr}. If a single one is
14921 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14922 extract the information from it. If multiple project files are found, none of
14923 them is read, and you have to use the @samp{-p} switch to specify the one
14924 you want to use.
14925
14926 The following lines can be included, even though most of them have default
14927 values which can be used in most cases.
14928 The lines can be entered in any order in the file.
14929 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14930 each line. If you have multiple instances, only the last one is taken into
14931 account.
14932
14933 @table @code
14934 @item src_dir=DIR
14935 [default: @code{"^./^[]^"}]
14936 specifies a directory where to look for source files. Multiple @code{src_dir}
14937 lines can be specified and they will be searched in the order they
14938 are specified.
14939
14940 @item obj_dir=DIR
14941 [default: @code{"^./^[]^"}]
14942 specifies a directory where to look for object and library files. Multiple
14943 @code{obj_dir} lines can be specified, and they will be searched in the order
14944 they are specified
14945
14946 @item comp_opt=SWITCHES
14947 [default: @code{""}]
14948 creates a variable which can be referred to subsequently by using
14949 the @code{$@{comp_opt@}} notation. This is intended to store the default
14950 switches given to @command{gnatmake} and @command{gcc}.
14951
14952 @item bind_opt=SWITCHES
14953 [default: @code{""}]
14954 creates a variable which can be referred to subsequently by using
14955 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14956 switches given to @command{gnatbind}.
14957
14958 @item link_opt=SWITCHES
14959 [default: @code{""}]
14960 creates a variable which can be referred to subsequently by using
14961 the @samp{$@{link_opt@}} notation. This is intended to store the default
14962 switches given to @command{gnatlink}.
14963
14964 @item main=EXECUTABLE
14965 [default: @code{""}]
14966 specifies the name of the executable for the application. This variable can
14967 be referred to in the following lines by using the @samp{$@{main@}} notation.
14968
14969 @ifset vms
14970 @item comp_cmd=COMMAND
14971 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14972 @end ifset
14973 @ifclear vms
14974 @item comp_cmd=COMMAND
14975 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14976 @end ifclear
14977 specifies the command used to compile a single file in the application.
14978
14979 @ifset vms
14980 @item make_cmd=COMMAND
14981 [default: @code{"GNAT MAKE $@{main@}
14982 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14983 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14984 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14985 @end ifset
14986 @ifclear vms
14987 @item make_cmd=COMMAND
14988 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14989  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14990  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14991 @end ifclear
14992 specifies the command used to recompile the whole application.
14993
14994 @item run_cmd=COMMAND
14995 [default: @code{"$@{main@}"}]
14996 specifies the command used to run the application.
14997
14998 @item debug_cmd=COMMAND
14999 [default: @code{"gdb $@{main@}"}]
15000 specifies the command used to debug the application
15001
15002 @end table
15003
15004 @noindent
15005 @command{gnatxref} and @command{gnatfind} only take into account the
15006 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15007
15008 @node Regular Expressions in gnatfind and gnatxref
15009 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15010
15011 @noindent
15012 As specified in the section about @command{gnatfind}, the pattern can be a
15013 regular expression. Actually, there are to set of regular expressions
15014 which are recognized by the program:
15015
15016 @table @code
15017 @item globbing patterns
15018 These are the most usual regular expression. They are the same that you
15019 generally used in a Unix shell command line, or in a DOS session.
15020
15021 Here is a more formal grammar:
15022 @smallexample
15023 @group
15024 @iftex
15025 @leftskip=.5cm
15026 @end iftex
15027 regexp ::= term
15028 term   ::= elmt            -- matches elmt
15029 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15030 term   ::= *               -- any string of 0 or more characters
15031 term   ::= ?               -- matches any character
15032 term   ::= [char @{char@}]   -- matches any character listed
15033 term   ::= [char - char]   -- matches any character in range
15034 @end group
15035 @end smallexample
15036
15037 @item full regular expression
15038 The second set of regular expressions is much more powerful. This is the
15039 type of regular expressions recognized by utilities such a @file{grep}.
15040
15041 The following is the form of a regular expression, expressed in Ada
15042 reference manual style BNF is as follows
15043
15044 @smallexample
15045 @iftex
15046 @leftskip=.5cm
15047 @end iftex
15048 @group
15049 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
15050
15051 term ::= item @{item@}       -- concatenation (item then item)
15052
15053 item ::= elmt              -- match elmt
15054 item ::= elmt *            -- zero or more elmt's
15055 item ::= elmt +            -- one or more elmt's
15056 item ::= elmt ?            -- matches elmt or nothing
15057 @end group
15058 @group
15059 elmt ::= nschar            -- matches given character
15060 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15061 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15062 elmt ::= [char - char]     -- matches chars in given range
15063 elmt ::= \ char            -- matches given character
15064 elmt ::= .                 -- matches any single character
15065 elmt ::= ( regexp )        -- parens used for grouping
15066
15067 char ::= any character, including special characters
15068 nschar ::= any character except ()[].*+?^^^
15069 @end group
15070 @end smallexample
15071
15072 Following are a few examples:
15073
15074 @table @samp
15075 @item abcde|fghi
15076 will match any of the two strings @samp{abcde} and @samp{fghi},
15077
15078 @item abc*d
15079 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15080 @samp{abcccd}, and so on,
15081
15082 @item [a-z]+
15083 will match any string which has only lowercase characters in it (and at
15084 least one character.
15085
15086 @end table
15087 @end table
15088
15089 @node Examples of gnatxref Usage
15090 @section Examples of @code{gnatxref} Usage
15091
15092 @subsection General Usage
15093
15094 @noindent
15095 For the following examples, we will consider the following units:
15096
15097 @smallexample @c ada
15098 @group
15099 @cartouche
15100 main.ads:
15101 1: with Bar;
15102 2: package Main is
15103 3:     procedure Foo (B : in Integer);
15104 4:     C : Integer;
15105 5: private
15106 6:     D : Integer;
15107 7: end Main;
15108
15109 main.adb:
15110 1: package body Main is
15111 2:     procedure Foo (B : in Integer) is
15112 3:     begin
15113 4:        C := B;
15114 5:        D := B;
15115 6:        Bar.Print (B);
15116 7:        Bar.Print (C);
15117 8:     end Foo;
15118 9: end Main;
15119
15120 bar.ads:
15121 1: package Bar is
15122 2:     procedure Print (B : Integer);
15123 3: end bar;
15124 @end cartouche
15125 @end group
15126 @end smallexample
15127
15128 @table @code
15129
15130 @noindent
15131 The first thing to do is to recompile your application (for instance, in
15132 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15133 the cross-referencing information.
15134 You can then issue any of the following commands:
15135
15136 @item gnatxref main.adb
15137 @code{gnatxref} generates cross-reference information for main.adb
15138 and every unit 'with'ed by main.adb.
15139
15140 The output would be:
15141 @smallexample
15142 @iftex
15143 @leftskip=0cm
15144 @end iftex
15145 B                                                      Type: Integer
15146   Decl: bar.ads           2:22
15147 B                                                      Type: Integer
15148   Decl: main.ads          3:20
15149   Body: main.adb          2:20
15150   Ref:  main.adb          4:13     5:13     6:19
15151 Bar                                                    Type: Unit
15152   Decl: bar.ads           1:9
15153   Ref:  main.adb          6:8      7:8
15154        main.ads           1:6
15155 C                                                      Type: Integer
15156   Decl: main.ads          4:5
15157   Modi: main.adb          4:8
15158   Ref:  main.adb          7:19
15159 D                                                      Type: Integer
15160   Decl: main.ads          6:5
15161   Modi: main.adb          5:8
15162 Foo                                                    Type: Unit
15163   Decl: main.ads          3:15
15164   Body: main.adb          2:15
15165 Main                                                    Type: Unit
15166   Decl: main.ads          2:9
15167   Body: main.adb          1:14
15168 Print                                                   Type: Unit
15169   Decl: bar.ads           2:15
15170   Ref:  main.adb          6:12     7:12
15171 @end smallexample
15172
15173 @noindent
15174 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15175 its body is in main.adb, line 1, column 14 and is not referenced any where.
15176
15177 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15178 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15179
15180 @item gnatxref package1.adb package2.ads
15181 @code{gnatxref} will generates cross-reference information for
15182 package1.adb, package2.ads and any other package 'with'ed by any
15183 of these.
15184
15185 @end table
15186
15187 @ifclear vms
15188 @subsection Using gnatxref with vi
15189
15190 @code{gnatxref} can generate a tags file output, which can be used
15191 directly from @command{vi}. Note that the standard version of @command{vi}
15192 will not work properly with overloaded symbols. Consider using another
15193 free implementation of @command{vi}, such as @command{vim}.
15194
15195 @smallexample
15196 $ gnatxref -v gnatfind.adb > tags
15197 @end smallexample
15198
15199 @noindent
15200 will generate the tags file for @code{gnatfind} itself (if the sources
15201 are in the search path!).
15202
15203 From @command{vi}, you can then use the command @samp{:tag @i{entity}}
15204 (replacing @i{entity} by whatever you are looking for), and vi will
15205 display a new file with the corresponding declaration of entity.
15206 @end ifclear
15207
15208 @node Examples of gnatfind Usage
15209 @section Examples of @code{gnatfind} Usage
15210
15211 @table @code
15212
15213 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15214 Find declarations for all entities xyz referenced at least once in
15215 main.adb. The references are search in every library file in the search
15216 path.
15217
15218 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15219 switch is set)
15220
15221 The output will look like:
15222 @smallexample
15223 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15224 ^directory/^[directory]^main.adb:24:10: xyz <= body
15225 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15226 @end smallexample
15227
15228 @noindent
15229 that is to say, one of the entities xyz found in main.adb is declared at
15230 line 12 of main.ads (and its body is in main.adb), and another one is
15231 declared at line 45 of foo.ads
15232
15233 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
15234 This is the same command as the previous one, instead @code{gnatfind} will
15235 display the content of the Ada source file lines.
15236
15237 The output will look like:
15238
15239 @smallexample
15240 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15241    procedure xyz;
15242 ^directory/^[directory]^main.adb:24:10: xyz <= body
15243    procedure xyz is
15244 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15245    xyz : Integer;
15246 @end smallexample
15247
15248 @noindent
15249 This can make it easier to find exactly the location your are looking
15250 for.
15251
15252 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
15253 Find references to all entities containing an x that are
15254 referenced on line 123 of main.ads.
15255 The references will be searched only in main.ads and foo.adb.
15256
15257 @item gnatfind main.ads:123
15258 Find declarations and bodies for all entities that are referenced on
15259 line 123 of main.ads.
15260
15261 This is the same as @code{gnatfind "*":main.adb:123}.
15262
15263 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
15264 Find the declaration for the entity referenced at column 45 in
15265 line 123 of file main.adb in directory mydir. Note that it
15266 is usual to omit the identifier name when the column is given,
15267 since the column position identifies a unique reference.
15268
15269 The column has to be the beginning of the identifier, and should not
15270 point to any character in the middle of the identifier.
15271
15272 @end table
15273
15274 @c *********************************
15275 @node The GNAT Pretty-Printer gnatpp
15276 @chapter The GNAT Pretty-Printer @command{gnatpp}
15277 @findex gnatpp
15278 @cindex Pretty-Printer
15279
15280 @noindent
15281 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
15282 for source reformatting / pretty-printing.
15283 It takes an Ada source file as input and generates a reformatted
15284 version as output.
15285 You can specify various style directives via switches; e.g.,
15286 identifier case conventions, rules of indentation, and comment layout.
15287
15288 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
15289 tree for the input source and thus requires the input to be syntactically and
15290 semantically legal.
15291 If this condition is not met, @command{gnatpp} will terminate with an
15292 error message; no output file will be generated.
15293
15294 If the source files presented to @command{gnatpp} contain
15295 preprocessing directives, then the output file will
15296 correspond to the generated source after all
15297 preprocessing is carried out. There is no way
15298 using @command{gnatpp} to obtain pretty printed files that
15299 include the preprocessing directives.
15300
15301 If the compilation unit
15302 contained in the input source depends semantically upon units located
15303 outside the current directory, you have to provide the source search path
15304 when invoking @command{gnatpp}, if these units are contained in files with
15305 names that do not follow the GNAT file naming rules, you have to provide
15306 the configuration file describing the corresponding naming scheme;
15307 see the description of the @command{gnatpp}
15308 switches below. Another possibility is to use a project file and to
15309 call @command{gnatpp} through the @command{gnat} driver
15310
15311 The @command{gnatpp} command has the form
15312
15313 @smallexample
15314 $ gnatpp [@var{switches}] @var{filename}
15315 @end smallexample
15316
15317 @noindent
15318 where
15319 @itemize @bullet
15320 @item
15321 @var{switches} is an optional sequence of switches defining such properties as
15322 the formatting rules, the source search path, and the destination for the
15323 output source file
15324
15325 @item
15326 @var{filename} is the name (including the extension) of the source file to
15327 reformat; ``wildcards'' or several file names on the same gnatpp command are
15328 allowed.  The file name may contain path information; it does not have to
15329 follow the GNAT file naming rules
15330 @end itemize
15331
15332 @menu
15333 * Switches for gnatpp::
15334 * Formatting Rules::
15335 @end menu
15336
15337 @node Switches for gnatpp
15338 @section Switches for @command{gnatpp}
15339
15340 @noindent
15341 The following subsections describe the various switches accepted by
15342 @command{gnatpp}, organized by category.
15343
15344 @ifclear vms
15345 You specify a switch by supplying a name and generally also a value.
15346 In many cases the values for a switch with a given name are incompatible with
15347 each other
15348 (for example the switch that controls the casing of a reserved word may have
15349 exactly one value: upper case, lower case, or
15350 mixed case) and thus exactly one such switch can be in effect for an
15351 invocation of @command{gnatpp}.
15352 If more than one is supplied, the last one is used.
15353 However, some values for the same switch are mutually compatible.
15354 You may supply several such switches to @command{gnatpp}, but then
15355 each must be specified in full, with both the name and the value.
15356 Abbreviated forms (the name appearing once, followed by each value) are
15357 not permitted.
15358 For example, to set
15359 the alignment of the assignment delimiter both in declarations and in
15360 assignment statements, you must write @option{-A2A3}
15361 (or @option{-A2 -A3}), but not @option{-A23}.
15362 @end ifclear
15363
15364 @ifset vms
15365 In many cases the set of options for a given qualifier are incompatible with
15366 each other (for example the qualifier that controls the casing of a reserved
15367 word may have exactly one option, which specifies either upper case, lower
15368 case, or mixed case), and thus exactly one such option can be in effect for
15369 an invocation of @command{gnatpp}.
15370 If more than one is supplied, the last one is used.
15371 However, some qualifiers have options that are mutually compatible,
15372 and then you may then supply several such options when invoking
15373 @command{gnatpp}.
15374 @end ifset
15375
15376 In most cases, it is obvious whether or not the
15377 ^values for a switch with a given name^options for a given qualifier^
15378 are compatible with each other.
15379 When the semantics might not be evident, the summaries below explicitly
15380 indicate the effect.
15381
15382 @menu
15383 * Alignment Control::
15384 * Casing Control::
15385 * Construct Layout Control::
15386 * General Text Layout Control::
15387 * Other Formatting Options::
15388 * Setting the Source Search Path::
15389 * Output File Control::
15390 * Other gnatpp Switches::
15391 @end menu
15392
15393 @node Alignment Control
15394 @subsection Alignment Control
15395 @cindex Alignment control in @command{gnatpp}
15396
15397 @noindent
15398 Programs can be easier to read if certain constructs are vertically aligned.
15399 By default all alignments are set ON.
15400 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
15401 OFF, and then use one or more of the other
15402 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
15403 to activate alignment for specific constructs.
15404
15405 @table @option
15406 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
15407
15408 @ifset vms
15409 @item /ALIGN=ON
15410 Set all alignments to ON
15411 @end ifset
15412
15413 @item ^-A0^/ALIGN=OFF^
15414 Set all alignments to OFF
15415
15416 @item ^-A1^/ALIGN=COLONS^
15417 Align @code{:} in declarations
15418
15419 @item ^-A2^/ALIGN=DECLARATIONS^
15420 Align @code{:=} in initializations in declarations
15421
15422 @item ^-A3^/ALIGN=STATEMENTS^
15423 Align @code{:=} in assignment statements
15424
15425 @item ^-A4^/ALIGN=ARROWS^
15426 Align @code{=>} in associations
15427
15428 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
15429 Align @code{at} keywords in the component clauses in record
15430 representation clauses
15431 @end table
15432
15433 @noindent
15434 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
15435 is allowed.
15436
15437 @node Casing Control
15438 @subsection Casing Control
15439 @cindex Casing control in @command{gnatpp}
15440
15441 @noindent
15442 @command{gnatpp} allows you to specify the casing for reserved words,
15443 pragma names, attribute designators and identifiers.
15444 For identifiers you may define a
15445 general rule for name casing but also override this rule
15446 via a set of dictionary files.
15447
15448 Three types of casing are supported: lower case, upper case, and mixed case.
15449 Lower and upper case are self-explanatory (but since some letters in
15450 Latin1 and other GNAT-supported character sets
15451 exist only in lower-case form, an upper case conversion will have no
15452 effect on them.)
15453 ``Mixed case'' means that the first letter, and also each letter immediately
15454 following an underscore, are converted to their uppercase forms;
15455 all the other letters are converted to their lowercase forms.
15456
15457 @table @option
15458 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
15459 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
15460 Attribute designators are lower case
15461
15462 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
15463 Attribute designators are upper case
15464
15465 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
15466 Attribute designators are mixed case (this is the default)
15467
15468 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
15469 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
15470 Keywords (technically, these are known in Ada as @emph{reserved words}) are
15471 lower case (this is the default)
15472
15473 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
15474 Keywords are upper case
15475
15476 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
15477 @item ^-nD^/NAME_CASING=AS_DECLARED^
15478 Name casing for defining occurrences are as they appear in the source file
15479 (this is the default)
15480
15481 @item ^-nU^/NAME_CASING=UPPER_CASE^
15482 Names are in upper case
15483
15484 @item ^-nL^/NAME_CASING=LOWER_CASE^
15485 Names are in lower case
15486
15487 @item ^-nM^/NAME_CASING=MIXED_CASE^
15488 Names are in mixed case
15489
15490 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
15491 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
15492 Pragma names are lower case
15493
15494 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
15495 Pragma names are upper case
15496
15497 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
15498 Pragma names are mixed case (this is the default)
15499
15500 @item ^-D@var{file}^/DICTIONARY=@var{file}^
15501 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
15502 Use @var{file} as a @emph{dictionary file} that defines
15503 the casing for a set of specified names,
15504 thereby overriding the effect on these names by
15505 any explicit or implicit
15506 ^-n^/NAME_CASING^ switch.
15507 To supply more than one dictionary file,
15508 use ^several @option{-D} switches^a list of files as options^.
15509
15510 @noindent
15511 @option{gnatpp} implicitly uses a @emph{default dictionary file}
15512 to define the casing for the Ada predefined names and
15513 the names declared in the GNAT libraries.
15514
15515 @item ^-D-^/SPECIFIC_CASING^
15516 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
15517 Do not use the default dictionary file;
15518 instead, use the casing
15519 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
15520 dictionary file(s)
15521 @end table
15522
15523 @noindent
15524 The structure of a dictionary file, and details on the conventions
15525 used in the default dictionary file, are defined in @ref{Name Casing}.
15526
15527 The @option{^-D-^/SPECIFIC_CASING^} and
15528 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
15529 compatible.
15530
15531 @node Construct Layout Control
15532 @subsection Construct Layout Control
15533 @cindex Layout control in @command{gnatpp}
15534
15535 @noindent
15536 This group of @command{gnatpp} switches controls the layout of comments and
15537 complex syntactic constructs.  See @ref{Formatting Comments} for details
15538 on their effect.
15539
15540 @table @option
15541 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
15542 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
15543 All the comments remain unchanged
15544
15545 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
15546 GNAT-style comment line indentation (this is the default).
15547
15548 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
15549 Reference-manual comment line indentation.
15550
15551 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
15552 GNAT-style comment beginning
15553
15554 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
15555 Reformat comment blocks
15556
15557 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
15558 Keep unchanged special form comments
15559
15560 Reformat comment blocks
15561
15562 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
15563 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
15564 GNAT-style layout (this is the default)
15565
15566 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
15567 Compact layout
15568
15569 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
15570 Uncompact layout
15571
15572 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
15573 @item ^-N^/NOTABS^
15574 All the VT characters are removed from the comment text. All the HT characters
15575 are expanded with the sequences of space characters to get to the next tab
15576 stops.
15577
15578 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
15579 @item ^--no-separate-is^/NO_SEPARATE_IS^
15580 Do not place the keyword @code{is} on a separate line in a subprogram body in
15581 case if the specification occupies more then one line.
15582
15583 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
15584 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
15585 Place the keyword @code{loop} in FOR and WHILE loop statements and the
15586 keyword @code{then} in IF statements on a separate line.
15587
15588 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
15589 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
15590 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
15591 keyword @code{then} in IF statements on a separate line. This option is
15592 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
15593
15594 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
15595 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
15596 Start each USE clause in a context clause from a separate line.
15597
15598 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
15599 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
15600 Use a separate line for a loop or block statement name, but do not use an extra
15601 indentation level for the statement itself.
15602
15603 @end table
15604
15605 @ifclear vms
15606 @noindent
15607 The @option{-c1} and @option{-c2} switches are incompatible.
15608 The @option{-c3} and @option{-c4} switches are compatible with each other and
15609 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
15610 the other comment formatting switches.
15611
15612 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
15613 @end ifclear
15614
15615 @ifset vms
15616 @noindent
15617 For the @option{/COMMENTS_LAYOUT} qualifier:
15618 @itemize @bullet
15619 @item
15620 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
15621 @item
15622 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
15623 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
15624 @end itemize
15625
15626 @noindent
15627 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
15628 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
15629 @end ifset
15630
15631 @node General Text Layout Control
15632 @subsection General Text Layout Control
15633
15634 @noindent
15635 These switches allow control over line length and indentation.
15636
15637 @table @option
15638 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
15639 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
15640 Maximum line length, @i{nnn} from 32@dots{}256, the default value is 79
15641
15642 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
15643 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
15644 Indentation level, @i{nnn} from 1@dots{}9, the default value is 3
15645
15646 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
15647 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
15648 Indentation level for continuation lines (relative to the line being
15649 continued), @i{nnn} from 1@dots{}9.
15650 The default
15651 value is one less then the (normal) indentation level, unless the
15652 indentation is set to 1 (in which case the default value for continuation
15653 line indentation is also 1)
15654 @end table
15655
15656 @node Other Formatting Options
15657 @subsection Other Formatting Options
15658
15659 @noindent
15660 These switches control the inclusion of missing end/exit labels, and
15661 the indentation level in @b{case} statements.
15662
15663 @table @option
15664 @item ^-e^/NO_MISSED_LABELS^
15665 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
15666 Do not insert missing end/exit labels. An end label is the name of
15667 a construct that may optionally be repeated at the end of the
15668 construct's declaration;
15669 e.g., the names of packages, subprograms, and tasks.
15670 An exit label is the name of a loop that may appear as target
15671 of an exit statement within the loop.
15672 By default, @command{gnatpp} inserts these end/exit labels when
15673 they are absent from the original source. This option suppresses such
15674 insertion, so that the formatted source reflects the original.
15675
15676 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
15677 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
15678 Insert a Form Feed character after a pragma Page.
15679
15680 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
15681 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
15682 Do not use an additional indentation level for @b{case} alternatives
15683 and variants if there are @i{nnn} or more (the default
15684 value is 10).
15685 If @i{nnn} is 0, an additional indentation level is
15686 used for @b{case} alternatives and variants regardless of their number.
15687 @end table
15688
15689 @node Setting the Source Search Path
15690 @subsection Setting the Source Search Path
15691
15692 @noindent
15693 To define the search path for the input source file, @command{gnatpp}
15694 uses the same switches as the GNAT compiler, with the same effects.
15695
15696 @table @option
15697 @item ^-I^/SEARCH=^@var{dir}
15698 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
15699 The same as the corresponding gcc switch
15700
15701 @item ^-I-^/NOCURRENT_DIRECTORY^
15702 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
15703 The same as the corresponding gcc switch
15704
15705 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
15706 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
15707 The same as the corresponding gcc switch
15708
15709 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
15710 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
15711 The same as the corresponding gcc switch
15712
15713 @end table
15714
15715 @node Output File Control
15716 @subsection Output File Control
15717
15718 @noindent
15719 By default the output is sent to the file whose name is obtained by appending
15720 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
15721 (if the file with this name already exists, it is unconditionally overwritten).
15722 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
15723 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
15724 as output file.
15725 The output may be redirected by the following switches:
15726
15727 @table @option
15728 @item ^-pipe^/STANDARD_OUTPUT^
15729 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
15730 Send the output to @code{Standard_Output}
15731
15732 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
15733 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
15734 Write the output into @var{output_file}.
15735 If @var{output_file} already exists, @command{gnatpp} terminates without
15736 reading or processing the input file.
15737
15738 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
15739 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
15740 Write the output into @var{output_file}, overwriting the existing file
15741 (if one is present).
15742
15743 @item ^-r^/REPLACE^
15744 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
15745 Replace the input source file with the reformatted output, and copy the
15746 original input source into the file whose name is obtained by appending the
15747 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
15748 If a file with this name already exists, @command{gnatpp} terminates without
15749 reading or processing the input file.
15750
15751 @item ^-rf^/OVERRIDING_REPLACE^
15752 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
15753 Like @option{^-r^/REPLACE^} except that if the file with the specified name
15754 already exists, it is overwritten.
15755
15756 @item ^-rnb^/NO_BACKUP^
15757 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
15758 Replace the input source file with the reformatted output without
15759 creating any backup copy of the input source.
15760
15761 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
15762 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
15763 Specifies the format of the reformatted output file. The @var{xxx}
15764 ^string specified with the switch^option^ may be either
15765 @itemize @bullet
15766 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
15767 @item ``@option{^crlf^CRLF^}''
15768 the same as @option{^crlf^CRLF^}
15769 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
15770 @item ``@option{^lf^LF^}''
15771 the same as @option{^unix^UNIX^}
15772 @end itemize
15773
15774 @item ^-W^/RESULT_ENCODING=^@var{e}
15775 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
15776 Specify the wide character encoding method used to write the code in the
15777 result file
15778 @var{e} is one of the following:
15779
15780 @itemize @bullet
15781
15782 @item ^h^HEX^
15783 Hex encoding
15784
15785 @item ^u^UPPER^
15786 Upper half encoding
15787
15788 @item ^s^SHIFT_JIS^
15789 Shift/JIS encoding
15790
15791 @item ^e^EUC^
15792 EUC encoding
15793
15794 @item ^8^UTF8^
15795 UTF-8 encoding
15796
15797 @item ^b^BRACKETS^
15798 Brackets encoding (default value)
15799 @end itemize
15800
15801 @end table
15802
15803 @noindent
15804 Options @option{^-pipe^/STANDARD_OUTPUT^},
15805 @option{^-o^/OUTPUT^} and
15806 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
15807 contains only one file to reformat.
15808 Option
15809 @option{^--eol^/END_OF_LINE^}
15810 and
15811 @option{^-W^/RESULT_ENCODING^}
15812 cannot be used together
15813 with @option{^-pipe^/STANDARD_OUTPUT^} option.
15814
15815 @node Other gnatpp Switches
15816 @subsection Other @code{gnatpp} Switches
15817
15818 @noindent
15819 The additional @command{gnatpp} switches are defined in this subsection.
15820
15821 @table @option
15822 @item ^-files @var{filename}^/FILES=@var{output_file}^
15823 @cindex @option{^-files^/FILES^} (@code{gnatpp})
15824 Take the argument source files from the specified file. This file should be an
15825 ordinary textual file containing file names separated by spaces or
15826 line breaks. You can use this switch more then once in the same call to
15827 @command{gnatpp}. You also can combine this switch with explicit list of
15828 files.
15829
15830 @item ^-v^/VERBOSE^
15831 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
15832 Verbose mode;
15833 @command{gnatpp} generates version information and then
15834 a trace of the actions it takes to produce or obtain the ASIS tree.
15835
15836 @item ^-w^/WARNINGS^
15837 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
15838 Warning mode;
15839 @command{gnatpp} generates a warning whenever it cannot provide
15840 a required layout in the result source.
15841 @end table
15842
15843 @node Formatting Rules
15844 @section Formatting Rules
15845
15846 @noindent
15847 The following subsections show how @command{gnatpp} treats ``white space'',
15848 comments, program layout, and name casing.
15849 They provide the detailed descriptions of the switches shown above.
15850
15851 @menu
15852 * White Space and Empty Lines::
15853 * Formatting Comments::
15854 * Construct Layout::
15855 * Name Casing::
15856 @end menu
15857
15858 @node White Space and Empty Lines
15859 @subsection White Space and Empty Lines
15860
15861 @noindent
15862 @command{gnatpp} does not have an option to control space characters.
15863 It will add or remove spaces according to the style illustrated by the
15864 examples in the @cite{Ada Reference Manual}.
15865
15866 The only format effectors
15867 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
15868 that will appear in the output file are platform-specific line breaks,
15869 and also format effectors within (but not at the end of) comments.
15870 In particular, each horizontal tab character that is not inside
15871 a comment will be treated as a space and thus will appear in the
15872 output file as zero or more spaces depending on
15873 the reformatting of the line in which it appears.
15874 The only exception is a Form Feed character, which is inserted after a
15875 pragma @code{Page} when @option{-ff} is set.
15876
15877 The output file will contain no lines with trailing ``white space'' (spaces,
15878 format effectors).
15879
15880 Empty lines in the original source are preserved
15881 only if they separate declarations or statements.
15882 In such contexts, a
15883 sequence of two or more empty lines is replaced by exactly one empty line.
15884 Note that a blank line will be removed if it separates two ``comment blocks''
15885 (a comment block is a sequence of whole-line comments).
15886 In order to preserve a visual separation between comment blocks, use an
15887 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
15888 Likewise, if for some reason you wish to have a sequence of empty lines,
15889 use a sequence of empty comments instead.
15890
15891 @node Formatting Comments
15892 @subsection Formatting Comments
15893
15894 @noindent
15895 Comments in Ada code are of two kinds:
15896 @itemize @bullet
15897 @item
15898 a @emph{whole-line comment}, which appears by itself (possibly preceded by
15899 ``white space'') on a line
15900
15901 @item
15902 an @emph{end-of-line comment}, which follows some other Ada lexical element
15903 on the same line.
15904 @end itemize
15905
15906 @noindent
15907 The indentation of a whole-line comment is that of either
15908 the preceding or following line in
15909 the formatted source, depending on switch settings as will be described below.
15910
15911 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
15912 between the end of the preceding Ada lexical element and the beginning
15913 of the comment as appear in the original source,
15914 unless either the comment has to be split to
15915 satisfy the line length limitation, or else the next line contains a
15916 whole line comment that is considered a continuation of this end-of-line
15917 comment (because it starts at the same position).
15918 In the latter two
15919 cases, the start of the end-of-line comment is moved right to the nearest
15920 multiple of the indentation level.
15921 This may result in a ``line overflow'' (the right-shifted comment extending
15922 beyond the maximum line length), in which case the comment is split as
15923 described below.
15924
15925 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
15926 (GNAT-style comment line indentation)
15927 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
15928 (reference-manual comment line indentation).
15929 With reference-manual style, a whole-line comment is indented as if it
15930 were a declaration or statement at the same place
15931 (i.e., according to the indentation of the preceding line(s)).
15932 With GNAT style, a whole-line comment that is immediately followed by an
15933 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15934 word @b{begin}, is indented based on the construct that follows it.
15935
15936 For example:
15937 @smallexample @c ada
15938 @cartouche
15939 if A then
15940     null;
15941        -- some comment
15942 else
15943    null;
15944 end if;
15945 @end cartouche
15946 @end smallexample
15947
15948 @noindent
15949 Reference-manual indentation produces:
15950
15951 @smallexample @c ada
15952 @cartouche
15953 if A then
15954    null;
15955    --  some comment
15956 else
15957    null;
15958 end if;
15959 @end cartouche
15960 @end smallexample
15961
15962 @noindent
15963 while GNAT-style indentation produces:
15964
15965 @smallexample @c ada
15966 @cartouche
15967 if A then
15968    null;
15969 --  some comment
15970 else
15971    null;
15972 end if;
15973 @end cartouche
15974 @end smallexample
15975
15976 @noindent
15977 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15978 (GNAT style comment beginning) has the following
15979 effect:
15980
15981 @itemize @bullet
15982 @item
15983 For each whole-line comment that does not end with two hyphens,
15984 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15985 to ensure that there are at least two spaces between these hyphens and the
15986 first non-blank character of the comment.
15987 @end itemize
15988
15989 @noindent
15990 For an end-of-line comment, if in the original source the next line is a
15991 whole-line comment that starts at the same position
15992 as the end-of-line comment,
15993 then the whole-line comment (and all whole-line comments
15994 that follow it and that start at the same position)
15995 will start at this position in the output file.
15996
15997 @noindent
15998 That is, if in the original source we have:
15999
16000 @smallexample @c ada
16001 @cartouche
16002 begin
16003 A := B + C;            --  B must be in the range Low1..High1
16004                        --  C must be in the range Low2..High2
16005              --B+C will be in the range Low1+Low2..High1+High2
16006 X := X + 1;
16007 @end cartouche
16008 @end smallexample
16009
16010 @noindent
16011 Then in the formatted source we get
16012
16013 @smallexample @c ada
16014 @cartouche
16015 begin
16016    A := B + C;            --  B must be in the range Low1..High1
16017                           --  C must be in the range Low2..High2
16018    --  B+C will be in the range Low1+Low2..High1+High2
16019    X := X + 1;
16020 @end cartouche
16021 @end smallexample
16022
16023 @noindent
16024 A comment that exceeds the line length limit will be split.
16025 Unless switch
16026 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16027 the line belongs to a reformattable block, splitting the line generates a
16028 @command{gnatpp} warning.
16029 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16030 comments may be reformatted in typical
16031 word processor style (that is, moving words between lines and putting as
16032 many words in a line as possible).
16033
16034 @noindent
16035 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16036 that has a special format (that is, a character that is neither a letter nor digit
16037 not white space nor line break immediately following the leading @code{--} of
16038 the comment) should be without any change moved from the argument source
16039 into reformatted source. This switch allows to preserve comments that are used
16040 as a special marks in the code (e.g.@: SPARK annotation).
16041
16042 @node Construct Layout
16043 @subsection Construct Layout
16044
16045 @noindent
16046 In several cases the suggested layout in the Ada Reference Manual includes
16047 an extra level of indentation that many programmers prefer to avoid. The
16048 affected cases include:
16049
16050 @itemize @bullet
16051
16052 @item Record type declaration (RM 3.8)
16053
16054 @item Record representation clause (RM 13.5.1)
16055
16056 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16057
16058 @item Block statement in case if a block has a statement identifier (RM 5.6)
16059 @end itemize
16060
16061 @noindent
16062 In compact mode (when GNAT style layout or compact layout is set),
16063 the pretty printer uses one level of indentation instead
16064 of two. This is achieved in the record definition and record representation
16065 clause cases by putting the @code{record} keyword on the same line as the
16066 start of the declaration or representation clause, and in the block and loop
16067 case by putting the block or loop header on the same line as the statement
16068 identifier.
16069
16070 @noindent
16071 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16072 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16073 layout on the one hand, and uncompact layout
16074 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16075 can be illustrated by the following examples:
16076
16077 @iftex
16078 @cartouche
16079 @multitable @columnfractions .5 .5
16080 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16081
16082 @item
16083 @smallexample @c ada
16084 type q is record
16085    a : integer;
16086    b : integer;
16087 end record;
16088 @end smallexample
16089 @tab
16090 @smallexample @c ada
16091 type q is
16092    record
16093       a : integer;
16094       b : integer;
16095    end record;
16096 @end smallexample
16097
16098 @item
16099 @smallexample @c ada
16100 for q use record
16101    a at 0 range  0 .. 31;
16102    b at 4 range  0 .. 31;
16103 end record;
16104 @end smallexample
16105 @tab
16106 @smallexample @c ada
16107 for q use
16108    record
16109       a at 0 range  0 .. 31;
16110       b at 4 range  0 .. 31;
16111    end record;
16112 @end smallexample
16113
16114 @item
16115 @smallexample @c ada
16116 Block : declare
16117    A : Integer := 3;
16118 begin
16119    Proc (A, A);
16120 end Block;
16121 @end smallexample
16122 @tab
16123 @smallexample @c ada
16124 Block :
16125    declare
16126       A : Integer := 3;
16127    begin
16128       Proc (A, A);
16129    end Block;
16130 @end smallexample
16131
16132 @item
16133 @smallexample @c ada
16134 Clear : for J in 1 .. 10 loop
16135    A (J) := 0;
16136 end loop Clear;
16137 @end smallexample
16138 @tab
16139 @smallexample @c ada
16140 Clear :
16141    for J in 1 .. 10 loop
16142       A (J) := 0;
16143    end loop Clear;
16144 @end smallexample
16145 @end multitable
16146 @end cartouche
16147 @end iftex
16148
16149 @ifnottex
16150 @smallexample
16151 @cartouche
16152 GNAT style, compact layout              Uncompact layout
16153
16154 type q is record                        type q is
16155    a : integer;                            record
16156    b : integer;                               a : integer;
16157 end record;                                   b : integer;
16158                                            end record;
16159
16160 for q use record                        for q use
16161    a at 0 range  0 .. 31;                  record
16162    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16163 end record;                                   b at 4 range  0 .. 31;
16164                                            end record;
16165
16166 Block : declare                         Block :
16167    A : Integer := 3;                       declare
16168 begin                                         A : Integer := 3;
16169    Proc (A, A);                            begin
16170 end Block;                                    Proc (A, A);
16171                                            end Block;
16172
16173 Clear : for J in 1 .. 10 loop           Clear :
16174    A (J) := 0;                             for J in 1 .. 10 loop
16175 end loop Clear;                               A (J) := 0;
16176                                            end loop Clear;
16177 @end cartouche
16178 @end smallexample
16179 @end ifnottex
16180
16181 @noindent
16182 A further difference between GNAT style layout and compact layout is that
16183 GNAT style layout inserts empty lines as separation for
16184 compound statements, return statements and bodies.
16185
16186 Note that the layout specified by
16187 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16188 for named block and loop statements overrides the layout defined by these
16189 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16190 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16191 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16192
16193 @node Name Casing
16194 @subsection Name Casing
16195
16196 @noindent
16197 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16198 the same casing as the corresponding defining identifier.
16199
16200 You control the casing for defining occurrences via the
16201 @option{^-n^/NAME_CASING^} switch.
16202 @ifclear vms
16203 With @option{-nD} (``as declared'', which is the default),
16204 @end ifclear
16205 @ifset vms
16206 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16207 @end ifset
16208 defining occurrences appear exactly as in the source file
16209 where they are declared.
16210 The other ^values for this switch^options for this qualifier^ ---
16211 @option{^-nU^UPPER_CASE^},
16212 @option{^-nL^LOWER_CASE^},
16213 @option{^-nM^MIXED_CASE^} ---
16214 result in
16215 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16216 If @command{gnatpp} changes the casing of a defining
16217 occurrence, it analogously changes the casing of all the
16218 usage occurrences of this name.
16219
16220 If the defining occurrence of a name is not in the source compilation unit
16221 currently being processed by @command{gnatpp}, the casing of each reference to
16222 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16223 switch (subject to the dictionary file mechanism described below).
16224 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
16225 had affected the
16226 casing for the defining occurrence of the name.
16227
16228 Some names may need to be spelled with casing conventions that are not
16229 covered by the upper-, lower-, and mixed-case transformations.
16230 You can arrange correct casing by placing such names in a
16231 @emph{dictionary file},
16232 and then supplying a @option{^-D^/DICTIONARY^} switch.
16233 The casing of names from dictionary files overrides
16234 any @option{^-n^/NAME_CASING^} switch.
16235
16236 To handle the casing of Ada predefined names and the names from GNAT libraries,
16237 @command{gnatpp} assumes a default dictionary file.
16238 The name of each predefined entity is spelled with the same casing as is used
16239 for the entity in the @cite{Ada Reference Manual}.
16240 The name of each entity in the GNAT libraries is spelled with the same casing
16241 as is used in the declaration of that entity.
16242
16243 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
16244 default dictionary file.
16245 Instead, the casing for predefined and GNAT-defined names will be established
16246 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
16247 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
16248 will appear as just shown,
16249 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
16250 To ensure that even such names are rendered in uppercase,
16251 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
16252 (or else, less conveniently, place these names in upper case in a dictionary
16253 file).
16254
16255 A dictionary file is
16256 a plain text file; each line in this file can be either a blank line
16257 (containing only space characters and ASCII.HT characters), an Ada comment
16258 line, or the specification of exactly one @emph{casing schema}.
16259
16260 A casing schema is a string that has the following syntax:
16261
16262 @smallexample
16263 @cartouche
16264   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
16265
16266   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
16267 @end cartouche
16268 @end smallexample
16269
16270 @noindent
16271 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
16272 @var{identifier} lexical element and the @var{letter_or_digit} category.)
16273
16274 The casing schema string can be followed by white space and/or an Ada-style
16275 comment; any amount of white space is allowed before the string.
16276
16277 If a dictionary file is passed as
16278 @ifclear vms
16279 the value of a @option{-D@var{file}} switch
16280 @end ifclear
16281 @ifset vms
16282 an option to the @option{/DICTIONARY} qualifier
16283 @end ifset
16284 then for every
16285 simple name and every identifier, @command{gnatpp} checks if the dictionary
16286 defines the casing for the name or for some of its parts (the term ``subword''
16287 is used below to denote the part of a name which is delimited by ``_'' or by
16288 the beginning or end of the word and which does not contain any ``_'' inside):
16289
16290 @itemize @bullet
16291 @item
16292 if the whole name is in the dictionary, @command{gnatpp} uses for this name
16293 the casing defined by the dictionary; no subwords are checked for this word
16294
16295 @item
16296 for every subword @command{gnatpp} checks if the dictionary contains the
16297 corresponding string of the form @code{*@var{simple_identifier}*},
16298 and if it does, the casing of this @var{simple_identifier} is used
16299 for this subword
16300
16301 @item
16302 if the whole name does not contain any ``_'' inside, and if for this name
16303 the dictionary contains two entries - one of the form @var{identifier},
16304 and another - of the form *@var{simple_identifier}*, then the first one
16305 is applied to define the casing of this name
16306
16307 @item
16308 if more than one dictionary file is passed as @command{gnatpp} switches, each
16309 dictionary adds new casing exceptions and overrides all the existing casing
16310 exceptions set by the previous dictionaries
16311
16312 @item
16313 when @command{gnatpp} checks if the word or subword is in the dictionary,
16314 this check is not case sensitive
16315 @end itemize
16316
16317 @noindent
16318 For example, suppose we have the following source to reformat:
16319
16320 @smallexample @c ada
16321 @cartouche
16322 procedure test is
16323    name1 : integer := 1;
16324    name4_name3_name2 : integer := 2;
16325    name2_name3_name4 : Boolean;
16326    name1_var : Float;
16327 begin
16328    name2_name3_name4 := name4_name3_name2 > name1;
16329 end;
16330 @end cartouche
16331 @end smallexample
16332
16333 @noindent
16334 And suppose we have two dictionaries:
16335
16336 @smallexample
16337 @cartouche
16338 @i{dict1:}
16339    NAME1
16340    *NaMe3*
16341    *Name1*
16342 @end cartouche
16343
16344 @cartouche
16345 @i{dict2:}
16346   *NAME3*
16347 @end cartouche
16348 @end smallexample
16349
16350 @noindent
16351 If @command{gnatpp} is called with the following switches:
16352
16353 @smallexample
16354 @ifclear vms
16355 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
16356 @end ifclear
16357 @ifset vms
16358 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
16359 @end ifset
16360 @end smallexample
16361
16362 @noindent
16363 then we will get the following name casing in the @command{gnatpp} output:
16364
16365 @smallexample @c ada
16366 @cartouche
16367 procedure Test is
16368    NAME1             : Integer := 1;
16369    Name4_NAME3_Name2 : Integer := 2;
16370    Name2_NAME3_Name4 : Boolean;
16371    Name1_Var         : Float;
16372 begin
16373    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
16374 end Test;
16375 @end cartouche
16376 @end smallexample
16377
16378 @c *********************************
16379 @node The GNAT Metric Tool gnatmetric
16380 @chapter The GNAT Metric Tool @command{gnatmetric}
16381 @findex gnatmetric
16382 @cindex Metric tool
16383
16384 @noindent
16385 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
16386 for computing various program metrics.
16387 It takes an Ada source file as input and generates a file containing the
16388 metrics data as output. Various switches control which
16389 metrics are computed and output.
16390
16391 @command{gnatmetric} generates and uses the ASIS
16392 tree for the input source and thus requires the input to be syntactically and
16393 semantically legal.
16394 If this condition is not met, @command{gnatmetric} will generate
16395 an error message; no metric information for this file will be
16396 computed and reported.
16397
16398 If the compilation unit contained in the input source depends semantically
16399 upon units in files located outside the current directory, you have to provide
16400 the source search path when invoking @command{gnatmetric}.
16401 If it depends semantically upon units that are contained
16402 in files with names that do not follow the GNAT file naming rules, you have to
16403 provide the configuration file describing the corresponding naming scheme (see
16404 the description of the @command{gnatmetric} switches below.)
16405 Alternatively, you may use a project file and invoke @command{gnatmetric}
16406 through the @command{gnat} driver.
16407
16408 The @command{gnatmetric} command has the form
16409
16410 @smallexample
16411 $ gnatmetric [@i{switches}] @{@i{filename}@} [@i{-cargs gcc_switches}]
16412 @end smallexample
16413
16414 @noindent
16415 where
16416 @itemize @bullet
16417 @item
16418 @i{switches} specify the metrics to compute and define the destination for
16419 the output
16420
16421 @item
16422 Each @i{filename} is the name (including the extension) of a source
16423 file to process. ``Wildcards'' are allowed, and
16424 the file name may contain path information.
16425 If no @i{filename} is supplied, then the @i{switches} list must contain
16426 at least one
16427 @option{-files} switch (@pxref{Other gnatmetric Switches}).
16428 Including both a @option{-files} switch and one or more
16429 @i{filename} arguments is permitted.
16430
16431 @item
16432 @i{-cargs gcc_switches} is a list of switches for
16433 @command{gcc}. They will be passed on to all compiler invocations made by
16434 @command{gnatmetric} to generate the ASIS trees. Here you can provide
16435 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
16436 and use the @option{-gnatec} switch to set the configuration file.
16437 @end itemize
16438
16439 @menu
16440 * Switches for gnatmetric::
16441 @end menu
16442
16443 @node Switches for gnatmetric
16444 @section Switches for @command{gnatmetric}
16445
16446 @noindent
16447 The following subsections describe the various switches accepted by
16448 @command{gnatmetric}, organized by category.
16449
16450 @menu
16451 * Output Files Control::
16452 * Disable Metrics For Local Units::
16453 * Specifying a set of metrics to compute::
16454 * Other gnatmetric Switches::
16455 * Generate project-wide metrics::
16456 @end menu
16457
16458 @node Output Files Control
16459 @subsection Output File Control
16460 @cindex Output file control in @command{gnatmetric}
16461
16462 @noindent
16463 @command{gnatmetric} has two output formats. It can generate a
16464 textual (human-readable) form, and also XML. By default only textual
16465 output is generated.
16466
16467 When generating the output in textual form, @command{gnatmetric} creates
16468 for each Ada source file a corresponding text file
16469 containing the computed metrics, except for the case when the set of metrics
16470 specified by gnatmetric parameters consists only of metrics that are computed
16471 for the whole set of analyzed sources, but not for each Ada source.
16472 By default, this file is placed in the same directory as where the source
16473 file is located, and its name is obtained
16474 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
16475 input file.
16476
16477 All the output information generated in XML format is placed in a single
16478 file. By default this file is placed in the current directory and has the
16479 name ^@file{metrix.xml}^@file{METRIX$XML}^.
16480
16481 Some of the computed metrics are summed over the units passed to
16482 @command{gnatmetric}; for example, the total number of lines of code.
16483 By default this information is sent to @file{stdout}, but a file
16484 can be specified with the @option{-og} switch.
16485
16486 The following switches control the @command{gnatmetric} output:
16487
16488 @table @option
16489 @cindex @option{^-x^/XML^} (@command{gnatmetric})
16490 @item ^-x^/XML^
16491 Generate the XML output
16492
16493 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
16494 @item ^-nt^/NO_TEXT^
16495 Do not generate the output in text form (implies @option{^-x^/XML^})
16496
16497 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
16498 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
16499 Put textual files with detailed metrics into @var{output_dir}
16500
16501 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
16502 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
16503 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
16504 in the name of the output file.
16505
16506 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
16507 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
16508 Put global metrics into @var{file_name}
16509
16510 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
16511 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
16512 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
16513
16514 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
16515 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
16516 Use ``short'' source file names in the output.  (The @command{gnatmetric}
16517 output includes the name(s) of the Ada source file(s) from which the metrics
16518 are computed.  By default each name includes the absolute path. The
16519 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
16520 to exclude all directory information from the file names that are output.)
16521
16522 @end table
16523
16524 @node Disable Metrics For Local Units
16525 @subsection Disable Metrics For Local Units
16526 @cindex Disable Metrics For Local Units in @command{gnatmetric}
16527
16528 @noindent
16529 @command{gnatmetric} relies on the GNAT compilation model @minus{}
16530 one compilation
16531 unit per one source file. It computes line metrics for the whole source
16532 file, and it also computes syntax
16533 and complexity metrics for the file's outermost unit.
16534
16535 By default, @command{gnatmetric} will also compute all metrics for certain
16536 kinds of locally declared program units:
16537
16538 @itemize @bullet
16539 @item
16540 subprogram (and generic subprogram) bodies;
16541
16542 @item
16543 package (and generic package) specifications and bodies;
16544
16545 @item
16546 task object and type specifications and bodies;
16547
16548 @item
16549 protected object and type specifications and bodies.
16550 @end itemize
16551
16552 @noindent
16553 These kinds of entities will be referred to as
16554 @emph{eligible local program units}, or simply @emph{eligible local units},
16555 @cindex Eligible local unit (for @command{gnatmetric})
16556 in the discussion below.
16557
16558 Note that a subprogram declaration, generic instantiation,
16559 or renaming declaration only receives metrics
16560 computation when it appear as the outermost entity
16561 in a source file.
16562
16563 Suppression of metrics computation for eligible local units can be
16564 obtained via the following switch:
16565
16566 @table @option
16567 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16568 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
16569 Do not compute detailed metrics for eligible local program units
16570
16571 @end table
16572
16573 @node Specifying a set of metrics to compute
16574 @subsection Specifying a set of metrics to compute
16575
16576 @noindent
16577 By default all the metrics are computed and reported. The switches
16578 described in this subsection allow you to control, on an individual
16579 basis, whether metrics are computed and
16580 reported. If at least one positive metric
16581 switch is specified (that is, a switch that defines that a given
16582 metric or set of metrics is to be computed), then only
16583 explicitly specified metrics are reported.
16584
16585 @menu
16586 * Line Metrics Control::
16587 * Syntax Metrics Control::
16588 * Complexity Metrics Control::
16589 @end menu
16590
16591 @node Line Metrics Control
16592 @subsubsection Line Metrics Control
16593 @cindex Line metrics control in @command{gnatmetric}
16594
16595 @noindent
16596 For any (legal) source file, and for each of its
16597 eligible local program units, @command{gnatmetric} computes the following
16598 metrics:
16599
16600 @itemize @bullet
16601 @item
16602 the total number of lines;
16603
16604 @item
16605 the total number of code lines (i.e., non-blank lines that are not comments)
16606
16607 @item
16608 the number of comment lines
16609
16610 @item
16611 the number of code lines containing end-of-line comments;
16612
16613 @item
16614 the comment percentage: the ratio between the number of lines that contain
16615 comments and the number of all non-blank lines, expressed as a percentage;
16616
16617 @item
16618 the number of empty lines and lines containing only space characters and/or
16619 format effectors (blank lines)
16620
16621 @item
16622 the average number of code lines in subprogram bodies, task bodies, entry
16623 bodies and statement sequences in package bodies (this metric is only computed
16624 across the whole set of the analyzed units)
16625
16626 @end itemize
16627
16628 @noindent
16629 @command{gnatmetric} sums the values of the line metrics for all the
16630 files being processed and then generates the cumulative results. The tool
16631 also computes for all the files being processed the average number of code
16632 lines in bodies.
16633
16634 You can use the following switches to select the specific line metrics
16635 to be computed and reported.
16636
16637 @table @option
16638 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
16639
16640 @ifclear vms
16641 @cindex @option{--no-lines@var{x}}
16642 @end ifclear
16643
16644 @item ^--lines-all^/LINE_COUNT_METRICS=ALL_ON^
16645 Report all the line metrics
16646
16647 @item ^--no-lines-all^/LINE_COUNT_METRICS=ALL_OFF^
16648 Do not report any of line metrics
16649
16650 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES_ON^
16651 Report the number of all lines
16652
16653 @item ^--no-lines^/LINE_COUNT_METRICS=ALL_LINES_OFF^
16654 Do not report the number of all lines
16655
16656 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES_ON^
16657 Report the number of code lines
16658
16659 @item ^--no-lines-code^/LINE_COUNT_METRICS=CODE_LINES_OFF^
16660 Do not report the number of code lines
16661
16662 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_ON^
16663 Report the number of comment lines
16664
16665 @item ^--no-lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_OFF^
16666 Do not report the number of comment lines
16667
16668 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_ON^
16669 Report the number of code lines containing
16670 end-of-line comments
16671
16672 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_OFF^
16673 Do not report the number of code lines containing
16674 end-of-line comments
16675
16676 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_ON^
16677 Report the comment percentage in the program text
16678
16679 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_OFF^
16680 Do not report the comment percentage in the program text
16681
16682 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_ON^
16683 Report the number of blank lines
16684
16685 @item ^--no-lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_OFF^
16686 Do not report the number of blank lines
16687
16688 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_ON^
16689 Report the average number of code lines in subprogram bodies, task bodies,
16690 entry bodies and statement sequences in package bodies. The metric is computed
16691 and reported for the whole set of processed Ada sources only.
16692
16693 @item ^--no-lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_OFF^
16694 Do not report the average number of code lines in subprogram bodies,
16695 task bodies, entry bodies and statement sequences in package bodies.
16696
16697 @end table
16698
16699 @node Syntax Metrics Control
16700 @subsubsection Syntax Metrics Control
16701 @cindex Syntax metrics control in @command{gnatmetric}
16702
16703 @noindent
16704 @command{gnatmetric} computes various syntactic metrics for the
16705 outermost unit and for each eligible local unit:
16706
16707 @table @emph
16708 @item LSLOC (``Logical Source Lines Of Code'')
16709 The total number of declarations and the total number of statements
16710
16711 @item Maximal static nesting level of inner program units
16712 According to
16713 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
16714 package, a task unit, a protected unit, a
16715 protected entry, a generic unit, or an explicitly declared subprogram other
16716 than an enumeration literal.''
16717
16718 @item Maximal nesting level of composite syntactic constructs
16719 This corresponds to the notion of the
16720 maximum nesting level in the GNAT built-in style checks
16721 (@pxref{Style Checking})
16722 @end table
16723
16724 @noindent
16725 For the outermost unit in the file, @command{gnatmetric} additionally computes
16726 the following metrics:
16727
16728 @table @emph
16729 @item Public subprograms
16730 This metric is computed for package specifications. It is the
16731 number of subprograms and generic subprograms declared in the visible
16732 part (including the visible part of nested packages, protected objects, and
16733 protected types).
16734
16735 @item All subprograms
16736 This metric is computed for bodies and subunits. The
16737 metric is equal to a total number of subprogram bodies in the compilation
16738 unit.
16739 Neither generic instantiations nor renamings-as-a-body nor body stubs
16740 are counted. Any subprogram body is counted, independently of its nesting
16741 level and enclosing constructs. Generic bodies and bodies of protected
16742 subprograms are counted in the same way as ``usual'' subprogram bodies.
16743
16744 @item Public types
16745 This metric is computed for package specifications and
16746 generic package declarations. It is the total number of types
16747 that can be referenced from outside this compilation unit, plus the
16748 number of types from all the visible parts of all the visible generic
16749 packages. Generic formal types are not counted.  Only types, not subtypes,
16750 are included.
16751
16752 @noindent
16753 Along with the total number of public types, the following
16754 types are counted and reported separately:
16755
16756 @itemize @bullet
16757 @item
16758 Abstract types
16759
16760 @item
16761 Root tagged types (abstract, non-abstract, private, non-private). Type
16762 extensions are @emph{not} counted
16763
16764 @item
16765 Private types (including private extensions)
16766
16767 @item
16768 Task types
16769
16770 @item
16771 Protected types
16772
16773 @end itemize
16774
16775 @item All types
16776 This metric is computed for any compilation unit. It is equal to the total
16777 number of the declarations of different types given in the compilation unit.
16778 The private and the corresponding full type declaration are counted as one
16779 type declaration. Incomplete type declarations and generic formal types
16780 are not counted.
16781 No distinction is made among different kinds of types (abstract,
16782 private etc.); the total number of types is computed and reported.
16783
16784 @end table
16785
16786 @noindent
16787 By default, all the syntax metrics are computed and reported. You can use the
16788 following switches to select specific syntax metrics.
16789
16790 @table @option
16791
16792 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
16793
16794 @ifclear vms
16795 @cindex @option{--no-syntax@var{x}}
16796 @end ifclear
16797
16798 @item ^--syntax-all^/SYNTAX_METRICS=ALL_ON^
16799 Report all the syntax metrics
16800
16801 @item ^--no-syntax-all^/ALL_OFF^
16802 Do not report any of syntax metrics
16803
16804 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS_ON^
16805 Report the total number of declarations
16806
16807 @item ^--no-declarations^/SYNTAX_METRICS=DECLARATIONS_OFF^
16808 Do not report the total number of declarations
16809
16810 @item ^--statements^/SYNTAX_METRICS=STATEMENTS_ON^
16811 Report the total number of statements
16812
16813 @item ^--no-statements^/SYNTAX_METRICS=STATEMENTS_OFF^
16814 Do not report the total number of statements
16815
16816 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_ON^
16817 Report the number of public subprograms in a compilation unit
16818
16819 @item ^--no-public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_OFF^
16820 Do not report the number of public subprograms in a compilation unit
16821
16822 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_ON^
16823 Report the number of all the subprograms in a compilation unit
16824
16825 @item ^--no-all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_OFF^
16826 Do not report the number of all the subprograms in a compilation unit
16827
16828 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES_ON^
16829 Report the number of public types in a compilation unit
16830
16831 @item ^--no-public-types^/SYNTAX_METRICS=PUBLIC_TYPES_OFF^
16832 Do not report the number of public types in a compilation unit
16833
16834 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES_ON^
16835 Report the number of all the types in a compilation unit
16836
16837 @item ^--no-all-types^/SYNTAX_METRICS=ALL_TYPES_OFF^
16838 Do not report the number of all the types in a compilation unit
16839
16840 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_ON^
16841 Report the maximal program unit nesting level
16842
16843 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
16844 Do not report the maximal program unit nesting level
16845
16846 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_ON^
16847 Report the maximal construct nesting level
16848
16849 @item ^--no-construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_OFF^
16850 Do not report the maximal construct nesting level
16851
16852 @end table
16853
16854 @node Complexity Metrics Control
16855 @subsubsection Complexity Metrics Control
16856 @cindex Complexity metrics control in @command{gnatmetric}
16857
16858 @noindent
16859 For a program unit that is an executable body (a subprogram body (including
16860 generic bodies), task body, entry body or a package body containing
16861 its own statement sequence) @command{gnatmetric} computes the following
16862 complexity metrics:
16863
16864 @itemize @bullet
16865 @item
16866 McCabe cyclomatic complexity;
16867
16868 @item
16869 McCabe essential complexity;
16870
16871 @item
16872 maximal loop nesting level
16873
16874 @end itemize
16875
16876 @noindent
16877 The McCabe complexity metrics are defined
16878 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
16879
16880 According to McCabe, both control statements and short-circuit control forms
16881 should be taken into account when computing cyclomatic complexity. For each
16882 body, we compute three metric values:
16883
16884 @itemize @bullet
16885 @item
16886 the complexity introduced by control
16887 statements only, without taking into account short-circuit forms,
16888
16889 @item
16890 the complexity introduced by short-circuit control forms only, and
16891
16892 @item
16893 the total
16894 cyclomatic complexity, which is the sum of these two values.
16895 @end itemize
16896
16897 @noindent
16898 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16899 the code in the exception handlers and in all the nested program units.
16900
16901 By default, all the complexity metrics are computed and reported.
16902 For more fine-grained control you can use
16903 the following switches:
16904
16905 @table @option
16906 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
16907
16908 @ifclear vms
16909 @cindex @option{--no-complexity@var{x}}
16910 @end ifclear
16911
16912 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL_ON^
16913 Report all the complexity metrics
16914
16915 @item ^--no-complexity-all^/COMPLEXITY_METRICS=ALL_OFF^
16916 Do not report any of complexity metrics
16917
16918 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_ON^
16919 Report the McCabe Cyclomatic Complexity
16920
16921 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_OFF^
16922 Do not report the McCabe Cyclomatic Complexity
16923
16924 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_ON^
16925 Report the Essential Complexity
16926
16927 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_OFF^
16928 Do not report the Essential Complexity
16929
16930 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
16931 Report maximal loop nesting level
16932
16933 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_OFF^
16934 Do not report maximal loop nesting level
16935
16936 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_ON^
16937 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
16938 task bodies, entry bodies and statement sequences in package bodies.
16939 The metric is computed and reported for whole set of processed Ada sources
16940 only.
16941
16942 @item ^--no-complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_OFF^
16943 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
16944 bodies, task bodies, entry bodies and statement sequences in package bodies
16945
16946 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
16947 @item ^-ne^/NO_EXITS_AS_GOTOS^
16948 Do not consider @code{exit} statements as @code{goto}s when
16949 computing Essential Complexity
16950
16951 @end table
16952
16953 @node Other gnatmetric Switches
16954 @subsection Other @code{gnatmetric} Switches
16955
16956 @noindent
16957 Additional @command{gnatmetric} switches are as follows:
16958
16959 @table @option
16960 @item ^-files @var{filename}^/FILES=@var{filename}^
16961 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16962 Take the argument source files from the specified file. This file should be an
16963 ordinary text file containing file names separated by spaces or
16964 line breaks. You can use this switch more then once in the same call to
16965 @command{gnatmetric}. You also can combine this switch with
16966 an explicit list of files.
16967
16968 @item ^-v^/VERBOSE^
16969 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16970 Verbose mode;
16971 @command{gnatmetric} generates version information and then
16972 a trace of sources being processed.
16973
16974 @item ^-dv^/DEBUG_OUTPUT^
16975 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
16976 Debug mode;
16977 @command{gnatmetric} generates various messages useful to understand what
16978 happens during the metrics computation
16979
16980 @item ^-q^/QUIET^
16981 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16982 Quiet mode.
16983 @end table
16984
16985 @node Generate project-wide metrics
16986 @subsection Generate project-wide metrics
16987
16988 In order to compute metrics on all units of a given project, you can use
16989 the @command{gnat} driver along with the @option{-P} option:
16990 @smallexample
16991    gnat metric -Pproj
16992 @end smallexample
16993
16994 @noindent
16995 If the project @code{proj} depends upon other projects, you can compute
16996 the metrics on the project closure using the @option{-U} option:
16997 @smallexample
16998    gnat metric -Pproj -U
16999 @end smallexample
17000
17001 @noindent
17002 Finally, if not all the units are relevant to a particular main
17003 program in the project closure, you can generate metrics for the set
17004 of units needed to create a given main program (unit closure) using
17005 the @option{-U} option followed by the name of the main unit:
17006 @smallexample
17007    gnat metric -Pproj -U main
17008 @end smallexample
17009
17010
17011 @c ***********************************
17012 @node File Name Krunching Using gnatkr
17013 @chapter File Name Krunching Using @code{gnatkr}
17014 @findex gnatkr
17015
17016 @noindent
17017 This chapter discusses the method used by the compiler to shorten
17018 the default file names chosen for Ada units so that they do not
17019 exceed the maximum length permitted. It also describes the
17020 @code{gnatkr} utility that can be used to determine the result of
17021 applying this shortening.
17022 @menu
17023 * About gnatkr::
17024 * Using gnatkr::
17025 * Krunching Method::
17026 * Examples of gnatkr Usage::
17027 @end menu
17028
17029 @node About gnatkr
17030 @section About @code{gnatkr}
17031
17032 @noindent
17033 The default file naming rule in GNAT
17034 is that the file name must be derived from
17035 the unit name. The exact default rule is as follows:
17036 @itemize @bullet
17037 @item
17038 Take the unit name and replace all dots by hyphens.
17039 @item
17040 If such a replacement occurs in the
17041 second character position of a name, and the first character is
17042 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17043 then replace the dot by the character
17044 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17045 instead of a minus.
17046 @end itemize
17047 The reason for this exception is to avoid clashes
17048 with the standard names for children of System, Ada, Interfaces,
17049 and GNAT, which use the prefixes
17050 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17051 respectively.
17052
17053 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17054 switch of the compiler activates a ``krunching''
17055 circuit that limits file names to nn characters (where nn is a decimal
17056 integer). For example, using OpenVMS,
17057 where the maximum file name length is
17058 39, the value of nn is usually set to 39, but if you want to generate
17059 a set of files that would be usable if ported to a system with some
17060 different maximum file length, then a different value can be specified.
17061 The default value of 39 for OpenVMS need not be specified.
17062
17063 The @code{gnatkr} utility can be used to determine the krunched name for
17064 a given file, when krunched to a specified maximum length.
17065
17066 @node Using gnatkr
17067 @section Using @code{gnatkr}
17068
17069 @noindent
17070 The @code{gnatkr} command has the form
17071
17072 @ifclear vms
17073 @smallexample
17074 $ gnatkr @var{name} [@var{length}]
17075 @end smallexample
17076 @end ifclear
17077
17078 @ifset vms
17079 @smallexample
17080 $ gnatkr @var{name} /COUNT=nn
17081 @end smallexample
17082 @end ifset
17083
17084 @noindent
17085 @var{name} is the uncrunched file name, derived from the name of the unit
17086 in the standard manner described in the previous section (i.e., in particular
17087 all dots are replaced by hyphens). The file name may or may not have an
17088 extension (defined as a suffix of the form period followed by arbitrary
17089 characters other than period). If an extension is present then it will
17090 be preserved in the output. For example, when krunching @file{hellofile.ads}
17091 to eight characters, the result will be hellofil.ads.
17092
17093 Note: for compatibility with previous versions of @code{gnatkr} dots may
17094 appear in the name instead of hyphens, but the last dot will always be
17095 taken as the start of an extension. So if @code{gnatkr} is given an argument
17096 such as @file{Hello.World.adb} it will be treated exactly as if the first
17097 period had been a hyphen, and for example krunching to eight characters
17098 gives the result @file{hellworl.adb}.
17099
17100 Note that the result is always all lower case (except on OpenVMS where it is
17101 all upper case). Characters of the other case are folded as required.
17102
17103 @var{length} represents the length of the krunched name. The default
17104 when no argument is given is ^8^39^ characters. A length of zero stands for
17105 unlimited, in other words do not chop except for system files where the
17106 implied crunching length is always eight characters.
17107
17108 @noindent
17109 The output is the krunched name. The output has an extension only if the
17110 original argument was a file name with an extension.
17111
17112 @node Krunching Method
17113 @section Krunching Method
17114
17115 @noindent
17116 The initial file name is determined by the name of the unit that the file
17117 contains. The name is formed by taking the full expanded name of the
17118 unit and replacing the separating dots with hyphens and
17119 using ^lowercase^uppercase^
17120 for all letters, except that a hyphen in the second character position is
17121 replaced by a ^tilde^dollar sign^ if the first character is
17122 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
17123 The extension is @code{.ads} for a
17124 specification and @code{.adb} for a body.
17125 Krunching does not affect the extension, but the file name is shortened to
17126 the specified length by following these rules:
17127
17128 @itemize @bullet
17129 @item
17130 The name is divided into segments separated by hyphens, tildes or
17131 underscores and all hyphens, tildes, and underscores are
17132 eliminated. If this leaves the name short enough, we are done.
17133
17134 @item
17135 If the name is too long, the longest segment is located (left-most
17136 if there are two of equal length), and shortened by dropping
17137 its last character. This is repeated until the name is short enough.
17138
17139 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
17140 to fit the name into 8 characters as required by some operating systems.
17141
17142 @smallexample
17143 our-strings-wide_fixed 22
17144 our strings wide fixed 19
17145 our string  wide fixed 18
17146 our strin   wide fixed 17
17147 our stri    wide fixed 16
17148 our stri    wide fixe  15
17149 our str     wide fixe  14
17150 our str     wid  fixe  13
17151 our str     wid  fix   12
17152 ou  str     wid  fix   11
17153 ou  st      wid  fix   10
17154 ou  st      wi   fix   9
17155 ou  st      wi   fi    8
17156 Final file name: oustwifi.adb
17157 @end smallexample
17158
17159 @item
17160 The file names for all predefined units are always krunched to eight
17161 characters. The krunching of these predefined units uses the following
17162 special prefix replacements:
17163
17164 @table @file
17165 @item ada-
17166 replaced by @file{^a^A^-}
17167
17168 @item gnat-
17169 replaced by @file{^g^G^-}
17170
17171 @item interfaces-
17172 replaced by @file{^i^I^-}
17173
17174 @item system-
17175 replaced by @file{^s^S^-}
17176 @end table
17177
17178 These system files have a hyphen in the second character position. That
17179 is why normal user files replace such a character with a
17180 ^tilde^dollar sign^, to
17181 avoid confusion with system file names.
17182
17183 As an example of this special rule, consider
17184 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
17185
17186 @smallexample
17187 ada-strings-wide_fixed 22
17188 a-  strings wide fixed 18
17189 a-  string  wide fixed 17
17190 a-  strin   wide fixed 16
17191 a-  stri    wide fixed 15
17192 a-  stri    wide fixe  14
17193 a-  str     wide fixe  13
17194 a-  str     wid  fixe  12
17195 a-  str     wid  fix   11
17196 a-  st      wid  fix   10
17197 a-  st      wi   fix   9
17198 a-  st      wi   fi    8
17199 Final file name: a-stwifi.adb
17200 @end smallexample
17201 @end itemize
17202
17203 Of course no file shortening algorithm can guarantee uniqueness over all
17204 possible unit names, and if file name krunching is used then it is your
17205 responsibility to ensure that no name clashes occur. The utility
17206 program @code{gnatkr} is supplied for conveniently determining the
17207 krunched name of a file.
17208
17209 @node Examples of gnatkr Usage
17210 @section Examples of @code{gnatkr} Usage
17211
17212 @smallexample
17213 @iftex
17214 @leftskip=0cm
17215 @end iftex
17216 @ifclear vms
17217 $ gnatkr very_long_unit_name.ads      --> velounna.ads
17218 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
17219 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
17220 $ gnatkr grandparent-parent-child     --> grparchi
17221 @end ifclear
17222 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
17223 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
17224 @end smallexample
17225
17226 @node Preprocessing Using gnatprep
17227 @chapter Preprocessing Using @code{gnatprep}
17228 @findex gnatprep
17229
17230 @noindent
17231 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
17232 preprocessing.
17233 Although designed for use with GNAT, @code{gnatprep} does not depend on any
17234 special GNAT features.
17235 For further discussion of conditional compilation in general, see
17236 @ref{Conditional Compilation}.
17237
17238 @menu
17239 * Using gnatprep::
17240 * Switches for gnatprep::
17241 * Form of Definitions File::
17242 * Form of Input Text for gnatprep::
17243 @end menu
17244
17245
17246 @node Using gnatprep
17247 @section Using @code{gnatprep}
17248
17249 @noindent
17250 To call @code{gnatprep} use
17251
17252 @smallexample
17253 $ gnatprep [switches] infile outfile [deffile]
17254 @end smallexample
17255
17256 @noindent
17257 where
17258 @table @code
17259 @item switches
17260 is an optional sequence of switches as described in the next section.
17261
17262 @item infile
17263 is the full name of the input file, which is an Ada source
17264 file containing preprocessor directives.
17265
17266 @item outfile
17267 is the full name of the output file, which is an Ada source
17268 in standard Ada form. When used with GNAT, this file name will
17269 normally have an ads or adb suffix.
17270
17271 @item deffile
17272 is the full name of a text file containing definitions of
17273 symbols to be referenced by the preprocessor. This argument is
17274 optional, and can be replaced by the use of the @option{-D} switch.
17275
17276 @end table
17277
17278 @node Switches for gnatprep
17279 @section Switches for @code{gnatprep}
17280
17281 @table @option
17282 @c !sort!
17283
17284 @item ^-b^/BLANK_LINES^
17285 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
17286 Causes both preprocessor lines and the lines deleted by
17287 preprocessing to be replaced by blank lines in the output source file,
17288 preserving line numbers in the output file.
17289
17290 @item ^-c^/COMMENTS^
17291 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
17292 Causes both preprocessor lines and the lines deleted
17293 by preprocessing to be retained in the output source as comments marked
17294 with the special string @code{"--! "}. This option will result in line numbers
17295 being preserved in the output file.
17296
17297 @item ^-C^/REPLACE_IN_COMMENTS^
17298 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
17299 Causes comments to be scanned. Normally comments are ignored by gnatprep.
17300 If this option is specified, then comments are scanned and any $symbol
17301 substitutions performed as in program text. This is particularly useful
17302 when structured comments are used (e.g., when writing programs in the
17303 SPARK dialect of Ada). Note that this switch is not available when
17304 doing integrated preprocessing (it would be useless in this context
17305 since comments are ignored by the compiler in any case).
17306
17307 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
17308 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
17309 Defines a new symbol, associated with value. If no value is given on the
17310 command line, then symbol is considered to be @code{True}. This switch
17311 can be used in place of a definition file.
17312
17313 @ifset vms
17314 @item /REMOVE
17315 @cindex @option{/REMOVE} (@command{gnatprep})
17316 This is the default setting which causes lines deleted by preprocessing
17317 to be entirely removed from the output file.
17318 @end ifset
17319
17320 @item ^-r^/REFERENCE^
17321 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
17322 Causes a @code{Source_Reference} pragma to be generated that
17323 references the original input file, so that error messages will use
17324 the file name of this original file. The use of this switch implies
17325 that preprocessor lines are not to be removed from the file, so its
17326 use will force @option{^-b^/BLANK_LINES^} mode if
17327 @option{^-c^/COMMENTS^}
17328 has not been specified explicitly.
17329
17330 Note that if the file to be preprocessed contains multiple units, then
17331 it will be necessary to @code{gnatchop} the output file from
17332 @code{gnatprep}. If a @code{Source_Reference} pragma is present
17333 in the preprocessed file, it will be respected by
17334 @code{gnatchop ^-r^/REFERENCE^}
17335 so that the final chopped files will correctly refer to the original
17336 input source file for @code{gnatprep}.
17337
17338 @item ^-s^/SYMBOLS^
17339 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
17340 Causes a sorted list of symbol names and values to be
17341 listed on the standard output file.
17342
17343 @item ^-u^/UNDEFINED^
17344 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
17345 Causes undefined symbols to be treated as having the value FALSE in the context
17346 of a preprocessor test. In the absence of this option, an undefined symbol in
17347 a @code{#if} or @code{#elsif} test will be treated as an error.
17348
17349 @end table
17350
17351 @ifclear vms
17352 @noindent
17353 Note: if neither @option{-b} nor @option{-c} is present,
17354 then preprocessor lines and
17355 deleted lines are completely removed from the output, unless -r is
17356 specified, in which case -b is assumed.
17357 @end ifclear
17358
17359 @node Form of Definitions File
17360 @section Form of Definitions File
17361
17362 @noindent
17363 The definitions file contains lines of the form
17364
17365 @smallexample
17366 symbol := value
17367 @end smallexample
17368
17369 @noindent
17370 where symbol is an identifier, following normal Ada (case-insensitive)
17371 rules for its syntax, and value is one of the following:
17372
17373 @itemize @bullet
17374 @item
17375 Empty, corresponding to a null substitution
17376 @item
17377 A string literal using normal Ada syntax
17378 @item
17379 Any sequence of characters from the set
17380 (letters, digits, period, underline).
17381 @end itemize
17382
17383 @noindent
17384 Comment lines may also appear in the definitions file, starting with
17385 the usual @code{--},
17386 and comments may be added to the definitions lines.
17387
17388 @node Form of Input Text for gnatprep
17389 @section Form of Input Text for @code{gnatprep}
17390
17391 @noindent
17392 The input text may contain preprocessor conditional inclusion lines,
17393 as well as general symbol substitution sequences.
17394
17395 The preprocessor conditional inclusion commands have the form
17396
17397 @smallexample
17398 @group
17399 @cartouche
17400 #if @i{expression} [then]
17401    lines
17402 #elsif @i{expression} [then]
17403    lines
17404 #elsif @i{expression} [then]
17405    lines
17406 @dots{}
17407 #else
17408    lines
17409 #end if;
17410 @end cartouche
17411 @end group
17412 @end smallexample
17413
17414 @noindent
17415 In this example, @i{expression} is defined by the following grammar:
17416 @smallexample
17417 @i{expression} ::=  <symbol>
17418 @i{expression} ::=  <symbol> = "<value>"
17419 @i{expression} ::=  <symbol> = <symbol>
17420 @i{expression} ::=  <symbol> 'Defined
17421 @i{expression} ::=  not @i{expression}
17422 @i{expression} ::=  @i{expression} and @i{expression}
17423 @i{expression} ::=  @i{expression} or @i{expression}
17424 @i{expression} ::=  @i{expression} and then @i{expression}
17425 @i{expression} ::=  @i{expression} or else @i{expression}
17426 @i{expression} ::=  ( @i{expression} )
17427 @end smallexample
17428
17429 @noindent
17430 For the first test (@i{expression} ::= <symbol>) the symbol must have
17431 either the value true or false, that is to say the right-hand of the
17432 symbol definition must be one of the (case-insensitive) literals
17433 @code{True} or @code{False}. If the value is true, then the
17434 corresponding lines are included, and if the value is false, they are
17435 excluded.
17436
17437 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
17438 the symbol has been defined in the definition file or by a @option{-D}
17439 switch on the command line. Otherwise, the test is false.
17440
17441 The equality tests are case insensitive, as are all the preprocessor lines.
17442
17443 If the symbol referenced is not defined in the symbol definitions file,
17444 then the effect depends on whether or not switch @option{-u}
17445 is specified. If so, then the symbol is treated as if it had the value
17446 false and the test fails. If this switch is not specified, then
17447 it is an error to reference an undefined symbol. It is also an error to
17448 reference a symbol that is defined with a value other than @code{True}
17449 or @code{False}.
17450
17451 The use of the @code{not} operator inverts the sense of this logical test.
17452 The @code{not} operator cannot be combined with the @code{or} or @code{and}
17453 operators, without parentheses. For example, "if not X or Y then" is not
17454 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
17455
17456 The @code{then} keyword is optional as shown
17457
17458 The @code{#} must be the first non-blank character on a line, but
17459 otherwise the format is free form. Spaces or tabs may appear between
17460 the @code{#} and the keyword. The keywords and the symbols are case
17461 insensitive as in normal Ada code. Comments may be used on a
17462 preprocessor line, but other than that, no other tokens may appear on a
17463 preprocessor line. Any number of @code{elsif} clauses can be present,
17464 including none at all. The @code{else} is optional, as in Ada.
17465
17466 The @code{#} marking the start of a preprocessor line must be the first
17467 non-blank character on the line, i.e., it must be preceded only by
17468 spaces or horizontal tabs.
17469
17470 Symbol substitution outside of preprocessor lines is obtained by using
17471 the sequence
17472
17473 @smallexample
17474 $symbol
17475 @end smallexample
17476
17477 @noindent
17478 anywhere within a source line, except in a comment or within a
17479 string literal. The identifier
17480 following the @code{$} must match one of the symbols defined in the symbol
17481 definition file, and the result is to substitute the value of the
17482 symbol in place of @code{$symbol} in the output file.
17483
17484 Note that although the substitution of strings within a string literal
17485 is not possible, it is possible to have a symbol whose defined value is
17486 a string literal. So instead of setting XYZ to @code{hello} and writing:
17487
17488 @smallexample
17489 Header : String := "$XYZ";
17490 @end smallexample
17491
17492 @noindent
17493 you should set XYZ to @code{"hello"} and write:
17494
17495 @smallexample
17496 Header : String := $XYZ;
17497 @end smallexample
17498
17499 @noindent
17500 and then the substitution will occur as desired.
17501
17502 @ifset vms
17503 @node The GNAT Run-Time Library Builder gnatlbr
17504 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
17505 @findex gnatlbr
17506 @cindex Library builder
17507
17508 @noindent
17509 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
17510 supplied configuration pragmas.
17511
17512 @menu
17513 * Running gnatlbr::
17514 * Switches for gnatlbr::
17515 * Examples of gnatlbr Usage::
17516 @end menu
17517
17518 @node Running gnatlbr
17519 @section Running @code{gnatlbr}
17520
17521 @noindent
17522 The @code{gnatlbr} command has the form
17523
17524 @smallexample
17525 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
17526 @end smallexample
17527
17528 @node Switches for gnatlbr
17529 @section Switches for @code{gnatlbr}
17530
17531 @noindent
17532 @code{gnatlbr} recognizes the following switches:
17533
17534 @table @option
17535 @c !sort!
17536 @item /CREATE=directory
17537 @cindex @code{/CREATE} (@code{gnatlbr})
17538      Create the new run-time library in the specified directory.
17539
17540 @item /SET=directory
17541 @cindex @code{/SET} (@code{gnatlbr})
17542      Make the library in the specified directory the current run-time
17543      library.
17544
17545 @item /DELETE=directory
17546 @cindex @code{/DELETE} (@code{gnatlbr})
17547      Delete the run-time library in the specified directory.
17548
17549 @item /CONFIG=file
17550 @cindex @code{/CONFIG} (@code{gnatlbr})
17551      With /CREATE:
17552      Use the configuration pragmas in the specified file when building
17553      the library.
17554
17555      With /SET:
17556      Use the configuration pragmas in the specified file when compiling.
17557
17558 @end table
17559
17560 @node Examples of gnatlbr Usage
17561 @section Example of @code{gnatlbr} Usage
17562
17563 @smallexample
17564 Contents of VAXFLOAT.ADC:
17565 pragma Float_Representation (VAX_Float);
17566
17567 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
17568
17569 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
17570
17571 @end smallexample
17572 @end ifset
17573
17574 @node The GNAT Library Browser gnatls
17575 @chapter The GNAT Library Browser @code{gnatls}
17576 @findex gnatls
17577 @cindex Library browser
17578
17579 @noindent
17580 @code{gnatls} is a tool that outputs information about compiled
17581 units. It gives the relationship between objects, unit names and source
17582 files. It can also be used to check the source dependencies of a unit
17583 as well as various characteristics.
17584
17585 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
17586 driver (see @ref{The GNAT Driver and Project Files}).
17587
17588 @menu
17589 * Running gnatls::
17590 * Switches for gnatls::
17591 * Examples of gnatls Usage::
17592 @end menu
17593
17594 @node Running gnatls
17595 @section Running @code{gnatls}
17596
17597 @noindent
17598 The @code{gnatls} command has the form
17599
17600 @smallexample
17601 $ gnatls switches @var{object_or_ali_file}
17602 @end smallexample
17603
17604 @noindent
17605 The main argument is the list of object or @file{ali} files
17606 (@pxref{The Ada Library Information Files})
17607 for which information is requested.
17608
17609 In normal mode, without additional option, @code{gnatls} produces a
17610 four-column listing. Each line represents information for a specific
17611 object. The first column gives the full path of the object, the second
17612 column gives the name of the principal unit in this object, the third
17613 column gives the status of the source and the fourth column gives the
17614 full path of the source representing this unit.
17615 Here is a simple example of use:
17616
17617 @smallexample
17618 $ gnatls *.o
17619 ^./^[]^demo1.o            demo1            DIF demo1.adb
17620 ^./^[]^demo2.o            demo2             OK demo2.adb
17621 ^./^[]^hello.o            h1                OK hello.adb
17622 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
17623 ^./^[]^instr.o            instr             OK instr.adb
17624 ^./^[]^tef.o              tef              DIF tef.adb
17625 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
17626 ^./^[]^tgef.o             tgef             DIF tgef.adb
17627 @end smallexample
17628
17629 @noindent
17630 The first line can be interpreted as follows: the main unit which is
17631 contained in
17632 object file @file{demo1.o} is demo1, whose main source is in
17633 @file{demo1.adb}. Furthermore, the version of the source used for the
17634 compilation of demo1 has been modified (DIF). Each source file has a status
17635 qualifier which can be:
17636
17637 @table @code
17638 @item OK (unchanged)
17639 The version of the source file used for the compilation of the
17640 specified unit corresponds exactly to the actual source file.
17641
17642 @item MOK (slightly modified)
17643 The version of the source file used for the compilation of the
17644 specified unit differs from the actual source file but not enough to
17645 require recompilation. If you use gnatmake with the qualifier
17646 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
17647 MOK will not be recompiled.
17648
17649 @item DIF (modified)
17650 No version of the source found on the path corresponds to the source
17651 used to build this object.
17652
17653 @item ??? (file not found)
17654 No source file was found for this unit.
17655
17656 @item HID (hidden,  unchanged version not first on PATH)
17657 The version of the source that corresponds exactly to the source used
17658 for compilation has been found on the path but it is hidden by another
17659 version of the same source that has been modified.
17660
17661 @end table
17662
17663 @node Switches for gnatls
17664 @section Switches for @code{gnatls}
17665
17666 @noindent
17667 @code{gnatls} recognizes the following switches:
17668
17669 @table @option
17670 @c !sort!
17671 @cindex @option{--version} @command{gnatls}
17672 Display Copyright and version, then exit disregarding all other options.
17673
17674 @item --help
17675 @cindex @option{--help} @command{gnatls}
17676 If @option{--version} was not used, display usage, then exit disregarding
17677 all other options.
17678
17679 @item ^-a^/ALL_UNITS^
17680 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
17681 Consider all units, including those of the predefined Ada library.
17682 Especially useful with @option{^-d^/DEPENDENCIES^}.
17683
17684 @item ^-d^/DEPENDENCIES^
17685 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
17686 List sources from which specified units depend on.
17687
17688 @item ^-h^/OUTPUT=OPTIONS^
17689 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
17690 Output the list of options.
17691
17692 @item ^-o^/OUTPUT=OBJECTS^
17693 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
17694 Only output information about object files.
17695
17696 @item ^-s^/OUTPUT=SOURCES^
17697 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
17698 Only output information about source files.
17699
17700 @item ^-u^/OUTPUT=UNITS^
17701 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
17702 Only output information about compilation units.
17703
17704 @item ^-files^/FILES^=@var{file}
17705 @cindex @option{^-files^/FILES^} (@code{gnatls})
17706 Take as arguments the files listed in text file @var{file}.
17707 Text file @var{file} may contain empty lines that are ignored.
17708 Each nonempty line should contain the name of an existing file.
17709 Several such switches may be specified simultaneously.
17710
17711 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17712 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
17713 @itemx ^-I^/SEARCH=^@var{dir}
17714 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
17715 @itemx -nostdinc
17716 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
17717 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
17718 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
17719 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
17720 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
17721 flags (@pxref{Switches for gnatmake}).
17722
17723 @item --RTS=@var{rts-path}
17724 @cindex @option{--RTS} (@code{gnatls})
17725 Specifies the default location of the runtime library. Same meaning as the
17726 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
17727
17728 @item ^-v^/OUTPUT=VERBOSE^
17729 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
17730 Verbose mode. Output the complete source, object and project paths. Do not use
17731 the default column layout but instead use long format giving as much as
17732 information possible on each requested units, including special
17733 characteristics such as:
17734
17735 @table @code
17736 @item  Preelaborable
17737 The unit is preelaborable in the Ada sense.
17738
17739 @item No_Elab_Code
17740 No elaboration code has been produced by the compiler for this unit.
17741
17742 @item Pure
17743 The unit is pure in the Ada sense.
17744
17745 @item Elaborate_Body
17746 The unit contains a pragma Elaborate_Body.
17747
17748 @item Remote_Types
17749 The unit contains a pragma Remote_Types.
17750
17751 @item Shared_Passive
17752 The unit contains a pragma Shared_Passive.
17753
17754 @item Predefined
17755 This unit is part of the predefined environment and cannot be modified
17756 by the user.
17757
17758 @item Remote_Call_Interface
17759 The unit contains a pragma Remote_Call_Interface.
17760
17761 @end table
17762
17763 @end table
17764
17765 @node Examples of gnatls Usage
17766 @section Example of @code{gnatls} Usage
17767 @ifclear vms
17768
17769 @noindent
17770 Example of using the verbose switch. Note how the source and
17771 object paths are affected by the -I switch.
17772
17773 @smallexample
17774 $ gnatls -v -I.. demo1.o
17775
17776 GNATLS 5.03w (20041123-34)
17777 Copyright 1997-2004 Free Software Foundation, Inc.
17778
17779 Source Search Path:
17780    <Current_Directory>
17781    ../
17782    /home/comar/local/adainclude/
17783
17784 Object Search Path:
17785    <Current_Directory>
17786    ../
17787    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17788
17789 Project Search Path:
17790    <Current_Directory>
17791    /home/comar/local/lib/gnat/
17792
17793 ./demo1.o
17794    Unit =>
17795      Name   => demo1
17796      Kind   => subprogram body
17797      Flags  => No_Elab_Code
17798      Source => demo1.adb    modified
17799 @end smallexample
17800
17801 @noindent
17802 The following is an example of use of the dependency list.
17803 Note the use of the -s switch
17804 which gives a straight list of source files. This can be useful for
17805 building specialized scripts.
17806
17807 @smallexample
17808 $ gnatls -d demo2.o
17809 ./demo2.o   demo2        OK demo2.adb
17810                          OK gen_list.ads
17811                          OK gen_list.adb
17812                          OK instr.ads
17813                          OK instr-child.ads
17814
17815 $ gnatls -d -s -a demo1.o
17816 demo1.adb
17817 /home/comar/local/adainclude/ada.ads
17818 /home/comar/local/adainclude/a-finali.ads
17819 /home/comar/local/adainclude/a-filico.ads
17820 /home/comar/local/adainclude/a-stream.ads
17821 /home/comar/local/adainclude/a-tags.ads
17822 gen_list.ads
17823 gen_list.adb
17824 /home/comar/local/adainclude/gnat.ads
17825 /home/comar/local/adainclude/g-io.ads
17826 instr.ads
17827 /home/comar/local/adainclude/system.ads
17828 /home/comar/local/adainclude/s-exctab.ads
17829 /home/comar/local/adainclude/s-finimp.ads
17830 /home/comar/local/adainclude/s-finroo.ads
17831 /home/comar/local/adainclude/s-secsta.ads
17832 /home/comar/local/adainclude/s-stalib.ads
17833 /home/comar/local/adainclude/s-stoele.ads
17834 /home/comar/local/adainclude/s-stratt.ads
17835 /home/comar/local/adainclude/s-tasoli.ads
17836 /home/comar/local/adainclude/s-unstyp.ads
17837 /home/comar/local/adainclude/unchconv.ads
17838 @end smallexample
17839 @end ifclear
17840
17841 @ifset vms
17842 @smallexample
17843 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17844
17845 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17846 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17847 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17848 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17849 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17850 demo1.adb
17851 gen_list.ads
17852 gen_list.adb
17853 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17854 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17855 instr.ads
17856 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17857 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17858 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17859 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17860 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17861 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17862 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17863 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17864 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17865 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17866 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17867 @end smallexample
17868 @end ifset
17869
17870 @node Cleaning Up Using gnatclean
17871 @chapter Cleaning Up Using @code{gnatclean}
17872 @findex gnatclean
17873 @cindex Cleaning tool
17874
17875 @noindent
17876 @code{gnatclean} is a tool that allows the deletion of files produced by the
17877 compiler, binder and linker, including ALI files, object files, tree files,
17878 expanded source files, library files, interface copy source files, binder
17879 generated files and executable files.
17880
17881 @menu
17882 * Running gnatclean::
17883 * Switches for gnatclean::
17884 @c * Examples of gnatclean Usage::
17885 @end menu
17886
17887 @node Running gnatclean
17888 @section Running @code{gnatclean}
17889
17890 @noindent
17891 The @code{gnatclean} command has the form:
17892
17893 @smallexample
17894 $ gnatclean switches @var{names}
17895 @end smallexample
17896
17897 @noindent
17898 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17899 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17900 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17901
17902 @noindent
17903 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17904 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17905 the linker. In informative-only mode, specified by switch
17906 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17907 normal mode is listed, but no file is actually deleted.
17908
17909 @node Switches for gnatclean
17910 @section Switches for @code{gnatclean}
17911
17912 @noindent
17913 @code{gnatclean} recognizes the following switches:
17914
17915 @table @option
17916 @c !sort!
17917 @cindex @option{--version} @command{gnatclean}
17918 Display Copyright and version, then exit disregarding all other options.
17919
17920 @item --help
17921 @cindex @option{--help} @command{gnatclean}
17922 If @option{--version} was not used, display usage, then exit disregarding
17923 all other options.
17924
17925 @item ^-c^/COMPILER_FILES_ONLY^
17926 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17927 Only attempt to delete the files produced by the compiler, not those produced
17928 by the binder or the linker. The files that are not to be deleted are library
17929 files, interface copy files, binder generated files and executable files.
17930
17931 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17932 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17933 Indicate that ALI and object files should normally be found in directory
17934 @var{dir}.
17935
17936 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17937 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17938 When using project files, if some errors or warnings are detected during
17939 parsing and verbose mode is not in effect (no use of switch
17940 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17941 file, rather than its simple file name.
17942
17943 @item ^-h^/HELP^
17944 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17945 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17946
17947 @item ^-n^/NODELETE^
17948 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17949 Informative-only mode. Do not delete any files. Output the list of the files
17950 that would have been deleted if this switch was not specified.
17951
17952 @item ^-P^/PROJECT_FILE=^@var{project}
17953 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17954 Use project file @var{project}. Only one such switch can be used.
17955 When cleaning a project file, the files produced by the compilation of the
17956 immediate sources or inherited sources of the project files are to be
17957 deleted. This is not depending on the presence or not of executable names
17958 on the command line.
17959
17960 @item ^-q^/QUIET^
17961 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17962 Quiet output. If there are no errors, do not output anything, except in
17963 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17964 (switch ^-n^/NODELETE^).
17965
17966 @item ^-r^/RECURSIVE^
17967 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17968 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17969 clean all imported and extended project files, recursively. If this switch
17970 is not specified, only the files related to the main project file are to be
17971 deleted. This switch has no effect if no project file is specified.
17972
17973 @item ^-v^/VERBOSE^
17974 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17975 Verbose mode.
17976
17977 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17978 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17979 Indicates the verbosity of the parsing of GNAT project files.
17980 @xref{Switches Related to Project Files}.
17981
17982 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17983 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17984 Indicates that external variable @var{name} has the value @var{value}.
17985 The Project Manager will use this value for occurrences of
17986 @code{external(name)} when parsing the project file.
17987 @xref{Switches Related to Project Files}.
17988
17989 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17990 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17991 When searching for ALI and object files, look in directory
17992 @var{dir}.
17993
17994 @item ^-I^/SEARCH=^@var{dir}
17995 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17996 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17997
17998 @item ^-I-^/NOCURRENT_DIRECTORY^
17999 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18000 @cindex Source files, suppressing search
18001 Do not look for ALI or object files in the directory
18002 where @code{gnatclean} was invoked.
18003
18004 @end table
18005
18006 @c @node Examples of gnatclean Usage
18007 @c @section Examples of @code{gnatclean} Usage
18008
18009 @ifclear vms
18010 @node GNAT and Libraries
18011 @chapter GNAT and Libraries
18012 @cindex Library, building, installing, using
18013
18014 @noindent
18015 This chapter describes how to build and use libraries with GNAT, and also shows
18016 how to recompile the GNAT run-time library. You should be familiar with the
18017 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18018 chapter.
18019
18020 @menu
18021 * Introduction to Libraries in GNAT::
18022 * General Ada Libraries::
18023 * Stand-alone Ada Libraries::
18024 * Rebuilding the GNAT Run-Time Library::
18025 @end menu
18026
18027 @node Introduction to Libraries in GNAT
18028 @section Introduction to Libraries in GNAT
18029
18030 @noindent
18031 A library is, conceptually, a collection of objects which does not have its
18032 own main thread of execution, but rather provides certain services to the
18033 applications that use it. A library can be either statically linked with the
18034 application, in which case its code is directly included in the application,
18035 or, on platforms that support it, be dynamically linked, in which case
18036 its code is shared by all applications making use of this library.
18037
18038 GNAT supports both types of libraries.
18039 In the static case, the compiled code can be provided in different ways. The
18040 simplest approach is to provide directly the set of objects resulting from
18041 compilation of the library source files. Alternatively, you can group the
18042 objects into an archive using whatever commands are provided by the operating
18043 system. For the latter case, the objects are grouped into a shared library.
18044
18045 In the GNAT environment, a library has three types of components:
18046 @itemize @bullet
18047 @item
18048 Source files.
18049 @item
18050 @file{ALI} files.
18051 @xref{The Ada Library Information Files}.
18052 @item
18053 Object files, an archive or a shared library.
18054 @end itemize
18055
18056 @noindent
18057 A GNAT library may expose all its source files, which is useful for
18058 documentation purposes. Alternatively, it may expose only the units needed by
18059 an external user to make use of the library. That is to say, the specs
18060 reflecting the library services along with all the units needed to compile
18061 those specs, which can include generic bodies or any body implementing an
18062 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18063 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18064
18065 All compilation units comprising an application, including those in a library,
18066 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18067 computes the elaboration order from the @file{ALI} files and this is why they
18068 constitute a mandatory part of GNAT libraries. Except in the case of
18069 @emph{stand-alone libraries}, where a specific library elaboration routine is
18070 produced independently of the application(s) using the library.
18071
18072 @node General Ada Libraries
18073 @section General Ada Libraries
18074
18075 @menu
18076 * Building a library::
18077 * Installing a library::
18078 * Using a library::
18079 @end menu
18080
18081 @node Building a library
18082 @subsection Building a library
18083
18084 @noindent
18085 The easiest way to build a library is to use the Project Manager,
18086 which supports a special type of project called a @emph{Library Project}
18087 (@pxref{Library Projects}).
18088
18089 A project is considered a library project, when two project-level attributes
18090 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
18091 control different aspects of library configuration, additional optional
18092 project-level attributes can be specified:
18093 @table @code
18094 @item Library_Kind
18095 This attribute controls whether the library is to be static or dynamic
18096
18097 @item Library_Version
18098 This attribute specifies the library version; this value is used
18099 during dynamic linking of shared libraries to determine if the currently
18100 installed versions of the binaries are compatible.
18101
18102 @item Library_Options
18103 @item Library_GCC
18104 These attributes specify additional low-level options to be used during
18105 library generation, and redefine the actual application used to generate
18106 library.
18107 @end table
18108
18109 @noindent
18110 The GNAT Project Manager takes full care of the library maintenance task,
18111 including recompilation of the source files for which objects do not exist
18112 or are not up to date, assembly of the library archive, and installation of
18113 the library (i.e., copying associated source, object and @file{ALI} files
18114 to the specified location).
18115
18116 Here is a simple library project file:
18117 @smallexample @c ada
18118 project My_Lib is
18119    for Source_Dirs use ("src1", "src2");
18120    for Object_Dir use "obj";
18121    for Library_Name use "mylib";
18122    for Library_Dir use "lib";
18123    for Library_Kind use "dynamic";
18124 end My_lib;
18125 @end smallexample
18126
18127 @noindent
18128 and the compilation command to build and install the library:
18129
18130 @smallexample @c ada
18131   $ gnatmake -Pmy_lib
18132 @end smallexample
18133
18134 @noindent
18135 It is not entirely trivial to perform manually all the steps required to
18136 produce a library. We recommend that you use the GNAT Project Manager
18137 for this task. In special cases where this is not desired, the necessary
18138 steps are discussed below.
18139
18140 There are various possibilities for compiling the units that make up the
18141 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
18142 with a conventional script. For simple libraries, it is also possible to create
18143 a dummy main program which depends upon all the packages that comprise the
18144 interface of the library. This dummy main program can then be given to
18145 @command{gnatmake}, which will ensure that all necessary objects are built.
18146
18147 After this task is accomplished, you should follow the standard procedure
18148 of the underlying operating system to produce the static or shared library.
18149
18150 Here is an example of such a dummy program:
18151 @smallexample @c ada
18152 @group
18153 with My_Lib.Service1;
18154 with My_Lib.Service2;
18155 with My_Lib.Service3;
18156 procedure My_Lib_Dummy is
18157 begin
18158    null;
18159 end;
18160 @end group
18161 @end smallexample
18162
18163 @noindent
18164 Here are the generic commands that will build an archive or a shared library.
18165
18166 @smallexample
18167 # compiling the library
18168 $ gnatmake -c my_lib_dummy.adb
18169
18170 # we don't need the dummy object itself
18171 $ rm my_lib_dummy.o my_lib_dummy.ali
18172
18173 # create an archive with the remaining objects
18174 $ ar rc libmy_lib.a *.o
18175 # some systems may require "ranlib" to be run as well
18176
18177 # or create a shared library
18178 $ gcc -shared -o libmy_lib.so *.o
18179 # some systems may require the code to have been compiled with -fPIC
18180
18181 # remove the object files that are now in the library
18182 $ rm *.o
18183
18184 # Make the ALI files read-only so that gnatmake will not try to
18185 # regenerate the objects that are in the library
18186 $ chmod -w *.ali
18187 @end smallexample
18188
18189 @noindent
18190 Please note that the library must have a name of the form @file{libxxx.a} or
18191 @file{libxxx.so} (or @file{libxxx.dll} on Windows) in order to be accessed by
18192 the directive @option{-lxxx} at link time.
18193
18194 @node Installing a library
18195 @subsection Installing a library
18196 @cindex @code{ADA_PROJECT_PATH}
18197
18198 @noindent
18199 If you use project files, library installation is part of the library build
18200 process. Thus no further action is needed in order to make use of the
18201 libraries that are built as part of the general application build. A usable
18202 version of the library is installed in the directory specified by the
18203 @code{Library_Dir} attribute of the library project file.
18204
18205 You may want to install a library in a context different from where the library
18206 is built. This situation arises with third party suppliers, who may want
18207 to distribute a library in binary form where the user is not expected to be
18208 able to recompile the library. The simplest option in this case is to provide
18209 a project file slightly different from the one used to build the library, by
18210 using the @code{externally_built} attribute. For instance, the project
18211 file used to build the library in the previous section can be changed into the
18212 following one when the library is installed:
18213
18214 @smallexample @c projectfile
18215 project My_Lib is
18216    for Source_Dirs use ("src1", "src2");
18217    for Library_Name use "mylib";
18218    for Library_Dir use "lib";
18219    for Library_Kind use "dynamic";
18220    for Externally_Built use "true";
18221 end My_lib;
18222 @end smallexample
18223
18224 @noindent
18225 This project file assumes that the directories @file{src1},
18226 @file{src2}, and @file{lib} exist in
18227 the directory containing the project file. The @code{externally_built}
18228 attribute makes it clear to the GNAT builder that it should not attempt to
18229 recompile any of the units from this library. It allows the library provider to
18230 restrict the source set to the minimum necessary for clients to make use of the
18231 library as described in the first section of this chapter. It is the
18232 responsibility of the library provider to install the necessary sources, ALI
18233 files and libraries in the directories mentioned in the project file. For
18234 convenience, the user's library project file should be installed in a location
18235 that will be searched automatically by the GNAT
18236 builder. These are the directories referenced in the @env{ADA_PROJECT_PATH}
18237 environment variable (@pxref{Importing Projects}), and also the default GNAT
18238 library location that can be queried with @command{gnatls -v} and is usually of
18239 the form $gnat_install_root/lib/gnat.
18240
18241 When project files are not an option, it is also possible, but not recommended,
18242 to install the library so that the sources needed to use the library are on the
18243 Ada source path and the ALI files & libraries be on the Ada Object path (see
18244 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
18245 administrator can place general-purpose libraries in the default compiler
18246 paths, by specifying the libraries' location in the configuration files
18247 @file{ada_source_path} and @file{ada_object_path}. These configuration files
18248 must be located in the GNAT installation tree at the same place as the gcc spec
18249 file. The location of the gcc spec file can be determined as follows:
18250 @smallexample
18251 $ gcc -v
18252 @end smallexample
18253
18254 @noindent
18255 The configuration files mentioned above have a simple format: each line
18256 must contain one unique directory name.
18257 Those names are added to the corresponding path
18258 in their order of appearance in the file. The names can be either absolute
18259 or relative; in the latter case, they are relative to where theses files
18260 are located.
18261
18262 The files @file{ada_source_path} and @file{ada_object_path} might not be
18263 present in a
18264 GNAT installation, in which case, GNAT will look for its run-time library in
18265 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
18266 objects and @file{ALI} files). When the files exist, the compiler does not
18267 look in @file{adainclude} and @file{adalib}, and thus the
18268 @file{ada_source_path} file
18269 must contain the location for the GNAT run-time sources (which can simply
18270 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
18271 contain the location for the GNAT run-time objects (which can simply
18272 be @file{adalib}).
18273
18274 You can also specify a new default path to the run-time library at compilation
18275 time with the switch @option{--RTS=rts-path}. You can thus choose / change
18276 the run-time library you want your program to be compiled with. This switch is
18277 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
18278 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
18279
18280 It is possible to install a library before or after the standard GNAT
18281 library, by reordering the lines in the configuration files. In general, a
18282 library must be installed before the GNAT library if it redefines
18283 any part of it.
18284
18285 @node Using a library
18286 @subsection Using a library
18287
18288 @noindent Once again, the project facility greatly simplifies the use of
18289 libraries. In this context, using a library is just a matter of adding a
18290 @code{with} clause in the user project. For instance, to make use of the
18291 library @code{My_Lib} shown in examples in earlier sections, you can
18292 write:
18293
18294 @smallexample @c projectfile
18295 with "my_lib";
18296 project My_Proj is
18297   @dots{}
18298 end My_Proj;
18299 @end smallexample
18300
18301 Even if you have a third-party, non-Ada library, you can still use GNAT's
18302 Project Manager facility to provide a wrapper for it. For example, the
18303 following project, when @code{with}ed by your main project, will link with the
18304 third-party library @file{liba.a}:
18305
18306 @smallexample @c projectfile
18307 @group
18308 project Liba is
18309    for Externally_Built use "true";
18310    for Source_Files use ();
18311    for Library_Dir use "lib";
18312    for Library_Name use "a";
18313    for Library_Kind use "static";
18314 end Liba;
18315 @end group
18316 @end smallexample
18317 This is an alternative to the use of @code{pragma Linker_Options}. It is
18318 especially interesting in the context of systems with several interdependent
18319 static libraries where finding a proper linker order is not easy and best be
18320 left to the tools having visibility over project dependence information.
18321
18322 @noindent
18323 In order to use an Ada library manually, you need to make sure that this
18324 library is on both your source and object path
18325 (see @ref{Search Paths and the Run-Time Library (RTL)}
18326 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
18327 in an archive or a shared library, you need to specify the desired
18328 library at link time.
18329
18330 For example, you can use the library @file{mylib} installed in
18331 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
18332
18333 @smallexample
18334 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
18335   -largs -lmy_lib
18336 @end smallexample
18337
18338 @noindent
18339 This can be expressed more simply:
18340 @smallexample
18341 $ gnatmake my_appl
18342 @end smallexample
18343 @noindent
18344 when the following conditions are met:
18345 @itemize @bullet
18346 @item
18347 @file{/dir/my_lib_src} has been added by the user to the environment
18348 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
18349 @file{ada_source_path}
18350 @item
18351 @file{/dir/my_lib_obj} has been added by the user to the environment
18352 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
18353 @file{ada_object_path}
18354 @item
18355 a pragma @code{Linker_Options} has been added to one of the sources.
18356 For example:
18357
18358 @smallexample @c ada
18359 pragma Linker_Options ("-lmy_lib");
18360 @end smallexample
18361 @end itemize
18362
18363 @node Stand-alone Ada Libraries
18364 @section Stand-alone Ada Libraries
18365 @cindex Stand-alone library, building, using
18366
18367 @menu
18368 * Introduction to Stand-alone Libraries::
18369 * Building a Stand-alone Library::
18370 * Creating a Stand-alone Library to be used in a non-Ada context::
18371 * Restrictions in Stand-alone Libraries::
18372 @end menu
18373
18374 @node Introduction to Stand-alone Libraries
18375 @subsection Introduction to Stand-alone Libraries
18376
18377 @noindent
18378 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
18379 necessary code to
18380 elaborate the Ada units that are included in the library. In contrast with
18381 an ordinary library, which consists of all sources, objects and @file{ALI}
18382 files of the
18383 library, a SAL may specify a restricted subset of compilation units
18384 to serve as a library interface. In this case, the fully
18385 self-sufficient set of files will normally consist of an objects
18386 archive, the sources of interface units' specs, and the @file{ALI}
18387 files of interface units.
18388 If an interface spec contains a generic unit or an inlined subprogram,
18389 the body's
18390 source must also be provided; if the units that must be provided in the source
18391 form depend on other units, the source and @file{ALI} files of those must
18392 also be provided.
18393
18394 The main purpose of a SAL is to minimize the recompilation overhead of client
18395 applications when a new version of the library is installed. Specifically,
18396 if the interface sources have not changed, client applications do not need to
18397 be recompiled. If, furthermore, a SAL is provided in the shared form and its
18398 version, controlled by @code{Library_Version} attribute, is not changed,
18399 then the clients do not need to be relinked.
18400
18401 SALs also allow the library providers to minimize the amount of library source
18402 text exposed to the clients.  Such ``information hiding'' might be useful or
18403 necessary for various reasons.
18404
18405 Stand-alone libraries are also well suited to be used in an executable whose
18406 main routine is not written in Ada.
18407
18408 @node Building a Stand-alone Library
18409 @subsection Building a Stand-alone Library
18410
18411 @noindent
18412 GNAT's Project facility provides a simple way of building and installing
18413 stand-alone libraries; see @ref{Stand-alone Library Projects}.
18414 To be a Stand-alone Library Project, in addition to the two attributes
18415 that make a project a Library Project (@code{Library_Name} and
18416 @code{Library_Dir}; see @ref{Library Projects}), the attribute
18417 @code{Library_Interface} must be defined.  For example:
18418
18419 @smallexample @c projectfile
18420 @group
18421    for Library_Dir use "lib_dir";
18422    for Library_Name use "dummy";
18423    for Library_Interface use ("int1", "int1.child");
18424 @end group
18425 @end smallexample
18426
18427 @noindent
18428 Attribute @code{Library_Interface} has a non-empty string list value,
18429 each string in the list designating a unit contained in an immediate source
18430 of the project file.
18431
18432 When a Stand-alone Library is built, first the binder is invoked to build
18433 a package whose name depends on the library name
18434 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
18435 This binder-generated package includes initialization and
18436 finalization procedures whose
18437 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
18438 in the example
18439 above). The object corresponding to this package is included in the library.
18440
18441 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
18442 calling of these procedures if a static SAL is built, or if a shared SAL
18443 is built
18444 with the project-level attribute @code{Library_Auto_Init} set to
18445 @code{"false"}.
18446
18447 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
18448 (those that are listed in attribute @code{Library_Interface}) are copied to
18449 the Library Directory. As a consequence, only the Interface Units may be
18450 imported from Ada units outside of the library. If other units are imported,
18451 the binding phase will fail.
18452
18453 The attribute @code{Library_Src_Dir} may be specified for a
18454 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
18455 single string value. Its value must be the path (absolute or relative to the
18456 project directory) of an existing directory. This directory cannot be the
18457 object directory or one of the source directories, but it can be the same as
18458 the library directory. The sources of the Interface
18459 Units of the library that are needed by an Ada client of the library will be
18460 copied to the designated directory, called the Interface Copy directory.
18461 These sources include the specs of the Interface Units, but they may also
18462 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
18463 are used, or when there is a generic unit in the spec. Before the sources
18464 are copied to the Interface Copy directory, an attempt is made to delete all
18465 files in the Interface Copy directory.
18466
18467 Building stand-alone libraries by hand is somewhat tedious, but for those
18468 occasions when it is necessary here are the steps that you need to perform:
18469 @itemize @bullet
18470 @item
18471 Compile all library sources.
18472
18473 @item
18474 Invoke the binder with the switch @option{-n} (No Ada main program),
18475 with all the @file{ALI} files of the interfaces, and
18476 with the switch @option{-L} to give specific names to the @code{init}
18477 and @code{final} procedures.  For example:
18478 @smallexample
18479   gnatbind -n int1.ali int2.ali -Lsal1
18480 @end smallexample
18481
18482 @item
18483 Compile the binder generated file:
18484 @smallexample
18485   gcc -c b~int2.adb
18486 @end smallexample
18487
18488 @item
18489 Link the dynamic library with all the necessary object files,
18490 indicating to the linker the names of the @code{init} (and possibly
18491 @code{final}) procedures for automatic initialization (and finalization).
18492 The built library should be placed in a directory different from
18493 the object directory.
18494
18495 @item
18496 Copy the @code{ALI} files of the interface to the library directory,
18497 add in this copy an indication that it is an interface to a SAL
18498 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
18499 with letter ``P'') and make the modified copy of the @file{ALI} file
18500 read-only.
18501 @end itemize
18502
18503 @noindent
18504 Using SALs is not different from using other libraries
18505 (see @ref{Using a library}).
18506
18507 @node Creating a Stand-alone Library to be used in a non-Ada context
18508 @subsection Creating a Stand-alone Library to be used in a non-Ada context
18509
18510 @noindent
18511 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
18512 a non-Ada context.
18513
18514 The only extra step required is to ensure that library interface subprograms
18515 are compatible with the main program, by means of @code{pragma Export}
18516 or @code{pragma Convention}.
18517
18518 Here is an example of simple library interface for use with C main program:
18519
18520 @smallexample @c ada
18521 package Interface is
18522
18523    procedure Do_Something;
18524    pragma Export (C, Do_Something, "do_something");
18525
18526    procedure Do_Something_Else;
18527    pragma Export (C, Do_Something_Else, "do_something_else");
18528
18529 end Interface;
18530 @end smallexample
18531
18532 @noindent
18533 On the foreign language side, you must provide a ``foreign'' view of the
18534 library interface; remember that it should contain elaboration routines in
18535 addition to interface subprograms.
18536
18537 The example below shows the content of @code{mylib_interface.h} (note
18538 that there is no rule for the naming of this file, any name can be used)
18539 @smallexample
18540 /* the library elaboration procedure */
18541 extern void mylibinit (void);
18542
18543 /* the library finalization procedure */
18544 extern void mylibfinal (void);
18545
18546 /* the interface exported by the library */
18547 extern void do_something (void);
18548 extern void do_something_else (void);
18549 @end smallexample
18550
18551 @noindent
18552 Libraries built as explained above can be used from any program, provided
18553 that the elaboration procedures (named @code{mylibinit} in the previous
18554 example) are called before the library services are used. Any number of
18555 libraries can be used simultaneously, as long as the elaboration
18556 procedure of each library is called.
18557
18558 Below is an example of a C program that uses the @code{mylib} library.
18559
18560 @smallexample
18561 #include "mylib_interface.h"
18562
18563 int
18564 main (void)
18565 @{
18566    /* First, elaborate the library before using it */
18567    mylibinit ();
18568
18569    /* Main program, using the library exported entities */
18570    do_something ();
18571    do_something_else ();
18572
18573    /* Library finalization at the end of the program */
18574    mylibfinal ();
18575    return 0;
18576 @}
18577 @end smallexample
18578
18579 @noindent
18580 Note that invoking any library finalization procedure generated by
18581 @code{gnatbind} shuts down the Ada run-time environment.
18582 Consequently, the
18583 finalization of all Ada libraries must be performed at the end of the program.
18584 No call to these libraries or to the Ada run-time library should be made
18585 after the finalization phase.
18586
18587 @node Restrictions in Stand-alone Libraries
18588 @subsection Restrictions in Stand-alone Libraries
18589
18590 @noindent
18591 The pragmas listed below should be used with caution inside libraries,
18592 as they can create incompatibilities with other Ada libraries:
18593 @itemize @bullet
18594 @item pragma @code{Locking_Policy}
18595 @item pragma @code{Queuing_Policy}
18596 @item pragma @code{Task_Dispatching_Policy}
18597 @item pragma @code{Unreserve_All_Interrupts}
18598 @end itemize
18599
18600 @noindent
18601 When using a library that contains such pragmas, the user must make sure
18602 that all libraries use the same pragmas with the same values. Otherwise,
18603 @code{Program_Error} will
18604 be raised during the elaboration of the conflicting
18605 libraries. The usage of these pragmas and its consequences for the user
18606 should therefore be well documented.
18607
18608 Similarly, the traceback in the exception occurrence mechanism should be
18609 enabled or disabled in a consistent manner across all libraries.
18610 Otherwise, Program_Error will be raised during the elaboration of the
18611 conflicting libraries.
18612
18613 If the @code{Version} or @code{Body_Version}
18614 attributes are used inside a library, then you need to
18615 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
18616 libraries, so that version identifiers can be properly computed.
18617 In practice these attributes are rarely used, so this is unlikely
18618 to be a consideration.
18619
18620 @node  Rebuilding the GNAT Run-Time Library
18621 @section Rebuilding the GNAT Run-Time Library
18622 @cindex GNAT Run-Time Library, rebuilding
18623 @cindex Building the GNAT Run-Time Library
18624 @cindex Rebuilding the GNAT Run-Time Library
18625 @cindex Run-Time Library, rebuilding
18626
18627 @noindent
18628 It may be useful to recompile the GNAT library in various contexts, the
18629 most important one being the use of partition-wide configuration pragmas
18630 such as @code{Normalize_Scalars}. A special Makefile called
18631 @code{Makefile.adalib} is provided to that effect and can be found in
18632 the directory containing the GNAT library. The location of this
18633 directory depends on the way the GNAT environment has been installed and can
18634 be determined by means of the command:
18635
18636 @smallexample
18637 $ gnatls -v
18638 @end smallexample
18639
18640 @noindent
18641 The last entry in the object search path usually contains the
18642 gnat library. This Makefile contains its own documentation and in
18643 particular the set of instructions needed to rebuild a new library and
18644 to use it.
18645
18646 @node Using the GNU make Utility
18647 @chapter Using the GNU @code{make} Utility
18648 @findex make
18649
18650 @noindent
18651 This chapter offers some examples of makefiles that solve specific
18652 problems. It does not explain how to write a makefile (see the GNU make
18653 documentation), nor does it try to replace the @command{gnatmake} utility
18654 (@pxref{The GNAT Make Program gnatmake}).
18655
18656 All the examples in this section are specific to the GNU version of
18657 make. Although @command{make} is a standard utility, and the basic language
18658 is the same, these examples use some advanced features found only in
18659 @code{GNU make}.
18660
18661 @menu
18662 * Using gnatmake in a Makefile::
18663 * Automatically Creating a List of Directories::
18664 * Generating the Command Line Switches::
18665 * Overcoming Command Line Length Limits::
18666 @end menu
18667
18668 @node Using gnatmake in a Makefile
18669 @section Using gnatmake in a Makefile
18670 @findex makefile
18671 @cindex GNU make
18672
18673 @noindent
18674 Complex project organizations can be handled in a very powerful way by
18675 using GNU make combined with gnatmake. For instance, here is a Makefile
18676 which allows you to build each subsystem of a big project into a separate
18677 shared library. Such a makefile allows you to significantly reduce the link
18678 time of very big applications while maintaining full coherence at
18679 each step of the build process.
18680
18681 The list of dependencies are handled automatically by
18682 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
18683 the appropriate directories.
18684
18685 Note that you should also read the example on how to automatically
18686 create the list of directories
18687 (@pxref{Automatically Creating a List of Directories})
18688 which might help you in case your project has a lot of subdirectories.
18689
18690 @smallexample
18691 @iftex
18692 @leftskip=0cm
18693 @font@heightrm=cmr8
18694 @heightrm
18695 @end iftex
18696 ## This Makefile is intended to be used with the following directory
18697 ## configuration:
18698 ##  - The sources are split into a series of csc (computer software components)
18699 ##    Each of these csc is put in its own directory.
18700 ##    Their name are referenced by the directory names.
18701 ##    They will be compiled into shared library (although this would also work
18702 ##    with static libraries
18703 ##  - The main program (and possibly other packages that do not belong to any
18704 ##    csc is put in the top level directory (where the Makefile is).
18705 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
18706 ##                    \_ second_csc (sources) __ lib (will contain the library)
18707 ##                    \_ @dots{}
18708 ## Although this Makefile is build for shared library, it is easy to modify
18709 ## to build partial link objects instead (modify the lines with -shared and
18710 ## gnatlink below)
18711 ##
18712 ## With this makefile, you can change any file in the system or add any new
18713 ## file, and everything will be recompiled correctly (only the relevant shared
18714 ## objects will be recompiled, and the main program will be re-linked).
18715
18716 # The list of computer software component for your project. This might be
18717 # generated automatically.
18718 CSC_LIST=aa bb cc
18719
18720 # Name of the main program (no extension)
18721 MAIN=main
18722
18723 # If we need to build objects with -fPIC, uncomment the following line
18724 #NEED_FPIC=-fPIC
18725
18726 # The following variable should give the directory containing libgnat.so
18727 # You can get this directory through 'gnatls -v'. This is usually the last
18728 # directory in the Object_Path.
18729 GLIB=@dots{}
18730
18731 # The directories for the libraries
18732 # (This macro expands the list of CSC to the list of shared libraries, you
18733 # could simply use the expanded form:
18734 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
18735 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
18736
18737 $@{MAIN@}: objects $@{LIB_DIR@}
18738     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
18739     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
18740
18741 objects::
18742     # recompile the sources
18743     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
18744
18745 # Note: In a future version of GNAT, the following commands will be simplified
18746 # by a new tool, gnatmlib
18747 $@{LIB_DIR@}:
18748     mkdir -p $@{dir $@@ @}
18749     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
18750     cd $@{dir $@@ @} && cp -f ../*.ali .
18751
18752 # The dependencies for the modules
18753 # Note that we have to force the expansion of *.o, since in some cases
18754 # make won't be able to do it itself.
18755 aa/lib/libaa.so: $@{wildcard aa/*.o@}
18756 bb/lib/libbb.so: $@{wildcard bb/*.o@}
18757 cc/lib/libcc.so: $@{wildcard cc/*.o@}
18758
18759 # Make sure all of the shared libraries are in the path before starting the
18760 # program
18761 run::
18762     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
18763
18764 clean::
18765     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
18766     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
18767     $@{RM@} $@{CSC_LIST:%=%/*.o@}
18768     $@{RM@} *.o *.ali $@{MAIN@}
18769 @end smallexample
18770
18771 @node Automatically Creating a List of Directories
18772 @section Automatically Creating a List of Directories
18773
18774 @noindent
18775 In most makefiles, you will have to specify a list of directories, and
18776 store it in a variable. For small projects, it is often easier to
18777 specify each of them by hand, since you then have full control over what
18778 is the proper order for these directories, which ones should be
18779 included.
18780
18781 However, in larger projects, which might involve hundreds of
18782 subdirectories, it might be more convenient to generate this list
18783 automatically.
18784
18785 The example below presents two methods. The first one, although less
18786 general, gives you more control over the list. It involves wildcard
18787 characters, that are automatically expanded by @command{make}. Its
18788 shortcoming is that you need to explicitly specify some of the
18789 organization of your project, such as for instance the directory tree
18790 depth, whether some directories are found in a separate tree, @enddots{}
18791
18792 The second method is the most general one. It requires an external
18793 program, called @command{find}, which is standard on all Unix systems. All
18794 the directories found under a given root directory will be added to the
18795 list.
18796
18797 @smallexample
18798 @iftex
18799 @leftskip=0cm
18800 @font@heightrm=cmr8
18801 @heightrm
18802 @end iftex
18803 # The examples below are based on the following directory hierarchy:
18804 # All the directories can contain any number of files
18805 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
18806 #                       ->  ab
18807 #                       ->  ac
18808 #                ->  b  ->  ba  ->  baa
18809 #                       ->  bb
18810 #                       ->  bc
18811 # This Makefile creates a variable called DIRS, that can be reused any time
18812 # you need this list (see the other examples in this section)
18813
18814 # The root of your project's directory hierarchy
18815 ROOT_DIRECTORY=.
18816
18817 ####
18818 # First method: specify explicitly the list of directories
18819 # This allows you to specify any subset of all the directories you need.
18820 ####
18821
18822 DIRS := a/aa/ a/ab/ b/ba/
18823
18824 ####
18825 # Second method: use wildcards
18826 # Note that the argument(s) to wildcard below should end with a '/'.
18827 # Since wildcards also return file names, we have to filter them out
18828 # to avoid duplicate directory names.
18829 # We thus use make's @code{dir} and @code{sort} functions.
18830 # It sets DIRs to the following value (note that the directories aaa and baa
18831 # are not given, unless you change the arguments to wildcard).
18832 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18833 ####
18834
18835 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18836                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18837
18838 ####
18839 # Third method: use an external program
18840 # This command is much faster if run on local disks, avoiding NFS slowdowns.
18841 # This is the most complete command: it sets DIRs to the following value:
18842 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18843 ####
18844
18845 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18846
18847 @end smallexample
18848
18849 @node Generating the Command Line Switches
18850 @section Generating the Command Line Switches
18851
18852 @noindent
18853 Once you have created the list of directories as explained in the
18854 previous section (@pxref{Automatically Creating a List of Directories}),
18855 you can easily generate the command line arguments to pass to gnatmake.
18856
18857 For the sake of completeness, this example assumes that the source path
18858 is not the same as the object path, and that you have two separate lists
18859 of directories.
18860
18861 @smallexample
18862 # see "Automatically creating a list of directories" to create
18863 # these variables
18864 SOURCE_DIRS=
18865 OBJECT_DIRS=
18866
18867 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18868 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18869
18870 all:
18871         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18872 @end smallexample
18873
18874 @node Overcoming Command Line Length Limits
18875 @section Overcoming Command Line Length Limits
18876
18877 @noindent
18878 One problem that might be encountered on big projects is that many
18879 operating systems limit the length of the command line. It is thus hard to give
18880 gnatmake the list of source and object directories.
18881
18882 This example shows how you can set up environment variables, which will
18883 make @command{gnatmake} behave exactly as if the directories had been
18884 specified on the command line, but have a much higher length limit (or
18885 even none on most systems).
18886
18887 It assumes that you have created a list of directories in your Makefile,
18888 using one of the methods presented in
18889 @ref{Automatically Creating a List of Directories}.
18890 For the sake of completeness, we assume that the object
18891 path (where the ALI files are found) is different from the sources patch.
18892
18893 Note a small trick in the Makefile below: for efficiency reasons, we
18894 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18895 expanded immediately by @code{make}. This way we overcome the standard
18896 make behavior which is to expand the variables only when they are
18897 actually used.
18898
18899 On Windows, if you are using the standard Windows command shell, you must
18900 replace colons with semicolons in the assignments to these variables.
18901
18902 @smallexample
18903 @iftex
18904 @leftskip=0cm
18905 @font@heightrm=cmr8
18906 @heightrm
18907 @end iftex
18908 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
18909 # This is the same thing as putting the -I arguments on the command line.
18910 # (the equivalent of using -aI on the command line would be to define
18911 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
18912 # You can of course have different values for these variables.
18913 #
18914 # Note also that we need to keep the previous values of these variables, since
18915 # they might have been set before running 'make' to specify where the GNAT
18916 # library is installed.
18917
18918 # see "Automatically creating a list of directories" to create these
18919 # variables
18920 SOURCE_DIRS=
18921 OBJECT_DIRS=
18922
18923 empty:=
18924 space:=$@{empty@} $@{empty@}
18925 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18926 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18927 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18928 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
18929 export ADA_INCLUDE_PATH
18930 export ADA_OBJECT_PATH
18931
18932 all:
18933         gnatmake main_unit
18934 @end smallexample
18935 @end ifclear
18936
18937 @node Memory Management Issues
18938 @chapter Memory Management Issues
18939
18940 @noindent
18941 This chapter describes some useful memory pools provided in the GNAT library
18942 and in particular the GNAT Debug Pool facility, which can be used to detect
18943 incorrect uses of access values (including ``dangling references'').
18944 @ifclear vms
18945 It also describes the @command{gnatmem} tool, which can be used to track down
18946 ``memory leaks''.
18947 @end ifclear
18948
18949 @menu
18950 * Some Useful Memory Pools::
18951 * The GNAT Debug Pool Facility::
18952 @ifclear vms
18953 * The gnatmem Tool::
18954 @end ifclear
18955 @end menu
18956
18957 @node Some Useful Memory Pools
18958 @section Some Useful Memory Pools
18959 @findex Memory Pool
18960 @cindex storage, pool
18961
18962 @noindent
18963 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18964 storage pool. Allocations use the standard system call @code{malloc} while
18965 deallocations use the standard system call @code{free}. No reclamation is
18966 performed when the pool goes out of scope. For performance reasons, the
18967 standard default Ada allocators/deallocators do not use any explicit storage
18968 pools but if they did, they could use this storage pool without any change in
18969 behavior. That is why this storage pool is used  when the user
18970 manages to make the default implicit allocator explicit as in this example:
18971 @smallexample @c ada
18972    type T1 is access Something;
18973     -- no Storage pool is defined for T2
18974    type T2 is access Something_Else;
18975    for T2'Storage_Pool use T1'Storage_Pool;
18976    -- the above is equivalent to
18977    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18978 @end smallexample
18979
18980 @noindent
18981 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18982 pool. The allocation strategy is similar to @code{Pool_Local}'s
18983 except that the all
18984 storage allocated with this pool is reclaimed when the pool object goes out of
18985 scope. This pool provides a explicit mechanism similar to the implicit one
18986 provided by several Ada 83 compilers for allocations performed through a local
18987 access type and whose purpose was to reclaim memory when exiting the
18988 scope of a given local access. As an example, the following program does not
18989 leak memory even though it does not perform explicit deallocation:
18990
18991 @smallexample @c ada
18992 with System.Pool_Local;
18993 procedure Pooloc1 is
18994    procedure Internal is
18995       type A is access Integer;
18996       X : System.Pool_Local.Unbounded_Reclaim_Pool;
18997       for A'Storage_Pool use X;
18998       v : A;
18999    begin
19000       for I in  1 .. 50 loop
19001          v := new Integer;
19002       end loop;
19003    end Internal;
19004 begin
19005    for I in  1 .. 100 loop
19006       Internal;
19007    end loop;
19008 end Pooloc1;
19009 @end smallexample
19010
19011 @noindent
19012 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19013 @code{Storage_Size} is specified for an access type.
19014 The whole storage for the pool is
19015 allocated at once, usually on the stack at the point where the access type is
19016 elaborated. It is automatically reclaimed when exiting the scope where the
19017 access type is defined. This package is not intended to be used directly by the
19018 user and it is implicitly used for each such declaration:
19019
19020 @smallexample @c ada
19021    type T1 is access Something;
19022    for T1'Storage_Size use 10_000;
19023 @end smallexample
19024
19025 @node The GNAT Debug Pool Facility
19026 @section The GNAT Debug Pool Facility
19027 @findex Debug Pool
19028 @cindex storage, pool, memory corruption
19029
19030 @noindent
19031 The use of unchecked deallocation and unchecked conversion can easily
19032 lead to incorrect memory references. The problems generated by such
19033 references are usually difficult to tackle because the symptoms can be
19034 very remote from the origin of the problem. In such cases, it is
19035 very helpful to detect the problem as early as possible. This is the
19036 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19037
19038 In order to use the GNAT specific debugging pool, the user must
19039 associate a debug pool object with each of the access types that may be
19040 related to suspected memory problems. See Ada Reference Manual 13.11.
19041 @smallexample @c ada
19042 type Ptr is access Some_Type;
19043 Pool : GNAT.Debug_Pools.Debug_Pool;
19044 for Ptr'Storage_Pool use Pool;
19045 @end smallexample
19046
19047 @noindent
19048 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19049 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19050 allow the user to redefine allocation and deallocation strategies. They
19051 also provide a checkpoint for each dereference, through the use of
19052 the primitive operation @code{Dereference} which is implicitly called at
19053 each dereference of an access value.
19054
19055 Once an access type has been associated with a debug pool, operations on
19056 values of the type may raise four distinct exceptions,
19057 which correspond to four potential kinds of memory corruption:
19058 @itemize @bullet
19059 @item
19060 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19061 @item
19062 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19063 @item
19064 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19065 @item
19066 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19067 @end itemize
19068
19069 @noindent
19070 For types associated with a Debug_Pool, dynamic allocation is performed using
19071 the standard GNAT allocation routine. References to all allocated chunks of
19072 memory are kept in an internal dictionary. Several deallocation strategies are
19073 provided, whereupon the user can choose to release the memory to the system,
19074 keep it allocated for further invalid access checks, or fill it with an easily
19075 recognizable pattern for debug sessions. The memory pattern is the old IBM
19076 hexadecimal convention: @code{16#DEADBEEF#}.
19077
19078 See the documentation in the file g-debpoo.ads for more information on the
19079 various strategies.
19080
19081 Upon each dereference, a check is made that the access value denotes a
19082 properly allocated memory location. Here is a complete example of use of
19083 @code{Debug_Pools}, that includes typical instances of  memory corruption:
19084 @smallexample @c ada
19085 @iftex
19086 @leftskip=0cm
19087 @end iftex
19088 with Gnat.Io; use Gnat.Io;
19089 with Unchecked_Deallocation;
19090 with Unchecked_Conversion;
19091 with GNAT.Debug_Pools;
19092 with System.Storage_Elements;
19093 with Ada.Exceptions; use Ada.Exceptions;
19094 procedure Debug_Pool_Test is
19095
19096    type T is access Integer;
19097    type U is access all T;
19098
19099    P : GNAT.Debug_Pools.Debug_Pool;
19100    for T'Storage_Pool use P;
19101
19102    procedure Free is new Unchecked_Deallocation (Integer, T);
19103    function UC is new Unchecked_Conversion (U, T);
19104    A, B : aliased T;
19105
19106    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
19107
19108 begin
19109    Info (P);
19110    A := new Integer;
19111    B := new Integer;
19112    B := A;
19113    Info (P);
19114    Free (A);
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    B := UC(A'Access);
19126    begin
19127       Put_Line (Integer'Image(B.all));
19128    exception
19129       when E : others => Put_Line ("raised: " & Exception_Name (E));
19130    end;
19131    begin
19132       Free (B);
19133    exception
19134       when E : others => Put_Line ("raised: " & Exception_Name (E));
19135    end;
19136    Info (P);
19137 end Debug_Pool_Test;
19138 @end smallexample
19139
19140 @noindent
19141 The debug pool mechanism provides the following precise diagnostics on the
19142 execution of this erroneous program:
19143 @smallexample
19144 Debug Pool info:
19145   Total allocated bytes :  0
19146   Total deallocated bytes :  0
19147   Current Water Mark:  0
19148   High Water Mark:  0
19149
19150 Debug Pool info:
19151   Total allocated bytes :  8
19152   Total deallocated bytes :  0
19153   Current Water Mark:  8
19154   High Water Mark:  8
19155
19156 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
19157 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
19158 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
19159 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
19160 Debug Pool info:
19161   Total allocated bytes :  8
19162   Total deallocated bytes :  4
19163   Current Water Mark:  4
19164   High Water Mark:  8
19165 @end smallexample
19166
19167 @ifclear vms
19168 @node The gnatmem Tool
19169 @section The @command{gnatmem} Tool
19170 @findex gnatmem
19171
19172 @noindent
19173 The @code{gnatmem} utility monitors dynamic allocation and
19174 deallocation activity in a program, and displays information about
19175 incorrect deallocations and possible sources of memory leaks.
19176 It provides three type of information:
19177 @itemize @bullet
19178 @item
19179 General information concerning memory management, such as the total
19180 number of allocations and deallocations, the amount of allocated
19181 memory and the high water mark, i.e.@: the largest amount of allocated
19182 memory in the course of program execution.
19183
19184 @item
19185 Backtraces for all incorrect deallocations, that is to say deallocations
19186 which do not correspond to a valid allocation.
19187
19188 @item
19189 Information on each allocation that is potentially the origin of a memory
19190 leak.
19191 @end itemize
19192
19193 @menu
19194 * Running gnatmem::
19195 * Switches for gnatmem::
19196 * Example of gnatmem Usage::
19197 @end menu
19198
19199 @node Running gnatmem
19200 @subsection Running @code{gnatmem}
19201
19202 @noindent
19203 @code{gnatmem} makes use of the output created by the special version of
19204 allocation and deallocation routines that record call information. This
19205 allows to obtain accurate dynamic memory usage history at a minimal cost to
19206 the execution speed. Note however, that @code{gnatmem} is not supported on
19207 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
19208 Solaris and Windows NT/2000/XP (x86).
19209
19210 @noindent
19211 The @code{gnatmem} command has the form
19212
19213 @smallexample
19214    $ gnatmem [switches] user_program
19215 @end smallexample
19216
19217 @noindent
19218 The program must have been linked with the instrumented version of the
19219 allocation and deallocation routines. This is done by linking with the
19220 @file{libgmem.a} library. For correct symbolic backtrace information,
19221 the user program should be compiled with debugging options
19222 (see @ref{Switches for gcc}). For example to build @file{my_program}:
19223
19224 @smallexample
19225 $ gnatmake -g my_program -largs -lgmem
19226 @end smallexample
19227
19228 @noindent
19229 As library @file{libgmem.a} contains an alternate body for package
19230 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
19231 when an executable is linked with library @file{libgmem.a}. It is then not
19232 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
19233
19234 @noindent
19235 When @file{my_program} is executed, the file @file{gmem.out} is produced.
19236 This file contains information about all allocations and deallocations
19237 performed by the program. It is produced by the instrumented allocations and
19238 deallocations routines and will be used by @code{gnatmem}.
19239
19240 In order to produce symbolic backtrace information for allocations and
19241 deallocations performed by the GNAT run-time library, you need to use a
19242 version of that library that has been compiled with the @option{-g} switch
19243 (see @ref{Rebuilding the GNAT Run-Time Library}).
19244
19245 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
19246 examine. If the location of @file{gmem.out} file was not explicitly supplied by
19247 @option{-i} switch, gnatmem will assume that this file can be found in the
19248 current directory. For example, after you have executed @file{my_program},
19249 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
19250
19251 @smallexample
19252 $ gnatmem my_program
19253 @end smallexample
19254
19255 @noindent
19256 This will produce the output with the following format:
19257
19258 *************** debut cc
19259 @smallexample
19260 $ gnatmem my_program
19261
19262 Global information
19263 ------------------
19264    Total number of allocations        :  45
19265    Total number of deallocations      :   6
19266    Final Water Mark (non freed mem)   :  11.29 Kilobytes
19267    High Water Mark                    :  11.40 Kilobytes
19268
19269 .
19270 .
19271 .
19272 Allocation Root # 2
19273 -------------------
19274  Number of non freed allocations    :  11
19275  Final Water Mark (non freed mem)   :   1.16 Kilobytes
19276  High Water Mark                    :   1.27 Kilobytes
19277  Backtrace                          :
19278    my_program.adb:23 my_program.alloc
19279 .
19280 .
19281 .
19282 @end smallexample
19283
19284 The first block of output gives general information. In this case, the
19285 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
19286 Unchecked_Deallocation routine occurred.
19287
19288 @noindent
19289 Subsequent paragraphs display  information on all allocation roots.
19290 An allocation root is a specific point in the execution of the program
19291 that generates some dynamic allocation, such as a ``@code{@b{new}}''
19292 construct. This root is represented by an execution backtrace (or subprogram
19293 call stack). By default the backtrace depth for allocations roots is 1, so
19294 that a root corresponds exactly to a source location. The backtrace can
19295 be made deeper, to make the root more specific.
19296
19297 @node Switches for gnatmem
19298 @subsection Switches for @code{gnatmem}
19299
19300 @noindent
19301 @code{gnatmem} recognizes the following switches:
19302
19303 @table @option
19304
19305 @item -q
19306 @cindex @option{-q} (@code{gnatmem})
19307 Quiet. Gives the minimum output needed to identify the origin of the
19308 memory leaks. Omits statistical information.
19309
19310 @item @var{N}
19311 @cindex @var{N} (@code{gnatmem})
19312 N is an integer literal (usually between 1 and 10) which controls the
19313 depth of the backtraces defining allocation root. The default value for
19314 N is 1. The deeper the backtrace, the more precise the localization of
19315 the root. Note that the total number of roots can depend on this
19316 parameter. This parameter must be specified @emph{before} the name of the
19317 executable to be analyzed, to avoid ambiguity.
19318
19319 @item -b n
19320 @cindex @option{-b} (@code{gnatmem})
19321 This switch has the same effect as just depth parameter.
19322
19323 @item -i @var{file}
19324 @cindex @option{-i} (@code{gnatmem})
19325 Do the @code{gnatmem} processing starting from @file{file}, rather than
19326 @file{gmem.out} in the current directory.
19327
19328 @item -m n
19329 @cindex @option{-m} (@code{gnatmem})
19330 This switch causes @code{gnatmem} to mask the allocation roots that have less
19331 than n leaks. The default value is 1. Specifying the value of 0 will allow to
19332 examine even the roots that didn't result in leaks.
19333
19334 @item -s order
19335 @cindex @option{-s} (@code{gnatmem})
19336 This switch causes @code{gnatmem} to sort the allocation roots according to the
19337 specified order of sort criteria, each identified by a single letter. The
19338 currently supported criteria are @code{n, h, w} standing respectively for
19339 number of unfreed allocations, high watermark, and final watermark
19340 corresponding to a specific root. The default order is @code{nwh}.
19341
19342 @end table
19343
19344 @node Example of gnatmem Usage
19345 @subsection Example of @code{gnatmem} Usage
19346
19347 @noindent
19348 The following example shows the use of @code{gnatmem}
19349 on a simple memory-leaking program.
19350 Suppose that we have the following Ada program:
19351
19352 @smallexample @c ada
19353 @group
19354 @cartouche
19355 with Unchecked_Deallocation;
19356 procedure Test_Gm is
19357
19358    type T is array (1..1000) of Integer;
19359    type Ptr is access T;
19360    procedure Free is new Unchecked_Deallocation (T, Ptr);
19361    A : Ptr;
19362
19363    procedure My_Alloc is
19364    begin
19365       A := new T;
19366    end My_Alloc;
19367
19368    procedure My_DeAlloc is
19369       B : Ptr := A;
19370    begin
19371       Free (B);
19372    end My_DeAlloc;
19373
19374 begin
19375    My_Alloc;
19376    for I in 1 .. 5 loop
19377       for J in I .. 5 loop
19378          My_Alloc;
19379       end loop;
19380       My_Dealloc;
19381    end loop;
19382 end;
19383 @end cartouche
19384 @end group
19385 @end smallexample
19386
19387 @noindent
19388 The program needs to be compiled with debugging option and linked with
19389 @code{gmem} library:
19390
19391 @smallexample
19392 $ gnatmake -g test_gm -largs -lgmem
19393 @end smallexample
19394
19395 @noindent
19396 Then we execute the program as usual:
19397
19398 @smallexample
19399 $ test_gm
19400 @end smallexample
19401
19402 @noindent
19403 Then @code{gnatmem} is invoked simply with
19404 @smallexample
19405 $ gnatmem test_gm
19406 @end smallexample
19407
19408 @noindent
19409 which produces the following output (result may vary on different platforms):
19410
19411 @smallexample
19412 Global information
19413 ------------------
19414    Total number of allocations        :  18
19415    Total number of deallocations      :   5
19416    Final Water Mark (non freed mem)   :  53.00 Kilobytes
19417    High Water Mark                    :  56.90 Kilobytes
19418
19419 Allocation Root # 1
19420 -------------------
19421  Number of non freed allocations    :  11
19422  Final Water Mark (non freed mem)   :  42.97 Kilobytes
19423  High Water Mark                    :  46.88 Kilobytes
19424  Backtrace                          :
19425    test_gm.adb:11 test_gm.my_alloc
19426
19427 Allocation Root # 2
19428 -------------------
19429  Number of non freed allocations    :   1
19430  Final Water Mark (non freed mem)   :  10.02 Kilobytes
19431  High Water Mark                    :  10.02 Kilobytes
19432  Backtrace                          :
19433    s-secsta.adb:81 system.secondary_stack.ss_init
19434
19435 Allocation Root # 3
19436 -------------------
19437  Number of non freed allocations    :   1
19438  Final Water Mark (non freed mem)   :  12 Bytes
19439  High Water Mark                    :  12 Bytes
19440  Backtrace                          :
19441    s-secsta.adb:181 system.secondary_stack.ss_init
19442 @end smallexample
19443
19444 @noindent
19445 Note that the GNAT run time contains itself a certain number of
19446 allocations that have no  corresponding deallocation,
19447 as shown here for root #2 and root
19448 #3. This is a normal behavior when the number of non-freed allocations
19449 is one, it allocates dynamic data structures that the run time needs for
19450 the complete lifetime of the program. Note also that there is only one
19451 allocation root in the user program with a single line back trace:
19452 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
19453 program shows that 'My_Alloc' is called at 2 different points in the
19454 source (line 21 and line 24). If those two allocation roots need to be
19455 distinguished, the backtrace depth parameter can be used:
19456
19457 @smallexample
19458 $ gnatmem 3 test_gm
19459 @end smallexample
19460
19461 @noindent
19462 which will give the following output:
19463
19464 @smallexample
19465 Global information
19466 ------------------
19467    Total number of allocations        :  18
19468    Total number of deallocations      :   5
19469    Final Water Mark (non freed mem)   :  53.00 Kilobytes
19470    High Water Mark                    :  56.90 Kilobytes
19471
19472 Allocation Root # 1
19473 -------------------
19474  Number of non freed allocations    :  10
19475  Final Water Mark (non freed mem)   :  39.06 Kilobytes
19476  High Water Mark                    :  42.97 Kilobytes
19477  Backtrace                          :
19478    test_gm.adb:11 test_gm.my_alloc
19479    test_gm.adb:24 test_gm
19480    b_test_gm.c:52 main
19481
19482 Allocation Root # 2
19483 -------------------
19484  Number of non freed allocations    :   1
19485  Final Water Mark (non freed mem)   :  10.02 Kilobytes
19486  High Water Mark                    :  10.02 Kilobytes
19487  Backtrace                          :
19488    s-secsta.adb:81  system.secondary_stack.ss_init
19489    s-secsta.adb:283 <system__secondary_stack___elabb>
19490    b_test_gm.c:33   adainit
19491
19492 Allocation Root # 3
19493 -------------------
19494  Number of non freed allocations    :   1
19495  Final Water Mark (non freed mem)   :   3.91 Kilobytes
19496  High Water Mark                    :   3.91 Kilobytes
19497  Backtrace                          :
19498    test_gm.adb:11 test_gm.my_alloc
19499    test_gm.adb:21 test_gm
19500    b_test_gm.c:52 main
19501
19502 Allocation Root # 4
19503 -------------------
19504  Number of non freed allocations    :   1
19505  Final Water Mark (non freed mem)   :  12 Bytes
19506  High Water Mark                    :  12 Bytes
19507  Backtrace                          :
19508    s-secsta.adb:181 system.secondary_stack.ss_init
19509    s-secsta.adb:283 <system__secondary_stack___elabb>
19510    b_test_gm.c:33   adainit
19511 @end smallexample
19512
19513 @noindent
19514 The allocation root #1 of the first example has been split in 2 roots #1
19515 and #3 thanks to the more precise associated backtrace.
19516
19517 @end ifclear
19518
19519 @node Stack Related Facilities
19520 @chapter Stack Related Facilities
19521
19522 @noindent
19523 This chapter describes some useful tools associated with stack
19524 checking and analysis. In
19525 particular, it deals with dynamic and static stack usage measurements.
19526
19527 @menu
19528 * Stack Overflow Checking::
19529 * Static Stack Usage Analysis::
19530 * Dynamic Stack Usage Analysis::
19531 @end menu
19532
19533 @node Stack Overflow Checking
19534 @section Stack Overflow Checking
19535 @cindex Stack Overflow Checking
19536 @cindex -fstack-check
19537
19538 @noindent
19539 For most operating systems, @command{gcc} does not perform stack overflow
19540 checking by default. This means that if the main environment task or
19541 some other task exceeds the available stack space, then unpredictable
19542 behavior will occur. Most native systems offer some level of protection by
19543 adding a guard page at the end of each task stack. This mechanism is usually
19544 not enough for dealing properly with stack overflow situations because
19545 a large local variable could ``jump'' above the guard page.
19546 Furthermore, when the
19547 guard page is hit, there may not be any space left on the stack for executing
19548 the exception propagation code. Enabling stack checking avoids
19549 such situations.
19550
19551 To activate stack checking, compile all units with the gcc option
19552 @option{-fstack-check}. For example:
19553
19554 @smallexample
19555 gcc -c -fstack-check package1.adb
19556 @end smallexample
19557
19558 @noindent
19559 Units compiled with this option will generate extra instructions to check
19560 that any use of the stack (for procedure calls or for declaring local
19561 variables in declare blocks) does not exceed the available stack space.
19562 If the space is exceeded, then a @code{Storage_Error} exception is raised.
19563
19564 For declared tasks, the stack size is controlled by the size
19565 given in an applicable @code{Storage_Size} pragma or by the value specified
19566 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
19567 the default size as defined in the GNAT runtime otherwise.
19568
19569 For the environment task, the stack size depends on
19570 system defaults and is unknown to the compiler. Stack checking
19571 may still work correctly if a fixed
19572 size stack is allocated, but this cannot be guaranteed.
19573 @ifclear vms
19574 To ensure that a clean exception is signalled for stack
19575 overflow, set the environment variable
19576 @env{GNAT_STACK_LIMIT} to indicate the maximum
19577 stack area that can be used, as in:
19578 @cindex GNAT_STACK_LIMIT
19579
19580 @smallexample
19581 SET GNAT_STACK_LIMIT 1600
19582 @end smallexample
19583
19584 @noindent
19585 The limit is given in kilobytes, so the above declaration would
19586 set the stack limit of the environment task to 1.6 megabytes.
19587 Note that the only purpose of this usage is to limit the amount
19588 of stack used by the environment task. If it is necessary to
19589 increase the amount of stack for the environment task, then this
19590 is an operating systems issue, and must be addressed with the
19591 appropriate operating systems commands.
19592 @end ifclear
19593 @ifset vms
19594 To have a fixed size stack in the environment task, the stack must be put
19595 in the P0 address space and its size specified.  Use these switches to
19596 create a p0 image:
19597
19598 @smallexample
19599 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
19600 @end smallexample
19601
19602 @noindent
19603 The quotes are required to keep case.  The number after @samp{STACK=} is the
19604 size of the environmental task stack in pagelets (512 bytes).  In this example
19605 the stack size is about 2 megabytes.
19606
19607 @noindent
19608 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
19609 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
19610 more details about the @option{/p0image} qualifier and the @option{stack}
19611 option.
19612 @end ifset
19613
19614 @node Static Stack Usage Analysis
19615 @section Static Stack Usage Analysis
19616 @cindex Static Stack Usage Analysis
19617 @cindex -fstack-usage
19618
19619 @noindent
19620 A unit compiled with @option{-fstack-usage} will generate an extra file
19621 that specifies
19622 the maximum amount of stack used, on a per-function basis.
19623 The file has the same
19624 basename as the target object file with a @file{.su} extension.
19625 Each line of this file is made up of three fields:
19626
19627 @itemize
19628 @item
19629 The name of the function.
19630 @item
19631 A number of bytes.
19632 @item
19633 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
19634 @end itemize
19635
19636 The second field corresponds to the size of the known part of the function
19637 frame.
19638
19639 The qualifier @code{static} means that the function frame size
19640 is purely static.
19641 It usually means that all local variables have a static size.
19642 In this case, the second field is a reliable measure of the function stack
19643 utilization.
19644
19645 The qualifier @code{dynamic} means that the function frame size is not static.
19646 It happens mainly when some local variables have a dynamic size. When this
19647 qualifier appears alone, the second field is not a reliable measure
19648 of the function stack analysis. When it is qualified with  @code{bounded}, it
19649 means that the second field is a reliable maximum of the function stack
19650 utilization.
19651
19652 @node Dynamic Stack Usage Analysis
19653 @section Dynamic Stack Usage Analysis
19654
19655 @noindent
19656 It is possible to measure the maximum amount of stack used by a task, by
19657 adding a switch to @command{gnatbind}, as:
19658
19659 @smallexample
19660 $ gnatbind -u0 file
19661 @end smallexample
19662
19663 @noindent
19664 With this option, at each task termination, its stack usage is  output on
19665 @file{stderr}.
19666 It is not always convenient to output the stack usage when the program
19667 is still running. Hence, it is possible to delay this output until program
19668 termination. for a given number of tasks specified as the argument of the
19669 @option{-u} option. For instance:
19670
19671 @smallexample
19672 $ gnatbind -u100 file
19673 @end smallexample
19674
19675 @noindent
19676 will buffer the stack usage information of the first 100 tasks to terminate and
19677 output this info at program termination. Results are displayed in four
19678 columns:
19679
19680 @noindent
19681 Index | Task Name | Stack Size | Actual Use [min - max]
19682
19683 @noindent
19684 where:
19685
19686 @table @emph
19687 @item Index
19688 is a number associated with each task.
19689
19690 @item Task Name
19691 is the name of the task analyzed.
19692
19693 @item Stack Size
19694 is the maximum size for the stack.
19695
19696 @item Actual Use
19697 is the measure done by the stack analyzer. In order to prevent overflow,
19698 the stack is not entirely analyzed, and it's not possible to know exactly how
19699 much has actually been used. The real amount of stack used is between the min
19700 and max values.
19701
19702 @end table
19703
19704 @noindent
19705 The environment task stack, e.g., the stack that contains the main unit, is
19706 only processed when the environment variable GNAT_STACK_LIMIT is set.
19707
19708
19709 @c *********************************
19710 @c *            GNATCHECK          *
19711 @c *********************************
19712 @node Verifying Properties Using gnatcheck
19713 @chapter Verifying Properties Using @command{gnatcheck}
19714 @findex gnatcheck
19715 @cindex @command{gnatcheck}
19716
19717 @noindent
19718 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
19719 of Ada source files according to a given set of semantic rules.
19720 @cindex ASIS
19721
19722 In order to check compliance with a given rule, @command{gnatcheck} has to
19723 semantically analyze the Ada sources.
19724 Therefore, checks can only be performed on
19725 legal Ada units. Moreover, when a unit depends semantically upon units located
19726 outside the current directory, the source search path has to be provided when
19727 calling @command{gnatcheck}, either through a specified project file or
19728 through @command{gnatcheck} switches as described below.
19729
19730 A number of rules are predefined in @command{gnatcheck} and are described
19731 later in this chapter.
19732 You can also add new rules, by modifying the @command{gnatcheck} code and
19733 rebuilding the tool. In order to add a simple rule making some local checks,
19734 a small amount of straightforward ASIS-based programming is usually needed.
19735
19736 Project support for @command{gnatcheck} is provided by the GNAT
19737 driver (see @ref{The GNAT Driver and Project Files}).
19738
19739 Invoking @command{gnatcheck} on the command line has the form:
19740
19741 @smallexample
19742 $ gnatcheck [@i{switches}]  @{@i{filename}@}
19743       [^-files^/FILES^=@{@i{arg_list_filename}@}]
19744       [-cargs @i{gcc_switches}] [-rules @i{rule_options}]
19745 @end smallexample
19746
19747 @noindent
19748 where
19749 @itemize @bullet
19750 @item
19751 @i{switches} specify the general tool options
19752
19753 @item
19754 Each @i{filename} is the name (including the extension) of a source
19755 file to process. ``Wildcards'' are allowed, and
19756 the file name may contain path information.
19757
19758 @item
19759 Each @i{arg_list_filename} is the name (including the extension) of a text
19760 file containing the names of the source files to process, separated by spaces
19761 or line breaks.
19762
19763 @item
19764 @i{gcc_switches} is a list of switches for
19765 @command{gcc}. They will be passed on to all compiler invocations made by
19766 @command{gnatcheck} to generate the ASIS trees. Here you can provide
19767 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19768 and use the @option{-gnatec} switch to set the configuration file.
19769
19770 @item
19771 @i{rule_options} is a list of options for controlling a set of
19772 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
19773 @end itemize
19774
19775 @noindent
19776 Either a @i{filename} or an @i{arg_list_filename} must be supplied.
19777
19778 @menu
19779 * Format of the Report File::
19780 * General gnatcheck Switches::
19781 * gnatcheck Rule Options::
19782 * Adding the Results of Compiler Checks to gnatcheck Output::
19783 * Project-Wide Checks::
19784 * Predefined Rules::
19785 @end menu
19786
19787 @node Format of the Report File
19788 @section Format of the Report File
19789 @cindex Report file (for @code{gnatcheck})
19790
19791 @noindent
19792 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
19793 rule violations.
19794 It also creates, in the current
19795 directory, a text file named @file{^gnatcheck.out^GNATCHECK.OUT^} that
19796 contains the complete report of the last gnatcheck run. This report contains:
19797 @itemize @bullet
19798 @item a list of the Ada source files being checked,
19799 @item a list of enabled and disabled rules,
19800 @item a list of the diagnostic messages, ordered in three different ways
19801 and collected in three separate
19802 sections. Section 1 contains the raw list of diagnostic messages. It
19803 corresponds to the output going to @file{stdout}. Section 2 contains
19804 messages ordered by rules.
19805 Section 3 contains messages ordered by source files.
19806 @end itemize
19807
19808 @node General gnatcheck Switches
19809 @section General @command{gnatcheck} Switches
19810
19811 @noindent
19812 The following switches control the general @command{gnatcheck} behavior
19813
19814 @table @option
19815 @c !sort!
19816 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
19817 @item ^-a^/ALL^
19818 Process all units including those with read-only ALI files such as
19819 those from GNAT Run-Time library.
19820
19821 @ifclear vms
19822 @ignore
19823 @cindex @option{-d} (@command{gnatcheck})
19824 @item -d
19825 Debug mode
19826 @end ignore
19827
19828 @cindex @option{-dd} (@command{gnatcheck})
19829 @item -dd
19830 Progress indicator mode (for use in GPS)
19831 @end ifclear
19832
19833 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
19834 @item ^-h^/HELP^
19835 List the predefined and user-defined rules. For more details see
19836 @ref{Predefined Rules}.
19837
19838 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
19839 @item ^-l^/LOCS^
19840 Use full source locations references in the report file. For a construct from
19841 a generic instantiation a full source location is a chain from the location
19842 of this construct in the generic unit to the place where this unit is
19843 instantiated.
19844
19845 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
19846 @item ^-q^/QUIET^
19847 Quiet mode. All the diagnoses about rule violations are placed in the
19848 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
19849
19850 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
19851 @item ^-s^/SHORT^
19852 Short format of the report file (no version information, no list of applied
19853 rules, no list of checked sources is included)
19854
19855 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
19856 @item ^-s1^/COMPILER_STYLE^
19857 Include the compiler-style section in the report file
19858
19859 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
19860 @item ^-s2^/BY_RULES^
19861 Include the section containing diagnoses ordered by rules in the report file
19862
19863 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
19864 @item ^-s3^/BY_FILES_BY_RULES^
19865 Include the section containing diagnoses ordered by files and then by rules
19866 in the report file
19867
19868 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
19869 @item ^-v^/VERBOSE^
19870 Verbose mode; @command{gnatcheck} generates version information and then
19871 a trace of sources being processed.
19872
19873 @end table
19874
19875 @noindent
19876 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
19877 @option{^-s2^/BY_RULES^} or
19878 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
19879 then the  @command{gnatcheck} report file will only contain sections
19880 explicitly denoted by these options.
19881
19882 @node gnatcheck Rule Options
19883 @section @command{gnatcheck} Rule Options
19884
19885 @noindent
19886 The following options control the processing performed by
19887 @command{gnatcheck}.
19888
19889 @table @option
19890 @cindex @option{+ALL} (@command{gnatcheck})
19891 @item +ALL
19892 Turn all the rule checks ON.
19893
19894 @cindex @option{-ALL} (@command{gnatcheck})
19895 @item -ALL
19896 Turn all the rule checks OFF.
19897
19898 @cindex @option{+R} (@command{gnatcheck})
19899 @item +R@i{rule_id[:param]}
19900 Turn on the check for a specified rule with the specified parameter, if any.
19901 @i{rule_id} must be the identifier of one of the currently implemented rules
19902 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
19903 are not case-sensitive. The @i{param} item must
19904 be a string representing a valid parameter(s) for the specified rule.
19905 If it contains any space characters then this string must be enclosed in
19906 quotation marks.
19907
19908 @cindex @option{-R} (@command{gnatcheck})
19909 @item -R@i{rule_id[:param]}
19910 Turn off the check for a specified rule with the specified parameter, if any.
19911
19912 @cindex @option{-from} (@command{gnatcheck})
19913 @item -from=@i{rule_option_filename}
19914 Read the rule options from the text file @i{rule_option_filename}, referred as
19915 ``rule file'' below.
19916
19917 @end table
19918
19919 @noindent
19920 The default behavior is that all the rule checks are enabled, except for
19921 the checks performed by the compiler.
19922 @ignore
19923 and the checks associated with the
19924 global rules.
19925 @end ignore
19926
19927 A rule file is a text file containing a set of rule options.
19928 @cindex Rule file (for @code{gnatcheck})
19929 The file may contain empty lines and Ada-style comments (comment
19930 lines and end-of-line comments). The rule file has free format; that is,
19931 you do not have to start a new rule option on a new line.
19932
19933 A rule file may contain other @option{-from=@i{rule_option_filename}}
19934 options, each such option being replaced with the content of the
19935 corresponding rule file during the rule files processing. In case a
19936 cycle is detected (that is, @i{rule_file_1} reads rule options from
19937 @i{rule_file_2}, and  @i{rule_file_2} reads (directly or indirectly)
19938 rule options from @i{rule_file_1}), the processing
19939 of rule files is interrupted and a part of their content is ignored.
19940
19941
19942 @node Adding the Results of Compiler Checks to gnatcheck Output
19943 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
19944
19945 @noindent
19946 The @command{gnatcheck} tool can include in the generated diagnostic messages
19947 and in
19948 the report file the results of the checks performed by the compiler. Though
19949 disabled by default, this effect may be obtained by using @option{+R} with
19950 the following rule identifiers and parameters:
19951
19952 @table @option
19953 @item Restrictions
19954 To record restrictions violations (that are performed by the compiler if the
19955 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
19956 use the rule named
19957 @code{Restrictions} with the same parameters as pragma
19958 @code{Restrictions} or @code{Restriction_Warnings}.
19959
19960 @item Style_Checks
19961 To record compiler style checks, use the rule named
19962 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
19963 which enables all the style checks, or a string that has exactly the same
19964 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
19965 @code{Style_Checks} (for further information about this pragma, please
19966 refer to the @cite{@value{EDITION} Reference Manual}).
19967
19968 @item Warnings
19969 To record compiler warnings (@pxref{Warning Message Control}), use the rule
19970 named @code{Warnings} with a parameter that is a valid
19971 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
19972 (for further information about this pragma, please
19973 refer to the @cite{@value{EDITION} Reference Manual}).
19974
19975 @end table
19976
19977 @node Project-Wide Checks
19978 @section Project-Wide Checks
19979 @cindex Project-wide checks (for @command{gnatcheck})
19980
19981 @noindent
19982 In order to perform checks on all units of a given project, you can use
19983 the GNAT driver along with the @option{-P} option:
19984 @smallexample
19985    gnat check -Pproj -rules -from=my_rules
19986 @end smallexample
19987
19988 @noindent
19989 If the project @code{proj} depends upon other projects, you can perform
19990 checks on the project closure using the @option{-U} option:
19991 @smallexample
19992    gnat check -Pproj -U -rules -from=my_rules
19993 @end smallexample
19994
19995 @noindent
19996 Finally, if not all the units are relevant to a particular main
19997 program in the project closure, you can perform checks for the set
19998 of units needed to create a given main program (unit closure) using
19999 the @option{-U} option followed by the name of the main unit:
20000 @smallexample
20001    gnat check -Pproj -U main -rules -from=my_rules
20002 @end smallexample
20003
20004
20005 @node Predefined Rules
20006 @section Predefined Rules
20007 @cindex Predefined rules (for @command{gnatcheck})
20008
20009 @ignore
20010 @c (Jan 2007) Since the global rules are still under development and are not
20011 @c documented, there is no point in explaining the difference between
20012 @c global and local rules
20013 @noindent
20014 A rule in @command{gnatcheck} is either local or global.
20015 A @emph{local rule} is a rule that applies to a well-defined section
20016 of a program and that can be checked by analyzing only this section.
20017 A @emph{global rule} requires analysis of some global properties of the
20018 whole program (mostly related to the program call graph).
20019 As of @value{NOW}, the implementation of global rules should be
20020 considered to be at a preliminary stage. You can use the
20021 @option{+GLOBAL} option to enable all the global rules, and the
20022 @option{-GLOBAL} rule option to disable all the global rules.
20023
20024 All the global rules in the list below are
20025 so indicated by marking them ``GLOBAL''.
20026 This +GLOBAL and -GLOBAL options are not
20027 included in the list of gnatcheck options above, because at the moment they
20028 are considered as a temporary debug options.
20029
20030 @command{gnatcheck} performs rule checks for generic
20031 instances only for global rules.  This limitation may be relaxed in a later
20032 release.
20033 @end ignore
20034
20035 @noindent
20036 The following subsections document the rules implemented in
20037 @command{gnatcheck}.
20038 The subsection title is the same as the rule identifier, which may be
20039 used as a parameter of the @option{+R} or @option{-R} options.
20040
20041
20042 @menu
20043 * Abstract_Type_Declarations::
20044 * Anonymous_Arrays::
20045 * Anonymous_Subtypes::
20046 * Blocks::
20047 * Boolean_Relational_Operators::
20048 @ignore
20049 * Ceiling_Violations::
20050 @end ignore
20051 * Controlled_Type_Declarations::
20052 * Declarations_In_Blocks::
20053 * Default_Parameters::
20054 * Discriminated_Records::
20055 * Enumeration_Ranges_In_CASE_Statements::
20056 * Exceptions_As_Control_Flow::
20057 * EXIT_Statements_With_No_Loop_Name::
20058 * Expanded_Loop_Exit_Names::
20059 * Explicit_Full_Discrete_Ranges::
20060 * Float_Equality_Checks::
20061 * Forbidden_Pragmas::
20062 * Function_Style_Procedures::
20063 * Generics_In_Subprograms::
20064 * GOTO_Statements::
20065 * Implicit_IN_Mode_Parameters::
20066 * Implicit_SMALL_For_Fixed_Point_Types::
20067 * Improperly_Located_Instantiations::
20068 * Improper_Returns::
20069 * Library_Level_Subprograms::
20070 * Local_Packages::
20071 @ignore
20072 * Improperly_Called_Protected_Entries::
20073 @end ignore
20074 * Misnamed_Identifiers::
20075 * Multiple_Entries_In_Protected_Definitions::
20076 * Name_Clashes::
20077 * Non_Qualified_Aggregates::
20078 * Non_Short_Circuit_Operators::
20079 * Non_SPARK_Attributes::
20080 * Non_Tagged_Derived_Types::
20081 * Non_Visible_Exceptions::
20082 * Numeric_Literals::
20083 * OTHERS_In_Aggregates::
20084 * OTHERS_In_CASE_Statements::
20085 * OTHERS_In_Exception_Handlers::
20086 * Outer_Loop_Exits::
20087 * Overloaded_Operators::
20088 * Overly_Nested_Control_Structures::
20089 * Parameters_Out_Of_Order::
20090 * Positional_Actuals_For_Defaulted_Generic_Parameters::
20091 * Positional_Actuals_For_Defaulted_Parameters::
20092 * Positional_Components::
20093 * Positional_Generic_Parameters::
20094 * Positional_Parameters::
20095 * Predefined_Numeric_Types::
20096 * Raising_External_Exceptions::
20097 * Raising_Predefined_Exceptions::
20098 @ignore
20099 * Recursion::
20100 * Side_Effect_Functions::
20101 @end ignore
20102 * Slices::
20103 * Unassigned_OUT_Parameters::
20104 * Uncommented_BEGIN_In_Package_Bodies::
20105 * Unconstrained_Array_Returns::
20106 * Universal_Ranges::
20107 * Unnamed_Blocks_And_Loops::
20108 @ignore
20109 * Unused_Subprograms::
20110 @end ignore
20111 * USE_PACKAGE_Clauses::
20112 * Volatile_Objects_Without_Address_Clauses::
20113 @end menu
20114
20115
20116 @node Abstract_Type_Declarations
20117 @subsection @code{Abstract_Type_Declarations}
20118 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
20119
20120 @noindent
20121 Flag all declarations of abstract types. For an abstract private
20122 type, both the private and full type declarations are flagged.
20123
20124 This rule has no parameters.
20125
20126
20127 @node Anonymous_Arrays
20128 @subsection @code{Anonymous_Arrays}
20129 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
20130
20131 @noindent
20132 Flag all anonymous array type definitions (by Ada semantics these can only
20133 occur in object declarations).
20134
20135 This rule has no parameters.
20136
20137 @node Anonymous_Subtypes
20138 @subsection @code{Anonymous_Subtypes}
20139 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
20140
20141 @noindent
20142 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
20143 any instance of a subtype indication with a constraint, other than one
20144 that occurs immediately within a subtype declaration. Any use of a range
20145 other than as a constraint used immediately within a subtype declaration
20146 is considered as an anonymous subtype.
20147
20148 An effect of this rule is that @code{for} loops such as the following are
20149 flagged (since @code{1..N} is formally a ``range''):
20150
20151 @smallexample @c ada
20152 for I in 1 .. N loop
20153    @dots{}
20154 end loop;
20155 @end smallexample
20156
20157 @noindent
20158 Declaring an explicit subtype solves the problem:
20159
20160 @smallexample @c ada
20161 subtype S is Integer range 1..N;
20162 @dots{}
20163 for I in S loop
20164    @dots{}
20165 end loop;
20166 @end smallexample
20167
20168 @noindent
20169 This rule has no parameters.
20170
20171 @node Blocks
20172 @subsection @code{Blocks}
20173 @cindex @code{Blocks} rule (for @command{gnatcheck})
20174
20175 @noindent
20176 Flag each block statement.
20177
20178 This rule has no parameters.
20179
20180 @node Boolean_Relational_Operators
20181 @subsection @code{Boolean_Relational_Operators}
20182 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
20183
20184 @noindent
20185 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
20186 ``>='', ``='' and ``/='') for the predefined Boolean type.
20187 (This rule is useful in enforcing the SPARK language restrictions.)
20188
20189 Calls to predefined relational operators of any type derived from
20190 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
20191 with these designators, and uses of operators that are renamings
20192 of the predefined relational operators for @code{Standard.Boolean},
20193 are likewise not detected.
20194
20195 This rule has no parameters.
20196
20197 @ignore
20198 @node Ceiling_Violations
20199 @subsection @code{Ceiling_Violations} (under construction, GLOBAL)
20200 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
20201
20202 @noindent
20203 Flag invocations of a protected operation by a task whose priority exceeds
20204 the protected object's ceiling.
20205
20206 As of @value{NOW}, this rule has the following limitations:
20207
20208 @itemize @bullet
20209
20210 @item
20211  We consider only pragmas Priority and Interrupt_Priority as means to define
20212   a task/protected operation priority. We do not consider the effect of using
20213   Ada.Dynamic_Priorities.Set_Priority procedure;
20214
20215 @item
20216  We consider only base task priorities, and no priority inheritance. That is,
20217   we do not make a difference between calls issued during task activation and
20218   execution of the sequence of statements from task body;
20219
20220 @item
20221  Any situation when the priority of protected operation caller is set by a
20222   dynamic expression (that is, the corresponding Priority or
20223   Interrupt_Priority pragma has a non-static expression as an argument) we
20224   treat as a priority inconsistency (and, therefore, detect this situation).
20225 @end itemize
20226
20227 @noindent
20228 At the moment the notion of the main subprogram is not implemented in
20229 gnatcheck, so any pragma Priority in a library level subprogram body (in case
20230 if this subprogram can be a main subprogram of a partition) changes the
20231 priority of an environment task. So if we have more then one such pragma in
20232 the set of processed sources, the pragma that is processed last, defines the
20233 priority of an environment task.
20234
20235 This rule has no parameters.
20236 @end ignore
20237
20238 @node Controlled_Type_Declarations
20239 @subsection @code{Controlled_Type_Declarations}
20240 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
20241
20242 @noindent
20243 Flag all declarations of controlled types. A declaration of a private type
20244 is flagged if its full declaration declares a controlled type. A declaration
20245 of a derived type is flagged if its ancestor type is controlled. Subtype
20246 declarations are not checked. A declaration of a type that itself is not a
20247 descendant of a type declared in @code{Ada.Finalization} but has a controlled
20248 component is not checked.
20249
20250 This rule has no parameters.
20251
20252
20253
20254 @node Declarations_In_Blocks
20255 @subsection @code{Declarations_In_Blocks}
20256 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
20257
20258 @noindent
20259 Flag all block statements containing local declarations. A @code{declare}
20260 block with an empty @i{declarative_part} or with a @i{declarative part}
20261 containing only pragmas and/or @code{use} clauses is not flagged.
20262
20263 This rule has no parameters.
20264
20265
20266 @node Default_Parameters
20267 @subsection @code{Default_Parameters}
20268 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
20269
20270 @noindent
20271 Flag all default expressions for subprogram parameters. Parameter
20272 declarations of formal and generic subprograms are also checked.
20273
20274 This rule has no parameters.
20275
20276
20277 @node Discriminated_Records
20278 @subsection @code{Discriminated_Records}
20279 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
20280
20281 @noindent
20282 Flag all declarations of record types with discriminants. Only the
20283 declarations of record and record extension types are checked. Incomplete,
20284 formal, private, derived and private extension type declarations are not
20285 checked. Task and protected type declarations also are not checked.
20286
20287 This rule has no parameters.
20288
20289
20290 @node Enumeration_Ranges_In_CASE_Statements
20291 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
20292 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
20293
20294 @noindent
20295 Flag each use of a range of enumeration literals as a choice in a
20296 @code{case} statement.
20297 All forms for specifying a range (explicit ranges
20298 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
20299 An enumeration range is
20300 flagged even if contains exactly one enumeration value or no values at all. A
20301 type derived from an enumeration type is considered as an enumeration type.
20302
20303 This rule helps prevent maintenance problems arising from adding an
20304 enumeration value to a type and having it implicitly handled by an existing
20305 @code{case} statement with an enumeration range that includes the new literal.
20306
20307 This rule has no parameters.
20308
20309
20310 @node Exceptions_As_Control_Flow
20311 @subsection @code{Exceptions_As_Control_Flow}
20312 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
20313
20314 @noindent
20315 Flag each place where an exception is explicitly raised and handled in the
20316 same subprogram body. A @code{raise} statement in an exception handler,
20317 package body, task body or entry body is not flagged.
20318
20319 The rule has no parameters.
20320
20321 @node EXIT_Statements_With_No_Loop_Name
20322 @subsection @code{EXIT_Statements_With_No_Loop_Name}
20323 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
20324
20325 @noindent
20326 Flag each @code{exit} statement that does not specify the name of the loop
20327 being exited.
20328
20329 The rule has no parameters.
20330
20331
20332 @node Expanded_Loop_Exit_Names
20333 @subsection @code{Expanded_Loop_Exit_Names}
20334 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
20335
20336 @noindent
20337 Flag all expanded loop names in @code{exit} statements.
20338
20339 This rule has no parameters.
20340
20341 @node Explicit_Full_Discrete_Ranges
20342 @subsection @code{Explicit_Full_Discrete_Ranges}
20343 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
20344
20345 @noindent
20346 Flag each discrete range that has the form @code{A'First .. A'Last}.
20347
20348 This rule has no parameters.
20349
20350 @node Float_Equality_Checks
20351 @subsection @code{Float_Equality_Checks}
20352 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
20353
20354 @noindent
20355 Flag all calls to the predefined equality operations for floating-point types.
20356 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
20357 User-defined equality operations are not flagged, nor are ``@code{=}''
20358 and ``@code{/=}'' operations for fixed-point types.
20359
20360 This rule has no parameters.
20361
20362
20363 @node Forbidden_Pragmas
20364 @subsection @code{Forbidden_Pragmas}
20365 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
20366
20367 @noindent
20368 Flag each use of the specified pragmas.  The pragmas to be detected
20369 are named in the rule's  parameters.
20370
20371 This rule has the following parameters:
20372
20373 @itemize @bullet
20374 @item For the @option{+R} option
20375
20376 @table @asis
20377 @item @emph{Pragma_Name}
20378 Adds the specified pragma to the set of pragmas to be
20379 checked and sets the checks for all the specified pragmas
20380 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
20381 does not correspond to any pragma name defined in the Ada
20382 standard or to the name of a GNAT-specific pragma defined
20383 in the GNAT Reference Manual, it is treated as the name of
20384 unknown pragma.
20385
20386 @item @code{GNAT}
20387 All the GNAT-specific pragmas are detected; this sets
20388 the checks for all the specified pragmas ON.
20389
20390 @item @code{ALL}
20391 All pragmas are detected; this sets the rule ON.
20392 @end table
20393
20394 @item For the @option{-R} option
20395 @table @asis
20396 @item @emph{Pragma_Name}
20397 Removes the specified pragma from the set of pragmas to be
20398 checked without affecting checks for
20399 other pragmas. @emph{Pragma_Name} is treated as a name
20400 of a pragma. If it does not correspond to any pragma
20401 defined in the Ada standard or to any name defined in the
20402 GNAT Reference Manual,
20403 this option is treated as turning OFF detection of all
20404 unknown pragmas.
20405
20406 @item GNAT
20407 Turn OFF detection of all GNAT-specific pragmas
20408
20409 @item ALL
20410 Clear the list of the pragmas to be detected and
20411 turn the rule OFF.
20412 @end table
20413 @end itemize
20414
20415 @noindent
20416 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
20417 the syntax of an Ada identifier and therefore can not be considered
20418 as a pragma name, a diagnostic message is generated and the corresponding
20419 parameter is ignored.
20420
20421 When more then one parameter is given in the same rule option, the parameters
20422 must be separated by a comma.
20423
20424 If more then one option for this rule is specified for the @command{gnatcheck}
20425 call, a new option overrides the previous one(s).
20426
20427 The @option{+R} option with no parameters turns the rule ON with the set of
20428 pragmas to be detected defined by the previous rule options.
20429 (By default this set is empty, so if the only option specified for the rule is
20430 @option{+RForbidden_Pragmas} (with
20431 no parameter), then the rule is enabled, but it does not detect anything).
20432 The @option{-R} option with no parameter turns the rule OFF, but it does not
20433 affect the set of pragmas to be detected.
20434
20435
20436
20437
20438 @node Function_Style_Procedures
20439 @subsection @code{Function_Style_Procedures}
20440 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
20441
20442 @noindent
20443 Flag each procedure that can be rewritten as a function. A procedure can be
20444 converted into a function if it has exactly one parameter of mode @code{out}
20445 and no parameters of mode @code{in out}. Procedure declarations,
20446 formal procedure declarations, and generic procedure declarations are always
20447 checked. Procedure
20448 bodies and body stubs are flagged only if they do not have corresponding
20449 separate declarations. Procedure renamings and procedure instantiations are
20450 not flagged.
20451
20452 If a procedure can be rewritten as a function, but its @code{out} parameter is
20453 of a limited type, it is not flagged.
20454
20455 Protected procedures are not flagged. Null procedures also are not flagged.
20456
20457 This rule has no parameters.
20458
20459
20460 @node Generics_In_Subprograms
20461 @subsection @code{Generics_In_Subprograms}
20462 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
20463
20464 @noindent
20465 Flag each declaration of a generic unit in a subprogram. Generic
20466 declarations in the bodies of generic subprograms are also flagged.
20467 A generic unit nested in another generic unit is not flagged.
20468 If a generic unit is
20469 declared in a local package that is declared in a subprogram body, the
20470 generic unit is flagged.
20471
20472 This rule has no parameters.
20473
20474
20475 @node GOTO_Statements
20476 @subsection @code{GOTO_Statements}
20477 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
20478
20479 @noindent
20480 Flag each occurrence of a @code{goto} statement.
20481
20482 This rule has no parameters.
20483
20484
20485 @node Implicit_IN_Mode_Parameters
20486 @subsection @code{Implicit_IN_Mode_Parameters}
20487 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
20488
20489 @noindent
20490 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
20491 Note that @code{access} parameters, although they technically behave
20492 like @code{in} parameters, are not flagged.
20493
20494 This rule has no parameters.
20495
20496
20497 @node Implicit_SMALL_For_Fixed_Point_Types
20498 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
20499 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
20500
20501 @noindent
20502 Flag each fixed point type declaration that lacks an explicit
20503 representation  clause to define its @code{'Small} value.
20504 Since @code{'Small} can be  defined only for ordinary fixed point types,
20505 decimal fixed point type declarations are not checked.
20506
20507 This rule has no parameters.
20508
20509
20510 @node Improperly_Located_Instantiations
20511 @subsection @code{Improperly_Located_Instantiations}
20512 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
20513
20514 @noindent
20515 Flag all generic instantiations in library-level package specifications
20516 (including library generic packages) and in all subprogram bodies.
20517
20518 Instantiations in task and entry bodies are not flagged. Instantiations in the
20519 bodies of protected subprograms are flagged.
20520
20521 This rule has no parameters.
20522
20523
20524
20525 @node Improper_Returns
20526 @subsection @code{Improper_Returns}
20527 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
20528
20529 @noindent
20530 Flag each explicit @code{return} statement in procedures, and
20531 multiple @code{return} statements in functions.
20532 Diagnostic messages are generated for all @code{return} statements
20533 in a procedure (thus each procedure must be written so that it
20534 returns implicitly at the end of its statement part),
20535 and for all @code{return} statements in a function after the first one.
20536 This rule supports the stylistic convention that each subprogram
20537 should have no more than one point of normal return.
20538
20539 This rule has no parameters.
20540
20541
20542 @node Library_Level_Subprograms
20543 @subsection @code{Library_Level_Subprograms}
20544 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
20545
20546 @noindent
20547 Flag all library-level subprograms (including generic subprogram instantiations).
20548
20549 This rule has no parameters.
20550
20551
20552 @node Local_Packages
20553 @subsection @code{Local_Packages}
20554 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
20555
20556 @noindent
20557 Flag all local packages declared in package and generic package
20558 specifications.
20559 Local packages in bodies are not flagged.
20560
20561 This rule has no parameters.
20562
20563 @ignore
20564 @node Improperly_Called_Protected_Entries
20565 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
20566 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
20567
20568 @noindent
20569 Flag each protected entry that can be called from more than one task.
20570
20571 This rule has no parameters.
20572 @end ignore
20573
20574
20575 @node Misnamed_Identifiers
20576 @subsection @code{Misnamed_Identifiers}
20577 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
20578
20579 @noindent
20580 Flag the declaration of each identifier that does not have a suffix
20581 corresponding to the kind of entity being declared.
20582 The following declarations are checked:
20583
20584 @itemize @bullet
20585 @item
20586  type declarations
20587
20588 @item
20589  constant declarations (but not number declarations)
20590
20591 @item
20592  package renaming declarations (but not generic package renaming
20593     declarations)
20594 @end itemize
20595
20596 @noindent
20597 This rule may have parameters. When used without parameters, the rule enforces
20598 the following checks:
20599
20600 @itemize @bullet
20601 @item
20602    type-defining names end with @code{_T}, unless the type is an access type,
20603     in which case the suffix must be @code{_A}
20604 @item
20605    constant names end with @code{_C}
20606 @item
20607    names defining package renamings end with @code{_R}
20608 @end itemize
20609
20610 @noindent
20611 For a private or incomplete type declaration the following checks are
20612 made for the defining name suffix:
20613
20614 @itemize @bullet
20615 @item
20616  For an incomplete type declaration: if the corresponding full type
20617   declaration is available, the defining identifier from the full type
20618   declaration is checked, but the defining identifier from the incomplete type
20619   declaration is not; otherwise the defining identifier from the incomplete
20620   type declaration is checked against the suffix specified for type
20621   declarations.
20622
20623 @item
20624  For a private type declaration (including private extensions),  the defining
20625   identifier from the private type declaration is checked against the type
20626   suffix (even if the corresponding full declaration is an access type
20627   declaration), and the defining identifier from the corresponding full type
20628   declaration is not checked.
20629 @end itemize
20630
20631 @noindent
20632 For a deferred constant, the defining name in the corresponding full constant
20633 declaration is not checked.
20634
20635 Defining names of formal types are not checked.
20636
20637 The rule may have the following parameters:
20638
20639 @itemize @bullet
20640 @item
20641 For the @option{+R} option:
20642 @table @code
20643 @item Default
20644 Sets the default listed above for all the names to be checked.
20645
20646 @item Type_Suffix=@emph{string}
20647 Specifies the suffix for a type name.
20648
20649 @item Access_Suffix=@emph{string}
20650 Specifies the suffix for an access type name. If
20651 this parameter is set, it overrides for access
20652 types the suffix set by the @code{Type_Suffix} parameter.
20653
20654 @item Constant_Suffix=@emph{string}
20655 Specifies the suffix for a constant name.
20656
20657 @item Renaming_Suffix=@emph{string}
20658 Specifies the suffix for a package renaming name.
20659 @end table
20660
20661 @item
20662 For the @option{-R} option:
20663 @table @code
20664 @item All_Suffixes
20665 Remove all the suffixes specified for the
20666 identifier suffix checks, whether by default or
20667 as specified by other rule parameters. All the
20668 checks for this rule are disabled as a result.
20669
20670 @item Type_Suffix
20671 Removes the suffix specified for types. This
20672 disables checks for types but does not disable
20673 any other checks for this rule (including the
20674 check for access type names if @code{Access_Suffix} is
20675 set).
20676
20677 @item Access_Suffix
20678 Removes the suffix specified for access types.
20679 This disables checks for access type names but
20680 does not disable any other checks for this rule.
20681 If @code{Type_Suffix} is set, access type names are
20682 checked as ordinary type names.
20683
20684 @item Constant_Suffix
20685 Removes the suffix specified for constants. This
20686 disables checks for constant names but does not
20687 disable any other checks for this rule.
20688
20689 @item Renaming_Suffix
20690 Removes the suffix specified for package
20691 renamings. This disables checks for package
20692 renamings but does not disable any other checks
20693 for this rule.
20694 @end table
20695 @end itemize
20696
20697 @noindent
20698 If more than one parameter is used, parameters must be separated by commas.
20699
20700 If more than one  option is specified for the @command{gnatcheck} invocation,
20701 a new option overrides the previous one(s).
20702
20703 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
20704 checks for all the
20705 name suffixes specified by previous options used for this rule.
20706
20707 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
20708 all the checks but keeps
20709 all the suffixes specified by previous options used for this rule.
20710
20711 The @emph{string} value must be a valid suffix for an Ada identifier (after
20712 trimming all the leading and trailing space characters, if any).
20713 Parameters are not case sensitive, except the @emph{string} part.
20714
20715 If any error is detected in a rule parameter, the parameter is ignored.
20716 In such a case the options that are set for the rule are not
20717 specified.
20718
20719
20720
20721 @node Multiple_Entries_In_Protected_Definitions
20722 @subsection @code{Multiple_Entries_In_Protected_Definitions}
20723 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
20724
20725 @noindent
20726 Flag each protected definition (i.e., each protected object/type declaration)
20727 that defines more than one entry.
20728 Diagnostic messages are generated for all the entry declarations
20729 except the first one. An entry family is counted as one entry. Entries from
20730 the private part of the protected definition are also checked.
20731
20732 This rule has no parameters.
20733
20734 @node Name_Clashes
20735 @subsection @code{Name_Clashes}
20736 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
20737
20738 @noindent
20739 Check that certain names are not used as defining identifiers. To activate
20740 this rule, you need to supply a reference to the dictionary file(s) as a rule
20741 parameter(s) (more then one dictionary file can be specified). If no
20742 dictionary file is set, this rule will not cause anything to be flagged.
20743 Only defining occurrences, not references, are checked.
20744 The check is not case-sensitive.
20745
20746 This rule is enabled by default, but without setting any corresponding
20747 dictionary file(s); thus the default effect is to do no checks.
20748
20749 A dictionary file is a plain text file. The maximum line length for this file
20750 is 1024 characters.  If the line is longer then this limit, extra characters
20751 are ignored.
20752
20753 Each line can be either an empty line, a comment line, or a line containing
20754 a list of identifiers separated by space or HT characters.
20755 A comment is an Ada-style comment (from @code{--} to end-of-line).
20756 Identifiers must follow the Ada syntax for identifiers.
20757 A line containing one or more identifiers may end with a comment.
20758
20759 @node Non_Qualified_Aggregates
20760 @subsection @code{Non_Qualified_Aggregates}
20761 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
20762
20763 @noindent
20764 Flag each non-qualified aggregate.
20765 A non-qualified aggregate is an
20766 aggregate that is not the expression of a qualified expression. A
20767 string literal is not considered an aggregate, but an array
20768 aggregate of a string type is considered as a normal aggregate.
20769 Aggregates of anonymous array types are not flagged.
20770
20771 This rule has no parameters.
20772
20773
20774 @node Non_Short_Circuit_Operators
20775 @subsection @code{Non_Short_Circuit_Operators}
20776 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
20777
20778 @noindent
20779 Flag all calls to predefined @code{and} and @code{or} operators for
20780 any boolean type. Calls to
20781 user-defined @code{and} and @code{or} and to operators defined by renaming
20782 declarations are not flagged. Calls to predefined @code{and} and @code{or}
20783 operators for modular types or boolean array types are not flagged.
20784
20785 This rule has no parameters.
20786
20787
20788
20789 @node Non_SPARK_Attributes
20790 @subsection @code{Non_SPARK_Attributes}
20791 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
20792
20793 @noindent
20794 The SPARK language defines the following subset of Ada 95 attribute
20795 designators as those that can be used in SPARK programs. The use of
20796 any other attribute is flagged.
20797
20798 @itemize @bullet
20799 @item @code{'Adjacent}
20800 @item @code{'Aft}
20801 @item @code{'Base}
20802 @item @code{'Ceiling}
20803 @item @code{'Component_Size}
20804 @item @code{'Compose}
20805 @item @code{'Copy_Sign}
20806 @item @code{'Delta}
20807 @item @code{'Denorm}
20808 @item @code{'Digits}
20809 @item @code{'Exponent}
20810 @item @code{'First}
20811 @item @code{'Floor}
20812 @item @code{'Fore}
20813 @item @code{'Fraction}
20814 @item @code{'Last}
20815 @item @code{'Leading_Part}
20816 @item @code{'Length}
20817 @item @code{'Machine}
20818 @item @code{'Machine_Emax}
20819 @item @code{'Machine_Emin}
20820 @item @code{'Machine_Mantissa}
20821 @item @code{'Machine_Overflows}
20822 @item @code{'Machine_Radix}
20823 @item @code{'Machine_Rounds}
20824 @item @code{'Max}
20825 @item @code{'Min}
20826 @item @code{'Model}
20827 @item @code{'Model_Emin}
20828 @item @code{'Model_Epsilon}
20829 @item @code{'Model_Mantissa}
20830 @item @code{'Model_Small}
20831 @item @code{'Modulus}
20832 @item @code{'Pos}
20833 @item @code{'Pred}
20834 @item @code{'Range}
20835 @item @code{'Remainder}
20836 @item @code{'Rounding}
20837 @item @code{'Safe_First}
20838 @item @code{'Safe_Last}
20839 @item @code{'Scaling}
20840 @item @code{'Signed_Zeros}
20841 @item @code{'Size}
20842 @item @code{'Small}
20843 @item @code{'Succ}
20844 @item @code{'Truncation}
20845 @item @code{'Unbiased_Rounding}
20846 @item @code{'Val}
20847 @item @code{'Valid}
20848 @end itemize
20849
20850 @noindent
20851 This rule has no parameters.
20852
20853
20854 @node Non_Tagged_Derived_Types
20855 @subsection @code{Non_Tagged_Derived_Types}
20856 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
20857
20858 @noindent
20859 Flag all derived type declarations that do not have a record extension part.
20860
20861 This rule has no parameters.
20862
20863
20864
20865 @node Non_Visible_Exceptions
20866 @subsection @code{Non_Visible_Exceptions}
20867 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
20868
20869 @noindent
20870 Flag constructs leading to the possibility of propagating an exception
20871 out of the scope in which the exception is declared.
20872 Two cases are detected:
20873
20874 @itemize @bullet
20875 @item
20876 An exception declaration in a subprogram body, task body or block
20877 statement is flagged if the body or statement does not contain a handler for
20878 that exception or a handler with an @code{others} choice.
20879
20880 @item
20881 A @code{raise} statement in an exception handler of a subprogram body,
20882 task body or block statement is flagged if it (re)raises a locally
20883 declared exception.  This may occur under the following circumstances:
20884 @itemize @minus
20885 @item
20886 it explicitly raises a locally declared exception, or
20887 @item
20888 it does not specify an exception name (i.e., it is simply @code{raise;})
20889 and the enclosing handler contains a locally declared exception in its
20890 exception choices.
20891 @end itemize
20892 @end itemize
20893
20894 @noindent
20895 Renamings of local exceptions are not flagged.
20896
20897 This rule has no parameters.
20898
20899
20900 @node Numeric_Literals
20901 @subsection @code{Numeric_Literals}
20902 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
20903
20904 @noindent
20905 Flag each use of a numeric literal in an index expression, and in any
20906 circumstance except for the following:
20907
20908 @itemize @bullet
20909 @item
20910 a literal occurring in the initialization expression for a constant
20911 declaration or a named number declaration, or
20912
20913 @item
20914 an integer literal that is less than or equal to a value
20915 specified by the @option{N} rule parameter.
20916 @end itemize
20917
20918 @noindent
20919 This rule may have the following parameters for the @option{+R} option:
20920
20921 @table @asis
20922 @item @emph{N}
20923 @emph{N} is an integer literal used as the maximal value that is not flagged
20924 (i.e., integer literals not exceeding this value are allowed)
20925
20926 @item @code{ALL}
20927 All integer literals are flagged
20928 @end table
20929
20930 @noindent
20931 If no parameters are set, the maximum unflagged value is 1.
20932
20933 The last specified check limit (or the fact that there is no limit at
20934 all) is used when multiple @option{+R} options appear.
20935
20936 The @option{-R} option for this rule has no parameters.
20937 It disables the rule but retains the last specified maximum unflagged value.
20938 If the @option{+R} option subsequently appears, this value is used as the
20939 threshold for the check.
20940
20941
20942 @node OTHERS_In_Aggregates
20943 @subsection @code{OTHERS_In_Aggregates}
20944 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
20945
20946 @noindent
20947 Flag each use of an @code{others} choice in extension aggregates.
20948 In record and array aggregates, an @code{others} choice is flagged unless
20949 it is used to refer to all components, or to all but one component.
20950
20951 If, in case of a named array aggregate, there are two associations, one
20952 with an @code{others} choice and another with a discrete range, the
20953 @code{others} choice is flagged even if the discrete range specifies
20954 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
20955
20956 This rule has no parameters.
20957
20958 @node OTHERS_In_CASE_Statements
20959 @subsection @code{OTHERS_In_CASE_Statements}
20960 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
20961
20962 @noindent
20963 Flag any use of an @code{others} choice in a @code{case} statement.
20964
20965 This rule has no parameters.
20966
20967 @node OTHERS_In_Exception_Handlers
20968 @subsection @code{OTHERS_In_Exception_Handlers}
20969 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
20970
20971 @noindent
20972 Flag any use of an @code{others} choice in an exception handler.
20973
20974 This rule has no parameters.
20975
20976
20977 @node Outer_Loop_Exits
20978 @subsection @code{Outer_Loop_Exits}
20979 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
20980
20981 @noindent
20982 Flag each @code{exit} statement containing a loop name that is not the name
20983 of the immediately enclosing @code{loop} statement.
20984
20985 This rule has no parameters.
20986
20987
20988 @node Overloaded_Operators
20989 @subsection @code{Overloaded_Operators}
20990 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
20991
20992 @noindent
20993 Flag each function declaration that overloads an operator symbol.
20994 A function body is checked only if the body does not have a
20995 separate spec. Formal functions are also checked. For a
20996 renaming declaration, only renaming-as-declaration is checked
20997
20998 This rule has no parameters.
20999
21000
21001 @node Overly_Nested_Control_Structures
21002 @subsection @code{Overly_Nested_Control_Structures}
21003 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
21004
21005 @noindent
21006 Flag each control structure whose nesting level exceeds the value provided
21007 in the rule parameter.
21008
21009 The control structures checked are the following:
21010
21011 @itemize @bullet
21012 @item    @code{if} statement
21013 @item    @code{case} statement
21014 @item    @code{loop} statement
21015 @item    Selective accept statement
21016 @item    Timed entry call statement
21017 @item    Conditional entry call
21018 @item    Asynchronous select statement
21019 @end itemize
21020
21021 @noindent
21022 The rule may have the following parameter for the @option{+R} option:
21023
21024 @table @emph
21025 @item N
21026 Positive integer specifying the maximal control structure nesting
21027 level that is not flagged
21028 @end table
21029
21030 @noindent
21031 If the parameter for the @option{+R} option is not a positive integer,
21032 the parameter is ignored and the rule is turned ON with the most recently
21033 specified maximal non-flagged nesting level.
21034
21035 If more then one  option is specified for the gnatcheck call, the later option and
21036 new parameter override the previous one(s).
21037
21038 A @option{+R} option with no parameter turns the rule ON using the maximal
21039 non-flagged nesting level specified by the most recent @option{+R} option with
21040 a parameter, or the value 4 if there is no such previous @option{+R} option.
21041
21042
21043
21044 @node Parameters_Out_Of_Order
21045 @subsection @code{Parameters_Out_Of_Order}
21046 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
21047
21048 @noindent
21049 Flag each subprogram and entry declaration whose formal parameters are not
21050 ordered according to the following scheme:
21051
21052 @itemize @bullet
21053
21054 @item @code{in} and @code{access} parameters first,
21055 then @code{in out} parameters,
21056 and then @code{out} parameters;
21057
21058 @item for @code{in} mode, parameters with default initialization expressions
21059 occur last
21060 @end itemize
21061
21062 @noindent
21063 Only the first violation of the described order is flagged.
21064
21065 The following constructs are checked:
21066
21067 @itemize @bullet
21068 @item   subprogram declarations (including null procedures);
21069 @item   generic subprogram declarations;
21070 @item   formal subprogram declarations;
21071 @item   entry declarations;
21072 @item   subprogram bodies and subprogram body stubs that do not
21073 have separate specifications
21074 @end itemize
21075
21076 @noindent
21077 Subprogram renamings are not checked.
21078
21079 This rule has no parameters.
21080
21081
21082 @node Positional_Actuals_For_Defaulted_Generic_Parameters
21083 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
21084 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
21085
21086 @noindent
21087 Flag each generic actual parameter corresponding to a generic formal
21088 parameter with a default initialization, if positional notation is used.
21089
21090 This rule has no parameters.
21091
21092 @node Positional_Actuals_For_Defaulted_Parameters
21093 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
21094 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
21095
21096 @noindent
21097 Flag each actual parameter to a subprogram or entry call where the
21098 corresponding formal parameter has a default expression, if positional
21099 notation is used.
21100
21101 This rule has no parameters.
21102
21103 @node Positional_Components
21104 @subsection @code{Positional_Components}
21105 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
21106
21107 @noindent
21108 Flag each array, record and extension aggregate that includes positional
21109 notation.
21110
21111 This rule has no parameters.
21112
21113
21114 @node Positional_Generic_Parameters
21115 @subsection @code{Positional_Generic_Parameters}
21116 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
21117
21118 @noindent
21119 Flag each instantiation using positional parameter notation.
21120
21121 This rule has no parameters.
21122
21123
21124 @node Positional_Parameters
21125 @subsection @code{Positional_Parameters}
21126 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
21127
21128 @noindent
21129 Flag each subprogram or entry call using positional parameter notation,
21130 except for the following:
21131
21132 @itemize @bullet
21133 @item
21134 Invocations of prefix or infix operators are not flagged
21135 @item
21136 If the called subprogram or entry has only one formal parameter,
21137 the call is not flagged;
21138 @item
21139 If a subprogram call uses the @emph{Object.Operation} notation, then
21140 @itemize @minus
21141 @item
21142 the first parameter (that is, @emph{Object}) is not flagged;
21143 @item
21144 if the called subprogram has only two parameters, the second parameter
21145 of the call is not flagged;
21146 @end itemize
21147 @end itemize
21148
21149 @noindent
21150 This rule has no parameters.
21151
21152
21153
21154
21155 @node Predefined_Numeric_Types
21156 @subsection @code{Predefined_Numeric_Types}
21157 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
21158
21159 @noindent
21160 Flag each explicit use of the name of any numeric type or subtype defined
21161 in package @code{Standard}.
21162
21163 The rationale for this rule is to detect when the
21164 program may depend on platform-specific characteristics of the implementation
21165 of the predefined numeric types. Note that this rule is over-pessimistic;
21166 for example, a program that uses @code{String} indexing
21167 likely needs a variable of type @code{Integer}.
21168 Another example is the flagging of predefined numeric types with explicit
21169 constraints:
21170
21171 @smallexample @c ada
21172     subtype My_Integer is Integer range Left .. Right;
21173     Vy_Var : My_Integer;
21174 @end smallexample
21175
21176 @noindent
21177 This rule detects only numeric types and subtypes defined in
21178 @code{Standard}. The use of numeric types and subtypes defined in other
21179 predefined packages (such as @code{System.Any_Priority} or
21180 @code{Ada.Text_IO.Count}) is not flagged
21181
21182 This rule has no parameters.
21183
21184
21185
21186 @node Raising_External_Exceptions
21187 @subsection @code{Raising_External_Exceptions}
21188 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
21189
21190 @noindent
21191 Flag any @code{raise} statement, in a program unit declared in a library
21192 package or in a generic library package, for an exception that is
21193 neither a predefined exception nor an exception that is also declared (or
21194 renamed) in the visible part of the package.
21195
21196 This rule has no parameters.
21197
21198
21199
21200 @node Raising_Predefined_Exceptions
21201 @subsection @code{Raising_Predefined_Exceptions}
21202 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
21203
21204 @noindent
21205 Flag each @code{raise} statement that raises a predefined exception
21206 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
21207 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
21208
21209 This rule has no parameters.
21210
21211
21212 @ignore
21213 @node Recursion
21214 @subsection @code{Recursion} (under construction, GLOBAL)
21215 @cindex @code{Recursion} rule (for @command{gnatcheck})
21216
21217 @noindent
21218 Flag recursive subprograms (cycles in the call graph). Declarations, and not
21219 calls, of recursive subprograms are detected.
21220
21221 This rule has no parameters.
21222 @end ignore
21223
21224 @ignore
21225 @node Side_Effect_Functions
21226 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
21227 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
21228
21229 @noindent
21230 Flag functions with side effects.
21231
21232 We define a side effect as changing any data object that is not local for the
21233 body of this function.
21234
21235 At the moment, we do NOT consider a side effect any input-output operations
21236 (changing a state or a content of any file).
21237
21238 We do not consider protected functions for this rule (???)
21239
21240 There are the following sources of side effect:
21241
21242 @enumerate
21243 @item Explicit (or direct) side-effect:
21244
21245 @itemize @bullet
21246 @item
21247 direct assignment to a non-local variable;
21248
21249 @item
21250 direct call to an entity that is known to change some data object that is
21251      not local for the body of this function (Note, that if F1 calls F2 and F2
21252      does have a side effect, this does not automatically mean that F1 also
21253      have a side effect, because it may be the case that F2 is declared in
21254      F1's body and it changes some data object that is global for F2, but
21255      local for F1);
21256 @end itemize
21257
21258 @item Indirect side-effect:
21259 @itemize @bullet
21260 @item
21261 Subprogram calls implicitly issued by:
21262 @itemize @bullet
21263 @item
21264 computing initialization expressions from type declarations as a part
21265          of object elaboration or allocator evaluation;
21266 @item
21267 computing implicit parameters of subprogram or entry calls or generic
21268          instantiations;
21269 @end itemize
21270
21271 @item
21272 activation of a task that change some non-local data object (directly or
21273      indirectly);
21274
21275 @item
21276 elaboration code of a package that is a result of a package instantiation;
21277
21278 @item
21279 controlled objects;
21280 @end itemize
21281
21282 @item Situations when we can suspect a side-effect, but the full static check
21283 is either impossible or too hard:
21284 @itemize @bullet
21285 @item
21286 assignment to access variables or to the objects pointed by access
21287      variables;
21288
21289 @item
21290 call to a subprogram pointed by access-to-subprogram value
21291
21292 @item
21293 dispatching calls;
21294 @end itemize
21295 @end enumerate
21296
21297 @noindent
21298 This rule has no parameters.
21299 @end ignore
21300
21301 @node Slices
21302 @subsection @code{Slices}
21303 @cindex @code{Slices} rule (for @command{gnatcheck})
21304
21305 @noindent
21306 Flag all uses of array slicing
21307
21308 This rule has no parameters.
21309
21310
21311 @node Unassigned_OUT_Parameters
21312 @subsection @code{Unassigned_OUT_Parameters}
21313 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
21314
21315 @noindent
21316 Flags procedures' @code{out} parameters that are not assigned, and
21317 identifies the contexts in which the assignments are missing.
21318
21319 An @code{out} parameter is flagged in the statements in the procedure
21320 body's handled sequence of statements (before the procedure body's
21321 @code{exception} part, if any) if this sequence of statements contains
21322 no assignments to the parameter.
21323
21324 An @code{out} parameter is flagged in an exception handler in the exception
21325 part of the procedure body's handled sequence of statements if the handler
21326 contains no assignment to the parameter.
21327
21328 Bodies of generic procedures are also considered.
21329
21330 The following are treated as assignments to an @code{out} parameter:
21331
21332 @itemize @bullet
21333 @item
21334 an assignment statement, with the parameter or some component as the target;
21335
21336 @item
21337 passing the parameter (or one of its components) as an @code{out} or
21338 @code{in out} parameter.
21339 @end itemize
21340
21341 @noindent
21342 This rule does not have any parameters.
21343
21344
21345
21346 @node Uncommented_BEGIN_In_Package_Bodies
21347 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
21348 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
21349
21350 @noindent
21351 Flags each package body with declarations and a statement part that does not
21352 include a trailing comment on the line containing the @code{begin} keyword;
21353 this trailing comment needs to specify the package name and nothing else.
21354 The @code{begin} is not flagged if the package body does not
21355 contain any declarations.
21356
21357 If the @code{begin} keyword is placed on the
21358 same line as the last declaration or the first statement, it is flagged
21359 independently of whether the line contains a trailing comment. The
21360 diagnostic message is attached to the line containing the first statement.
21361
21362 This rule has no parameters.
21363
21364
21365 @node Unconstrained_Array_Returns
21366 @subsection @code{Unconstrained_Array_Returns}
21367 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
21368
21369 @noindent
21370 Flag each function returning an unconstrained array. Function declarations,
21371 function bodies (and body stubs) having no separate specifications,
21372 and generic function instantiations are checked.
21373 Generic function declarations, function calls and function renamings are
21374 not checked.
21375
21376 This rule has no parameters.
21377
21378 @node Universal_Ranges
21379 @subsection @code{Universal_Ranges}
21380 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
21381
21382 @noindent
21383 Flag discrete ranges that are a part of an index constraint, constrained
21384 array definition, or @code{for}-loop parameter specification, and whose bounds
21385 are both of type @i{universal_integer}. Ranges that have at least one
21386 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
21387 or an expression of non-universal type) are not flagged.
21388
21389 This rule has no parameters.
21390
21391
21392 @node Unnamed_Blocks_And_Loops
21393 @subsection @code{Unnamed_Blocks_And_Loops}
21394 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
21395
21396 @noindent
21397 Flag each unnamed block statement and loop statement.
21398
21399 The rule has no parameters.
21400
21401
21402
21403 @ignore
21404 @node Unused_Subprograms
21405 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
21406 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
21407
21408 @noindent
21409 Flag all unused subprograms.
21410
21411 This rule has no parameters.
21412 @end ignore
21413
21414
21415
21416
21417 @node USE_PACKAGE_Clauses
21418 @subsection @code{USE_PACKAGE_Clauses}
21419 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
21420
21421 @noindent
21422 Flag all @code{use} clauses for packages; @code{use type} clauses are
21423 not flagged.
21424
21425 This rule has no parameters.
21426
21427
21428
21429 @node Volatile_Objects_Without_Address_Clauses
21430 @subsection @code{Volatile_Objects_Without_Address_Clauses}
21431 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
21432
21433 @noindent
21434 Flag each volatile object that does not have an address clause.
21435
21436 The following check is made: if the pragma @code{Volatile} is applied to a
21437 data object or to its type, then an address clause must
21438 be supplied for this object.
21439
21440 This rule does not check the components of data objects,
21441 array components that are volatile as a result of the pragma
21442 @code{Volatile_Components}, or objects that are volatile because
21443 they are atomic as a result of pragmas @code{Atomic} or
21444 @code{Atomic_Components}.
21445
21446 Only variable declarations, and not constant declarations, are checked.
21447
21448 This rule has no parameters.
21449
21450
21451 @c *********************************
21452 @node Creating Sample Bodies Using gnatstub
21453 @chapter Creating Sample Bodies Using @command{gnatstub}
21454 @findex gnatstub
21455
21456 @noindent
21457 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
21458 for library unit declarations.
21459
21460 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
21461 driver (see @ref{The GNAT Driver and Project Files}).
21462
21463 To create a body stub, @command{gnatstub} has to compile the library
21464 unit declaration. Therefore, bodies can be created only for legal
21465 library units. Moreover, if a library unit depends semantically upon
21466 units located outside the current directory, you have to provide
21467 the source search path when calling @command{gnatstub}, see the description
21468 of @command{gnatstub} switches below.
21469
21470 @menu
21471 * Running gnatstub::
21472 * Switches for gnatstub::
21473 @end menu
21474
21475 @node Running gnatstub
21476 @section Running @command{gnatstub}
21477
21478 @noindent
21479 @command{gnatstub} has the command-line interface of the form
21480
21481 @smallexample
21482 $ gnatstub [switches] filename [directory]
21483 @end smallexample
21484
21485 @noindent
21486 where
21487 @table @emph
21488 @item filename
21489 is the name of the source file that contains a library unit declaration
21490 for which a body must be created. The file name may contain the path
21491 information.
21492 The file name does not have to follow the GNAT file name conventions. If the
21493 name
21494 does not follow GNAT file naming conventions, the name of the body file must
21495 be provided
21496 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
21497 If the file name follows the GNAT file naming
21498 conventions and the name of the body file is not provided,
21499 @command{gnatstub}
21500 creates the name
21501 of the body file from the argument file name by replacing the @file{.ads}
21502 suffix
21503 with the @file{.adb} suffix.
21504
21505 @item directory
21506 indicates the directory in which the body stub is to be placed (the default
21507 is the
21508 current directory)
21509
21510 @item switches
21511 is an optional sequence of switches as described in the next section
21512 @end table
21513
21514 @node Switches for gnatstub
21515 @section Switches for @command{gnatstub}
21516
21517 @table @option
21518 @c !sort!
21519
21520 @item ^-f^/FULL^
21521 @cindex @option{^-f^/FULL^} (@command{gnatstub})
21522 If the destination directory already contains a file with the name of the
21523 body file
21524 for the argument spec file, replace it with the generated body stub.
21525
21526 @item ^-hs^/HEADER=SPEC^
21527 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
21528 Put the comment header (i.e., all the comments preceding the
21529 compilation unit) from the source of the library unit declaration
21530 into the body stub.
21531
21532 @item ^-hg^/HEADER=GENERAL^
21533 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
21534 Put a sample comment header into the body stub.
21535
21536 @ifclear vms
21537 @item -IDIR
21538 @cindex @option{-IDIR} (@command{gnatstub})
21539 @itemx -I-
21540 @cindex @option{-I-} (@command{gnatstub})
21541 @end ifclear
21542 @ifset vms
21543 @item /NOCURRENT_DIRECTORY
21544 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
21545 @end ifset
21546 ^These switches have ^This switch has^ the same meaning as in calls to
21547 @command{gcc}.
21548 ^They define ^It defines ^ the source search path in the call to
21549 @command{gcc} issued
21550 by @command{gnatstub} to compile an argument source file.
21551
21552 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
21553 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
21554 This switch has the same meaning as in calls to @command{gcc}.
21555 It defines the additional configuration file to be passed to the call to
21556 @command{gcc} issued
21557 by @command{gnatstub} to compile an argument source file.
21558
21559 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
21560 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
21561 (@var{n} is a non-negative integer). Set the maximum line length in the
21562 body stub to @var{n}; the default is 79. The maximum value that can be
21563 specified is 32767. Note that in the special case of configuration
21564 pragma files, the maximum is always 32767 regardless of whether or
21565 not this switch appears.
21566
21567 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
21568 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
21569 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
21570 the generated body sample to @var{n}.
21571 The default indentation is 3.
21572
21573 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
21574 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
21575 Order local bodies alphabetically. (By default local bodies are ordered
21576 in the same way as the corresponding local specs in the argument spec file.)
21577
21578 @item ^-i^/INDENTATION=^@var{n}
21579 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
21580 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
21581
21582 @item ^-k^/TREE_FILE=SAVE^
21583 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
21584 Do not remove the tree file (i.e., the snapshot of the compiler internal
21585 structures used by @command{gnatstub}) after creating the body stub.
21586
21587 @item ^-l^/LINE_LENGTH=^@var{n}
21588 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
21589 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
21590
21591 @item ^-o^/BODY=^@var{body-name}
21592 @cindex @option{^-o^/BODY^} (@command{gnatstub})
21593 Body file name.  This should be set if the argument file name does not
21594 follow
21595 the GNAT file naming
21596 conventions. If this switch is omitted the default name for the body will be
21597 obtained
21598 from the argument file name according to the GNAT file naming conventions.
21599
21600 @item ^-q^/QUIET^
21601 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
21602 Quiet mode: do not generate a confirmation when a body is
21603 successfully created, and do not generate a message when a body is not
21604 required for an
21605 argument unit.
21606
21607 @item ^-r^/TREE_FILE=REUSE^
21608 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
21609 Reuse the tree file (if it exists) instead of creating it.  Instead of
21610 creating the tree file for the library unit declaration, @command{gnatstub}
21611 tries to find it in the current directory and use it for creating
21612 a body. If the tree file is not found, no body is created. This option
21613 also implies @option{^-k^/SAVE^}, whether or not
21614 the latter is set explicitly.
21615
21616 @item ^-t^/TREE_FILE=OVERWRITE^
21617 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
21618 Overwrite the existing tree file.  If the current directory already
21619 contains the file which, according to the GNAT file naming rules should
21620 be considered as a tree file for the argument source file,
21621 @command{gnatstub}
21622 will refuse to create the tree file needed to create a sample body
21623 unless this option is set.
21624
21625 @item ^-v^/VERBOSE^
21626 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
21627 Verbose mode: generate version information.
21628
21629 @end table
21630
21631 @node Other Utility Programs
21632 @chapter Other Utility Programs
21633
21634 @noindent
21635 This chapter discusses some other utility programs available in the Ada
21636 environment.
21637
21638 @menu
21639 * Using Other Utility Programs with GNAT::
21640 * The External Symbol Naming Scheme of GNAT::
21641 * Converting Ada Files to html with gnathtml::
21642 * Installing gnathtml::
21643 @ifset vms
21644 * LSE::
21645 * Profiling::
21646 @end ifset
21647 @end menu
21648
21649 @node Using Other Utility Programs with GNAT
21650 @section Using Other Utility Programs with GNAT
21651
21652 @noindent
21653 The object files generated by GNAT are in standard system format and in
21654 particular the debugging information uses this format. This means
21655 programs generated by GNAT can be used with existing utilities that
21656 depend on these formats.
21657
21658 @ifclear vms
21659 In general, any utility program that works with C will also often work with
21660 Ada programs generated by GNAT. This includes software utilities such as
21661 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
21662 as Purify.
21663 @end ifclear
21664
21665 @node The External Symbol Naming Scheme of GNAT
21666 @section The External Symbol Naming Scheme of GNAT
21667
21668 @noindent
21669 In order to interpret the output from GNAT, when using tools that are
21670 originally intended for use with other languages, it is useful to
21671 understand the conventions used to generate link names from the Ada
21672 entity names.
21673
21674 All link names are in all lowercase letters. With the exception of library
21675 procedure names, the mechanism used is simply to use the full expanded
21676 Ada name with dots replaced by double underscores. For example, suppose
21677 we have the following package spec:
21678
21679 @smallexample @c ada
21680 @group
21681 @cartouche
21682 package QRS is
21683    MN : Integer;
21684 end QRS;
21685 @end cartouche
21686 @end group
21687 @end smallexample
21688
21689 @noindent
21690 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
21691 the corresponding link name is @code{qrs__mn}.
21692 @findex Export
21693 Of course if a @code{pragma Export} is used this may be overridden:
21694
21695 @smallexample @c ada
21696 @group
21697 @cartouche
21698 package Exports is
21699    Var1 : Integer;
21700    pragma Export (Var1, C, External_Name => "var1_name");
21701    Var2 : Integer;
21702    pragma Export (Var2, C, Link_Name => "var2_link_name");
21703 end Exports;
21704 @end cartouche
21705 @end group
21706 @end smallexample
21707
21708 @noindent
21709 In this case, the link name for @var{Var1} is whatever link name the
21710 C compiler would assign for the C function @var{var1_name}. This typically
21711 would be either @var{var1_name} or @var{_var1_name}, depending on operating
21712 system conventions, but other possibilities exist. The link name for
21713 @var{Var2} is @var{var2_link_name}, and this is not operating system
21714 dependent.
21715
21716 @findex _main
21717 One exception occurs for library level procedures. A potential ambiguity
21718 arises between the required name @code{_main} for the C main program,
21719 and the name we would otherwise assign to an Ada library level procedure
21720 called @code{Main} (which might well not be the main program).
21721
21722 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
21723 names. So if we have a library level procedure such as
21724
21725 @smallexample @c ada
21726 @group
21727 @cartouche
21728 procedure Hello (S : String);
21729 @end cartouche
21730 @end group
21731 @end smallexample
21732
21733 @noindent
21734 the external name of this procedure will be @var{_ada_hello}.
21735
21736
21737 @node Converting Ada Files to html with gnathtml
21738 @section Converting Ada Files to HTML with @code{gnathtml}
21739
21740 @noindent
21741 This @code{Perl} script allows Ada source files to be browsed using
21742 standard Web browsers. For installation procedure, see the section
21743 @xref{Installing gnathtml}.
21744
21745 Ada reserved keywords are highlighted in a bold font and Ada comments in
21746 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
21747 switch to suppress the generation of cross-referencing information, user
21748 defined variables and types will appear in a different color; you will
21749 be able to click on any identifier and go to its declaration.
21750
21751 The command line is as follow:
21752 @smallexample
21753 $ perl gnathtml.pl [^switches^options^] ada-files
21754 @end smallexample
21755
21756 @noindent
21757 You can pass it as many Ada files as you want. @code{gnathtml} will generate
21758 an html file for every ada file, and a global file called @file{index.htm}.
21759 This file is an index of every identifier defined in the files.
21760
21761 The available ^switches^options^ are the following ones:
21762
21763 @table @option
21764 @item -83
21765 @cindex @option{-83} (@code{gnathtml})
21766 Only the Ada 83 subset of keywords will be highlighted.
21767
21768 @item -cc @var{color}
21769 @cindex @option{-cc} (@code{gnathtml})
21770 This option allows you to change the color used for comments. The default
21771 value is green. The color argument can be any name accepted by html.
21772
21773 @item -d
21774 @cindex @option{-d} (@code{gnathtml})
21775 If the Ada files depend on some other files (for instance through
21776 @code{with} clauses, the latter files will also be converted to html.
21777 Only the files in the user project will be converted to html, not the files
21778 in the run-time library itself.
21779
21780 @item -D
21781 @cindex @option{-D} (@code{gnathtml})
21782 This command is the same as @option{-d} above, but @command{gnathtml} will
21783 also look for files in the run-time library, and generate html files for them.
21784
21785 @item -ext @var{extension}
21786 @cindex @option{-ext} (@code{gnathtml})
21787 This option allows you to change the extension of the generated HTML files.
21788 If you do not specify an extension, it will default to @file{htm}.
21789
21790 @item -f
21791 @cindex @option{-f} (@code{gnathtml})
21792 By default, gnathtml will generate html links only for global entities
21793 ('with'ed units, global variables and types,@dots{}).  If you specify
21794 @option{-f} on the command line, then links will be generated for local
21795 entities too.
21796
21797 @item -l @var{number}
21798 @cindex @option{-l} (@code{gnathtml})
21799 If this ^switch^option^ is provided and @var{number} is not 0, then
21800 @code{gnathtml} will number the html files every @var{number} line.
21801
21802 @item -I @var{dir}
21803 @cindex @option{-I} (@code{gnathtml})
21804 Specify a directory to search for library files (@file{.ALI} files) and
21805 source files. You can provide several -I switches on the command line,
21806 and the directories will be parsed in the order of the command line.
21807
21808 @item -o @var{dir}
21809 @cindex @option{-o} (@code{gnathtml})
21810 Specify the output directory for html files. By default, gnathtml will
21811 saved the generated html files in a subdirectory named @file{html/}.
21812
21813 @item -p @var{file}
21814 @cindex @option{-p} (@code{gnathtml})
21815 If you are using Emacs and the most recent Emacs Ada mode, which provides
21816 a full Integrated Development Environment for compiling, checking,
21817 running and debugging applications, you may use @file{.gpr} files
21818 to give the directories where Emacs can find sources and object files.
21819
21820 Using this ^switch^option^, you can tell gnathtml to use these files.
21821 This allows you to get an html version of your application, even if it
21822 is spread over multiple directories.
21823
21824 @item -sc @var{color}
21825 @cindex @option{-sc} (@code{gnathtml})
21826 This ^switch^option^ allows you to change the color used for symbol
21827 definitions.
21828 The default value is red. The color argument can be any name accepted by html.
21829
21830 @item -t @var{file}
21831 @cindex @option{-t} (@code{gnathtml})
21832 This ^switch^option^ provides the name of a file. This file contains a list of
21833 file names to be converted, and the effect is exactly as though they had
21834 appeared explicitly on the command line. This
21835 is the recommended way to work around the command line length limit on some
21836 systems.
21837
21838 @end table
21839
21840 @node Installing gnathtml
21841 @section Installing @code{gnathtml}
21842
21843 @noindent
21844 @code{Perl} needs to be installed on your machine to run this script.
21845 @code{Perl} is freely available for almost every architecture and
21846 Operating System via the Internet.
21847
21848 On Unix systems, you  may want to modify  the  first line of  the script
21849 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
21850 is. The syntax of this line is:
21851 @smallexample
21852 #!full_path_name_to_perl
21853 @end smallexample
21854
21855 @noindent
21856 Alternatively, you may run the script using the following command line:
21857
21858 @smallexample
21859 $ perl gnathtml.pl [switches] files
21860 @end smallexample
21861
21862 @ifset vms
21863 @node LSE
21864 @section LSE
21865 @findex LSE
21866
21867 @noindent
21868 The GNAT distribution provides an Ada 95 template for the HP Language
21869 Sensitive Editor (LSE), a component of DECset. In order to
21870 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
21871
21872 @node Profiling
21873 @section Profiling
21874 @findex PCA
21875
21876 @noindent
21877 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
21878 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
21879 the collection phase with the /DEBUG qualifier.
21880
21881 @smallexample
21882 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
21883 $ DEFINE LIB$DEBUG PCA$COLLECTOR
21884 $ RUN/DEBUG <PROGRAM_NAME>
21885 @end smallexample
21886 @noindent
21887 @end ifset
21888
21889 @node Running and Debugging Ada Programs
21890 @chapter Running and Debugging Ada Programs
21891 @cindex Debugging
21892
21893 @noindent
21894 This chapter discusses how to debug Ada programs.
21895 @ifset vms
21896 It applies to GNAT on the Alpha OpenVMS platform;
21897 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
21898 since HP has implemented Ada support in the OpenVMS debugger on I64.
21899 @end ifset
21900
21901 An incorrect Ada program may be handled in three ways by the GNAT compiler:
21902
21903 @enumerate
21904 @item
21905 The illegality may be a violation of the static semantics of Ada. In
21906 that case GNAT diagnoses the constructs in the program that are illegal.
21907 It is then a straightforward matter for the user to modify those parts of
21908 the program.
21909
21910 @item
21911 The illegality may be a violation of the dynamic semantics of Ada. In
21912 that case the program compiles and executes, but may generate incorrect
21913 results, or may terminate abnormally with some exception.
21914
21915 @item
21916 When presented with a program that contains convoluted errors, GNAT
21917 itself may terminate abnormally without providing full diagnostics on
21918 the incorrect user program.
21919 @end enumerate
21920
21921 @menu
21922 * The GNAT Debugger GDB::
21923 * Running GDB::
21924 * Introduction to GDB Commands::
21925 * Using Ada Expressions::
21926 * Calling User-Defined Subprograms::
21927 * Using the Next Command in a Function::
21928 * Ada Exceptions::
21929 * Ada Tasks::
21930 * Debugging Generic Units::
21931 * GNAT Abnormal Termination or Failure to Terminate::
21932 * Naming Conventions for GNAT Source Files::
21933 * Getting Internal Debugging Information::
21934 * Stack Traceback::
21935 @end menu
21936
21937 @cindex Debugger
21938 @findex gdb
21939
21940 @node The GNAT Debugger GDB
21941 @section The GNAT Debugger GDB
21942
21943 @noindent
21944 @code{GDB} is a general purpose, platform-independent debugger that
21945 can be used to debug mixed-language programs compiled with @command{gcc},
21946 and in particular is capable of debugging Ada programs compiled with
21947 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
21948 complex Ada data structures.
21949
21950 The manual @cite{Debugging with GDB}
21951 @ifset vms
21952 , located in the GNU:[DOCS] directory,
21953 @end ifset
21954 contains full details on the usage of @code{GDB}, including a section on
21955 its usage on programs. This manual should be consulted for full
21956 details. The section that follows is a brief introduction to the
21957 philosophy and use of @code{GDB}.
21958
21959 When GNAT programs are compiled, the compiler optionally writes debugging
21960 information into the generated object file, including information on
21961 line numbers, and on declared types and variables. This information is
21962 separate from the generated code. It makes the object files considerably
21963 larger, but it does not add to the size of the actual executable that
21964 will be loaded into memory, and has no impact on run-time performance. The
21965 generation of debug information is triggered by the use of the
21966 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
21967 used to carry out the compilations. It is important to emphasize that
21968 the use of these options does not change the generated code.
21969
21970 The debugging information is written in standard system formats that
21971 are used by many tools, including debuggers and profilers. The format
21972 of the information is typically designed to describe C types and
21973 semantics, but GNAT implements a translation scheme which allows full
21974 details about Ada types and variables to be encoded into these
21975 standard C formats. Details of this encoding scheme may be found in
21976 the file exp_dbug.ads in the GNAT source distribution. However, the
21977 details of this encoding are, in general, of no interest to a user,
21978 since @code{GDB} automatically performs the necessary decoding.
21979
21980 When a program is bound and linked, the debugging information is
21981 collected from the object files, and stored in the executable image of
21982 the program. Again, this process significantly increases the size of
21983 the generated executable file, but it does not increase the size of
21984 the executable program itself. Furthermore, if this program is run in
21985 the normal manner, it runs exactly as if the debug information were
21986 not present, and takes no more actual memory.
21987
21988 However, if the program is run under control of @code{GDB}, the
21989 debugger is activated.  The image of the program is loaded, at which
21990 point it is ready to run.  If a run command is given, then the program
21991 will run exactly as it would have if @code{GDB} were not present. This
21992 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
21993 entirely non-intrusive until a breakpoint is encountered.  If no
21994 breakpoint is ever hit, the program will run exactly as it would if no
21995 debugger were present. When a breakpoint is hit, @code{GDB} accesses
21996 the debugging information and can respond to user commands to inspect
21997 variables, and more generally to report on the state of execution.
21998
21999 @c **************
22000 @node Running GDB
22001 @section Running GDB
22002
22003 @noindent
22004 This section describes how to initiate the debugger.
22005 @c The above sentence is really just filler, but it was otherwise
22006 @c clumsy to get the first paragraph nonindented given the conditional
22007 @c nature of the description
22008
22009 @ifclear vms
22010 The debugger can be launched from a @code{GPS} menu or
22011 directly from the command line. The description below covers the latter use.
22012 All the commands shown can be used in the @code{GPS} debug console window,
22013 but there are usually more GUI-based ways to achieve the same effect.
22014 @end ifclear
22015
22016 The command to run @code{GDB} is
22017
22018 @smallexample
22019 $ ^gdb program^GDB PROGRAM^
22020 @end smallexample
22021
22022 @noindent
22023 where @code{^program^PROGRAM^} is the name of the executable file. This
22024 activates the debugger and results in a prompt for debugger commands.
22025 The simplest command is simply @code{run}, which causes the program to run
22026 exactly as if the debugger were not present. The following section
22027 describes some of the additional commands that can be given to @code{GDB}.
22028
22029 @c *******************************
22030 @node Introduction to GDB Commands
22031 @section Introduction to GDB Commands
22032
22033 @noindent
22034 @code{GDB} contains a large repertoire of commands. The manual
22035 @cite{Debugging with GDB}
22036 @ifset vms
22037 (located in the GNU:[DOCS] directory)
22038 @end ifset
22039 includes extensive documentation on the use
22040 of these commands, together with examples of their use. Furthermore,
22041 the command @command{help} invoked from within GDB activates a simple help
22042 facility which summarizes the available commands and their options.
22043 In this section we summarize a few of the most commonly
22044 used commands to give an idea of what @code{GDB} is about. You should create
22045 a simple program with debugging information and experiment with the use of
22046 these @code{GDB} commands on the program as you read through the
22047 following section.
22048
22049 @table @code
22050 @item set args @var{arguments}
22051 The @var{arguments} list above is a list of arguments to be passed to
22052 the program on a subsequent run command, just as though the arguments
22053 had been entered on a normal invocation of the program. The @code{set args}
22054 command is not needed if the program does not require arguments.
22055
22056 @item run
22057 The @code{run} command causes execution of the program to start from
22058 the beginning. If the program is already running, that is to say if
22059 you are currently positioned at a breakpoint, then a prompt will ask
22060 for confirmation that you want to abandon the current execution and
22061 restart.
22062
22063 @item breakpoint @var{location}
22064 The breakpoint command sets a breakpoint, that is to say a point at which
22065 execution will halt and @code{GDB} will await further
22066 commands. @var{location} is
22067 either a line number within a file, given in the format @code{file:linenumber},
22068 or it is the name of a subprogram. If you request that a breakpoint be set on
22069 a subprogram that is overloaded, a prompt will ask you to specify on which of
22070 those subprograms you want to breakpoint. You can also
22071 specify that all of them should be breakpointed. If the program is run
22072 and execution encounters the breakpoint, then the program
22073 stops and @code{GDB} signals that the breakpoint was encountered by
22074 printing the line of code before which the program is halted.
22075
22076 @item breakpoint exception @var{name}
22077 A special form of the breakpoint command which breakpoints whenever
22078 exception @var{name} is raised.
22079 If @var{name} is omitted,
22080 then a breakpoint will occur when any exception is raised.
22081
22082 @item print @var{expression}
22083 This will print the value of the given expression. Most simple
22084 Ada expression formats are properly handled by @code{GDB}, so the expression
22085 can contain function calls, variables, operators, and attribute references.
22086
22087 @item continue
22088 Continues execution following a breakpoint, until the next breakpoint or the
22089 termination of the program.
22090
22091 @item step
22092 Executes a single line after a breakpoint. If the next statement
22093 is a subprogram call, execution continues into (the first statement of)
22094 the called subprogram.
22095
22096 @item next
22097 Executes a single line. If this line is a subprogram call, executes and
22098 returns from the call.
22099
22100 @item list
22101 Lists a few lines around the current source location. In practice, it
22102 is usually more convenient to have a separate edit window open with the
22103 relevant source file displayed. Successive applications of this command
22104 print subsequent lines. The command can be given an argument which is a
22105 line number, in which case it displays a few lines around the specified one.
22106
22107 @item backtrace
22108 Displays a backtrace of the call chain. This command is typically
22109 used after a breakpoint has occurred, to examine the sequence of calls that
22110 leads to the current breakpoint. The display includes one line for each
22111 activation record (frame) corresponding to an active subprogram.
22112
22113 @item up
22114 At a breakpoint, @code{GDB} can display the values of variables local
22115 to the current frame. The command @code{up} can be used to
22116 examine the contents of other active frames, by moving the focus up
22117 the stack, that is to say from callee to caller, one frame at a time.
22118
22119 @item down
22120 Moves the focus of @code{GDB} down from the frame currently being
22121 examined to the frame of its callee (the reverse of the previous command),
22122
22123 @item frame @var{n}
22124 Inspect the frame with the given number. The value 0 denotes the frame
22125 of the current breakpoint, that is to say the top of the call stack.
22126
22127 @end table
22128
22129 @noindent
22130 The above list is a very short introduction to the commands that
22131 @code{GDB} provides. Important additional capabilities, including conditional
22132 breakpoints, the ability to execute command sequences on a breakpoint,
22133 the ability to debug at the machine instruction level and many other
22134 features are described in detail in @cite{Debugging with GDB}.
22135 Note that most commands can be abbreviated
22136 (for example, c for continue, bt for backtrace).
22137
22138 @node Using Ada Expressions
22139 @section Using Ada Expressions
22140 @cindex Ada expressions
22141
22142 @noindent
22143 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
22144 extensions. The philosophy behind the design of this subset is
22145
22146 @itemize @bullet
22147 @item
22148 That @code{GDB} should provide basic literals and access to operations for
22149 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
22150 leaving more sophisticated computations to subprograms written into the
22151 program (which therefore may be called from @code{GDB}).
22152
22153 @item
22154 That type safety and strict adherence to Ada language restrictions
22155 are not particularly important to the @code{GDB} user.
22156
22157 @item
22158 That brevity is important to the @code{GDB} user.
22159 @end itemize
22160
22161 @noindent
22162 Thus, for brevity, the debugger acts as if there were
22163 implicit @code{with} and @code{use} clauses in effect for all user-written
22164 packages, thus making it unnecessary to fully qualify most names with
22165 their packages, regardless of context. Where this causes ambiguity,
22166 @code{GDB} asks the user's intent.
22167
22168 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
22169
22170 @node Calling User-Defined Subprograms
22171 @section Calling User-Defined Subprograms
22172
22173 @noindent
22174 An important capability of @code{GDB} is the ability to call user-defined
22175 subprograms while debugging. This is achieved simply by entering
22176 a subprogram call statement in the form:
22177
22178 @smallexample
22179 call subprogram-name (parameters)
22180 @end smallexample
22181
22182 @noindent
22183 The keyword @code{call} can be omitted in the normal case where the
22184 @code{subprogram-name} does not coincide with any of the predefined
22185 @code{GDB} commands.
22186
22187 The effect is to invoke the given subprogram, passing it the
22188 list of parameters that is supplied. The parameters can be expressions and
22189 can include variables from the program being debugged. The
22190 subprogram must be defined
22191 at the library level within your program, and @code{GDB} will call the
22192 subprogram within the environment of your program execution (which
22193 means that the subprogram is free to access or even modify variables
22194 within your program).
22195
22196 The most important use of this facility is in allowing the inclusion of
22197 debugging routines that are tailored to particular data structures
22198 in your program. Such debugging routines can be written to provide a suitably
22199 high-level description of an abstract type, rather than a low-level dump
22200 of its physical layout. After all, the standard
22201 @code{GDB print} command only knows the physical layout of your
22202 types, not their abstract meaning. Debugging routines can provide information
22203 at the desired semantic level and are thus enormously useful.
22204
22205 For example, when debugging GNAT itself, it is crucial to have access to
22206 the contents of the tree nodes used to represent the program internally.
22207 But tree nodes are represented simply by an integer value (which in turn
22208 is an index into a table of nodes).
22209 Using the @code{print} command on a tree node would simply print this integer
22210 value, which is not very useful. But the PN routine (defined in file
22211 treepr.adb in the GNAT sources) takes a tree node as input, and displays
22212 a useful high level representation of the tree node, which includes the
22213 syntactic category of the node, its position in the source, the integers
22214 that denote descendant nodes and parent node, as well as varied
22215 semantic information. To study this example in more detail, you might want to
22216 look at the body of the PN procedure in the stated file.
22217
22218 @node Using the Next Command in a Function
22219 @section Using the Next Command in a Function
22220
22221 @noindent
22222 When you use the @code{next} command in a function, the current source
22223 location will advance to the next statement as usual. A special case
22224 arises in the case of a @code{return} statement.
22225
22226 Part of the code for a return statement is the ``epilog'' of the function.
22227 This is the code that returns to the caller. There is only one copy of
22228 this epilog code, and it is typically associated with the last return
22229 statement in the function if there is more than one return. In some
22230 implementations, this epilog is associated with the first statement
22231 of the function.
22232
22233 The result is that if you use the @code{next} command from a return
22234 statement that is not the last return statement of the function you
22235 may see a strange apparent jump to the last return statement or to
22236 the start of the function. You should simply ignore this odd jump.
22237 The value returned is always that from the first return statement
22238 that was stepped through.
22239
22240 @node Ada Exceptions
22241 @section Breaking on Ada Exceptions
22242 @cindex Exceptions
22243
22244 @noindent
22245 You can set breakpoints that trip when your program raises
22246 selected exceptions.
22247
22248 @table @code
22249 @item break exception
22250 Set a breakpoint that trips whenever (any task in the) program raises
22251 any exception.
22252
22253 @item break exception @var{name}
22254 Set a breakpoint that trips whenever (any task in the) program raises
22255 the exception @var{name}.
22256
22257 @item break exception unhandled
22258 Set a breakpoint that trips whenever (any task in the) program raises an
22259 exception for which there is no handler.
22260
22261 @item info exceptions
22262 @itemx info exceptions @var{regexp}
22263 The @code{info exceptions} command permits the user to examine all defined
22264 exceptions within Ada programs. With a regular expression, @var{regexp}, as
22265 argument, prints out only those exceptions whose name matches @var{regexp}.
22266 @end table
22267
22268 @node Ada Tasks
22269 @section Ada Tasks
22270 @cindex Tasks
22271
22272 @noindent
22273 @code{GDB} allows the following task-related commands:
22274
22275 @table @code
22276 @item info tasks
22277 This command shows a list of current Ada tasks, as in the following example:
22278
22279 @smallexample
22280 @iftex
22281 @leftskip=0cm
22282 @end iftex
22283 (gdb) info tasks
22284   ID       TID P-ID   Thread Pri State                 Name
22285    1   8088000   0   807e000  15 Child Activation Wait main_task
22286    2   80a4000   1   80ae000  15 Accept/Select Wait    b
22287    3   809a800   1   80a4800  15 Child Activation Wait a
22288 *  4   80ae800   3   80b8000  15 Running               c
22289 @end smallexample
22290
22291 @noindent
22292 In this listing, the asterisk before the first task indicates it to be the
22293 currently running task. The first column lists the task ID that is used
22294 to refer to tasks in the following commands.
22295
22296 @item break @var{linespec} task @var{taskid}
22297 @itemx break @var{linespec} task @var{taskid} if @dots{}
22298 @cindex Breakpoints and tasks
22299 These commands are like the @code{break @dots{} thread @dots{}}.
22300 @var{linespec} specifies source lines.
22301
22302 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
22303 to specify that you only want @code{GDB} to stop the program when a
22304 particular Ada task reaches this breakpoint. @var{taskid} is one of the
22305 numeric task identifiers assigned by @code{GDB}, shown in the first
22306 column of the @samp{info tasks} display.
22307
22308 If you do not specify @samp{task @var{taskid}} when you set a
22309 breakpoint, the breakpoint applies to @emph{all} tasks of your
22310 program.
22311
22312 You can use the @code{task} qualifier on conditional breakpoints as
22313 well; in this case, place @samp{task @var{taskid}} before the
22314 breakpoint condition (before the @code{if}).
22315
22316 @item task @var{taskno}
22317 @cindex Task switching
22318
22319 This command allows to switch to the task referred by @var{taskno}. In
22320 particular, This allows to browse the backtrace of the specified
22321 task. It is advised to switch back to the original task before
22322 continuing execution otherwise the scheduling of the program may be
22323 perturbed.
22324 @end table
22325
22326 @noindent
22327 For more detailed information on the tasking support,
22328 see @cite{Debugging with GDB}.
22329
22330 @node Debugging Generic Units
22331 @section Debugging Generic Units
22332 @cindex Debugging Generic Units
22333 @cindex Generics
22334
22335 @noindent
22336 GNAT always uses code expansion for generic instantiation. This means that
22337 each time an instantiation occurs, a complete copy of the original code is
22338 made, with appropriate substitutions of formals by actuals.
22339
22340 It is not possible to refer to the original generic entities in
22341 @code{GDB}, but it is always possible to debug a particular instance of
22342 a generic, by using the appropriate expanded names. For example, if we have
22343
22344 @smallexample @c ada
22345 @group
22346 @cartouche
22347 procedure g is
22348
22349    generic package k is
22350       procedure kp (v1 : in out integer);
22351    end k;
22352
22353    package body k is
22354       procedure kp (v1 : in out integer) is
22355       begin
22356          v1 := v1 + 1;
22357       end kp;
22358    end k;
22359
22360    package k1 is new k;
22361    package k2 is new k;
22362
22363    var : integer := 1;
22364
22365 begin
22366    k1.kp (var);
22367    k2.kp (var);
22368    k1.kp (var);
22369    k2.kp (var);
22370 end;
22371 @end cartouche
22372 @end group
22373 @end smallexample
22374
22375 @noindent
22376 Then to break on a call to procedure kp in the k2 instance, simply
22377 use the command:
22378
22379 @smallexample
22380 (gdb) break g.k2.kp
22381 @end smallexample
22382
22383 @noindent
22384 When the breakpoint occurs, you can step through the code of the
22385 instance in the normal manner and examine the values of local variables, as for
22386 other units.
22387
22388 @node GNAT Abnormal Termination or Failure to Terminate
22389 @section GNAT Abnormal Termination or Failure to Terminate
22390 @cindex GNAT Abnormal Termination or Failure to Terminate
22391
22392 @noindent
22393 When presented with programs that contain serious errors in syntax
22394 or semantics,
22395 GNAT may on rare occasions  experience problems in operation, such
22396 as aborting with a
22397 segmentation fault or illegal memory access, raising an internal
22398 exception, terminating abnormally, or failing to terminate at all.
22399 In such cases, you can activate
22400 various features of GNAT that can help you pinpoint the construct in your
22401 program that is the likely source of the problem.
22402
22403 The following strategies are presented in increasing order of
22404 difficulty, corresponding to your experience in using GNAT and your
22405 familiarity with compiler internals.
22406
22407 @enumerate
22408 @item
22409 Run @command{gcc} with the @option{-gnatf}. This first
22410 switch causes all errors on a given line to be reported. In its absence,
22411 only the first error on a line is displayed.
22412
22413 The @option{-gnatdO} switch causes errors to be displayed as soon as they
22414 are encountered, rather than after compilation is terminated. If GNAT
22415 terminates prematurely or goes into an infinite loop, the last error
22416 message displayed may help to pinpoint the culprit.
22417
22418 @item
22419 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
22420 mode, @command{gcc} produces ongoing information about the progress of the
22421 compilation and provides the name of each procedure as code is
22422 generated. This switch allows you to find which Ada procedure was being
22423 compiled when it encountered a code generation problem.
22424
22425 @item
22426 @cindex @option{-gnatdc} switch
22427 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
22428 switch that does for the front-end what @option{^-v^VERBOSE^} does
22429 for the back end. The system prints the name of each unit,
22430 either a compilation unit or nested unit, as it is being analyzed.
22431 @item
22432 Finally, you can start
22433 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
22434 front-end of GNAT, and can be run independently (normally it is just
22435 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
22436 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
22437 @code{where} command is the first line of attack; the variable
22438 @code{lineno} (seen by @code{print lineno}), used by the second phase of
22439 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
22440 which the execution stopped, and @code{input_file name} indicates the name of
22441 the source file.
22442 @end enumerate
22443
22444 @node Naming Conventions for GNAT Source Files
22445 @section Naming Conventions for GNAT Source Files
22446
22447 @noindent
22448 In order to examine the workings of the GNAT system, the following
22449 brief description of its organization may be helpful:
22450
22451 @itemize @bullet
22452 @item
22453 Files with prefix @file{^sc^SC^} contain the lexical scanner.
22454
22455 @item
22456 All files prefixed with @file{^par^PAR^} are components of the parser. The
22457 numbers correspond to chapters of the Ada Reference Manual. For example,
22458 parsing of select statements can be found in @file{par-ch9.adb}.
22459
22460 @item
22461 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
22462 numbers correspond to chapters of the Ada standard. For example, all
22463 issues involving context clauses can be found in @file{sem_ch10.adb}. In
22464 addition, some features of the language require sufficient special processing
22465 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
22466 dynamic dispatching, etc.
22467
22468 @item
22469 All files prefixed with @file{^exp^EXP^} perform normalization and
22470 expansion of the intermediate representation (abstract syntax tree, or AST).
22471 these files use the same numbering scheme as the parser and semantics files.
22472 For example, the construction of record initialization procedures is done in
22473 @file{exp_ch3.adb}.
22474
22475 @item
22476 The files prefixed with @file{^bind^BIND^} implement the binder, which
22477 verifies the consistency of the compilation, determines an order of
22478 elaboration, and generates the bind file.
22479
22480 @item
22481 The files @file{atree.ads} and @file{atree.adb} detail the low-level
22482 data structures used by the front-end.
22483
22484 @item
22485 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
22486 the abstract syntax tree as produced by the parser.
22487
22488 @item
22489 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
22490 all entities, computed during semantic analysis.
22491
22492 @item
22493 Library management issues are dealt with in files with prefix
22494 @file{^lib^LIB^}.
22495
22496 @item
22497 @findex Ada
22498 @cindex Annex A
22499 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
22500 defined in Annex A.
22501
22502 @item
22503 @findex Interfaces
22504 @cindex Annex B
22505 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
22506 defined in Annex B.
22507
22508 @item
22509 @findex System
22510 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
22511 both language-defined children and GNAT run-time routines.
22512
22513 @item
22514 @findex GNAT
22515 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
22516 general-purpose packages, fully documented in their specifications. All
22517 the other @file{.c} files are modifications of common @command{gcc} files.
22518 @end itemize
22519
22520 @node Getting Internal Debugging Information
22521 @section Getting Internal Debugging Information
22522
22523 @noindent
22524 Most compilers have internal debugging switches and modes. GNAT
22525 does also, except GNAT internal debugging switches and modes are not
22526 secret. A summary and full description of all the compiler and binder
22527 debug flags are in the file @file{debug.adb}. You must obtain the
22528 sources of the compiler to see the full detailed effects of these flags.
22529
22530 The switches that print the source of the program (reconstructed from
22531 the internal tree) are of general interest for user programs, as are the
22532 options to print
22533 the full internal tree, and the entity table (the symbol table
22534 information). The reconstructed source provides a readable version of the
22535 program after the front-end has completed analysis and  expansion,
22536 and is useful when studying the performance of specific constructs.
22537 For example, constraint checks are indicated, complex aggregates
22538 are replaced with loops and assignments, and tasking primitives
22539 are replaced with run-time calls.
22540
22541 @node Stack Traceback
22542 @section Stack Traceback
22543 @cindex traceback
22544 @cindex stack traceback
22545 @cindex stack unwinding
22546
22547 @noindent
22548 Traceback is a mechanism to display the sequence of subprogram calls that
22549 leads to a specified execution point in a program. Often (but not always)
22550 the execution point is an instruction at which an exception has been raised.
22551 This mechanism is also known as @i{stack unwinding} because it obtains
22552 its information by scanning the run-time stack and recovering the activation
22553 records of all active subprograms. Stack unwinding is one of the most
22554 important tools for program debugging.
22555
22556 The first entry stored in traceback corresponds to the deepest calling level,
22557 that is to say the subprogram currently executing the instruction
22558 from which we want to obtain the traceback.
22559
22560 Note that there is no runtime performance penalty when stack traceback
22561 is enabled, and no exception is raised during program execution.
22562
22563 @menu
22564 * Non-Symbolic Traceback::
22565 * Symbolic Traceback::
22566 @end menu
22567
22568 @node Non-Symbolic Traceback
22569 @subsection Non-Symbolic Traceback
22570 @cindex traceback, non-symbolic
22571
22572 @noindent
22573 Note: this feature is not supported on all platforms. See
22574 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
22575 platforms.
22576
22577 @menu
22578 * Tracebacks From an Unhandled Exception::
22579 * Tracebacks From Exception Occurrences (non-symbolic)::
22580 * Tracebacks From Anywhere in a Program (non-symbolic)::
22581 @end menu
22582
22583 @node Tracebacks From an Unhandled Exception
22584 @subsubsection Tracebacks From an Unhandled Exception
22585
22586 @noindent
22587 A runtime non-symbolic traceback is a list of addresses of call instructions.
22588 To enable this feature you must use the @option{-E}
22589 @code{gnatbind}'s option. With this option a stack traceback is stored as part
22590 of exception information. You can retrieve this information using the
22591 @code{addr2line} tool.
22592
22593 Here is a simple example:
22594
22595 @smallexample @c ada
22596 @cartouche
22597 procedure STB is
22598
22599    procedure P1 is
22600    begin
22601       raise Constraint_Error;
22602    end P1;
22603
22604    procedure P2 is
22605    begin
22606       P1;
22607    end P2;
22608
22609 begin
22610    P2;
22611 end STB;
22612 @end cartouche
22613 @end smallexample
22614
22615 @smallexample
22616 $ gnatmake stb -bargs -E
22617 $ stb
22618
22619 Execution terminated by unhandled exception
22620 Exception name: CONSTRAINT_ERROR
22621 Message: stb.adb:5
22622 Call stack traceback locations:
22623 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
22624 @end smallexample
22625
22626 @noindent
22627 As we see the traceback lists a sequence of addresses for the unhandled
22628 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
22629 guess that this exception come from procedure P1. To translate these
22630 addresses into the source lines where the calls appear, the
22631 @code{addr2line} tool, described below, is invaluable. The use of this tool
22632 requires the program to be compiled with debug information.
22633
22634 @smallexample
22635 $ gnatmake -g stb -bargs -E
22636 $ stb
22637
22638 Execution terminated by unhandled exception
22639 Exception name: CONSTRAINT_ERROR
22640 Message: stb.adb:5
22641 Call stack traceback locations:
22642 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
22643
22644 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
22645    0x4011f1 0x77e892a4
22646
22647 00401373 at d:/stb/stb.adb:5
22648 0040138B at d:/stb/stb.adb:10
22649 0040139C at d:/stb/stb.adb:14
22650 00401335 at d:/stb/b~stb.adb:104
22651 004011C4 at /build/@dots{}/crt1.c:200
22652 004011F1 at /build/@dots{}/crt1.c:222
22653 77E892A4 in ?? at ??:0
22654 @end smallexample
22655
22656 @noindent
22657 The @code{addr2line} tool has several other useful options:
22658
22659 @table @code
22660 @item --functions
22661 to get the function name corresponding to any location
22662
22663 @item --demangle=gnat
22664 to use the gnat decoding mode for the function names. Note that
22665 for binutils version 2.9.x the option is simply @option{--demangle}.
22666 @end table
22667
22668 @smallexample
22669 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
22670    0x40139c 0x401335 0x4011c4 0x4011f1
22671
22672 00401373 in stb.p1 at d:/stb/stb.adb:5
22673 0040138B in stb.p2 at d:/stb/stb.adb:10
22674 0040139C in stb at d:/stb/stb.adb:14
22675 00401335 in main at d:/stb/b~stb.adb:104
22676 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
22677 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
22678 @end smallexample
22679
22680 @noindent
22681 From this traceback we can see that the exception was raised in
22682 @file{stb.adb} at line 5, which was reached from a procedure call in
22683 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
22684 which contains the call to the main program.
22685 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
22686 and the output will vary from platform to platform.
22687
22688 It is also possible to use @code{GDB} with these traceback addresses to debug
22689 the program. For example, we can break at a given code location, as reported
22690 in the stack traceback:
22691
22692 @smallexample
22693 $ gdb -nw stb
22694 @ifclear vms
22695 @noindent
22696 Furthermore, this feature is not implemented inside Windows DLL. Only
22697 the non-symbolic traceback is reported in this case.
22698 @end ifclear
22699
22700 (gdb) break *0x401373
22701 Breakpoint 1 at 0x401373: file stb.adb, line 5.
22702 @end smallexample
22703
22704 @noindent
22705 It is important to note that the stack traceback addresses
22706 do not change when debug information is included. This is particularly useful
22707 because it makes it possible to release software without debug information (to
22708 minimize object size), get a field report that includes a stack traceback
22709 whenever an internal bug occurs, and then be able to retrieve the sequence
22710 of calls with the same program compiled with debug information.
22711
22712 @node Tracebacks From Exception Occurrences (non-symbolic)
22713 @subsubsection Tracebacks From Exception Occurrences
22714
22715 @noindent
22716 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
22717 The stack traceback is attached to the exception information string, and can
22718 be retrieved in an exception handler within the Ada program, by means of the
22719 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
22720
22721 @smallexample @c ada
22722 with Ada.Text_IO;
22723 with Ada.Exceptions;
22724
22725 procedure STB is
22726
22727    use Ada;
22728    use Ada.Exceptions;
22729
22730    procedure P1 is
22731       K : Positive := 1;
22732    begin
22733       K := K - 1;
22734    exception
22735       when E : others =>
22736          Text_IO.Put_Line (Exception_Information (E));
22737    end P1;
22738
22739    procedure P2 is
22740    begin
22741       P1;
22742    end P2;
22743
22744 begin
22745    P2;
22746 end STB;
22747 @end smallexample
22748
22749 @noindent
22750 This program will output:
22751
22752 @smallexample
22753 $ stb
22754
22755 Exception name: CONSTRAINT_ERROR
22756 Message: stb.adb:12
22757 Call stack traceback locations:
22758 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
22759 @end smallexample
22760
22761 @node Tracebacks From Anywhere in a Program (non-symbolic)
22762 @subsubsection Tracebacks From Anywhere in a Program
22763
22764 @noindent
22765 It is also possible to retrieve a stack traceback from anywhere in a
22766 program. For this you need to
22767 use the @code{GNAT.Traceback} API. This package includes a procedure called
22768 @code{Call_Chain} that computes a complete stack traceback, as well as useful
22769 display procedures described below. It is not necessary to use the
22770 @option{-E gnatbind} option in this case, because the stack traceback mechanism
22771 is invoked explicitly.
22772
22773 @noindent
22774 In the following example we compute a traceback at a specific location in
22775 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
22776 convert addresses to strings:
22777
22778 @smallexample @c ada
22779 with Ada.Text_IO;
22780 with GNAT.Traceback;
22781 with GNAT.Debug_Utilities;
22782
22783 procedure STB is
22784
22785    use Ada;
22786    use GNAT;
22787    use GNAT.Traceback;
22788
22789    procedure P1 is
22790       TB  : Tracebacks_Array (1 .. 10);
22791       --  We are asking for a maximum of 10 stack frames.
22792       Len : Natural;
22793       --  Len will receive the actual number of stack frames returned.
22794    begin
22795       Call_Chain (TB, Len);
22796
22797       Text_IO.Put ("In STB.P1 : ");
22798
22799       for K in 1 .. Len loop
22800          Text_IO.Put (Debug_Utilities.Image (TB (K)));
22801          Text_IO.Put (' ');
22802       end loop;
22803
22804       Text_IO.New_Line;
22805    end P1;
22806
22807    procedure P2 is
22808    begin
22809       P1;
22810    end P2;
22811
22812 begin
22813    P2;
22814 end STB;
22815 @end smallexample
22816
22817 @smallexample
22818 $ gnatmake -g stb
22819 $ stb
22820
22821 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
22822 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
22823 @end smallexample
22824
22825 @noindent
22826 You can then get further information by invoking the @code{addr2line}
22827 tool as described earlier (note that the hexadecimal addresses
22828 need to be specified in C format, with a leading ``0x'').
22829
22830 @node Symbolic Traceback
22831 @subsection Symbolic Traceback
22832 @cindex traceback, symbolic
22833
22834 @noindent
22835 A symbolic traceback is a stack traceback in which procedure names are
22836 associated with each code location.
22837
22838 @noindent
22839 Note that this feature is not supported on all platforms. See
22840 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
22841 list of currently supported platforms.
22842
22843 @noindent
22844 Note that the symbolic traceback requires that the program be compiled
22845 with debug information. If it is not compiled with debug information
22846 only the non-symbolic information will be valid.
22847
22848 @menu
22849 * Tracebacks From Exception Occurrences (symbolic)::
22850 * Tracebacks From Anywhere in a Program (symbolic)::
22851 @end menu
22852
22853 @node Tracebacks From Exception Occurrences (symbolic)
22854 @subsubsection Tracebacks From Exception Occurrences
22855
22856 @smallexample @c ada
22857 with Ada.Text_IO;
22858 with GNAT.Traceback.Symbolic;
22859
22860 procedure STB is
22861
22862    procedure P1 is
22863    begin
22864       raise Constraint_Error;
22865    end P1;
22866
22867    procedure P2 is
22868    begin
22869       P1;
22870    end P2;
22871
22872    procedure P3 is
22873    begin
22874       P2;
22875    end P3;
22876
22877 begin
22878    P3;
22879 exception
22880    when E : others =>
22881       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
22882 end STB;
22883 @end smallexample
22884
22885 @smallexample
22886 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
22887 $ stb
22888
22889 0040149F in stb.p1 at stb.adb:8
22890 004014B7 in stb.p2 at stb.adb:13
22891 004014CF in stb.p3 at stb.adb:18
22892 004015DD in ada.stb at stb.adb:22
22893 00401461 in main at b~stb.adb:168
22894 004011C4 in __mingw_CRTStartup at crt1.c:200
22895 004011F1 in mainCRTStartup at crt1.c:222
22896 77E892A4 in ?? at ??:0
22897 @end smallexample
22898
22899 @noindent
22900 In the above example the ``.\'' syntax in the @command{gnatmake} command
22901 is currently required by @command{addr2line} for files that are in
22902 the current working directory.
22903 Moreover, the exact sequence of linker options may vary from platform
22904 to platform.
22905 The above @option{-largs} section is for Windows platforms. By contrast,
22906 under Unix there is no need for the @option{-largs} section.
22907 Differences across platforms are due to details of linker implementation.
22908
22909 @node Tracebacks From Anywhere in a Program (symbolic)
22910 @subsubsection Tracebacks From Anywhere in a Program
22911
22912 @noindent
22913 It is possible to get a symbolic stack traceback
22914 from anywhere in a program, just as for non-symbolic tracebacks.
22915 The first step is to obtain a non-symbolic
22916 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
22917 information. Here is an example:
22918
22919 @smallexample @c ada
22920 with Ada.Text_IO;
22921 with GNAT.Traceback;
22922 with GNAT.Traceback.Symbolic;
22923
22924 procedure STB is
22925
22926    use Ada;
22927    use GNAT.Traceback;
22928    use GNAT.Traceback.Symbolic;
22929
22930    procedure P1 is
22931       TB  : Tracebacks_Array (1 .. 10);
22932       --  We are asking for a maximum of 10 stack frames.
22933       Len : Natural;
22934       --  Len will receive the actual number of stack frames returned.
22935    begin
22936       Call_Chain (TB, Len);
22937       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
22938    end P1;
22939
22940    procedure P2 is
22941    begin
22942       P1;
22943    end P2;
22944
22945 begin
22946    P2;
22947 end STB;
22948 @end smallexample
22949
22950 @c ******************************
22951 @ifset vms
22952 @node Compatibility with HP Ada
22953 @chapter Compatibility with HP Ada
22954 @cindex Compatibility
22955
22956 @noindent
22957 @cindex DEC Ada
22958 @cindex HP Ada
22959 @cindex Compatibility between GNAT and HP Ada
22960 This chapter compares HP Ada (formerly known as ``DEC Ada'')
22961 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
22962 GNAT is highly compatible
22963 with HP Ada, and it should generally be straightforward to port code
22964 from the HP Ada environment to GNAT. However, there are a few language
22965 and implementation differences of which the user must be aware. These
22966 differences are discussed in this chapter. In
22967 addition, the operating environment and command structure for the
22968 compiler are different, and these differences are also discussed.
22969
22970 For further details on these and other compatibility issues,
22971 see Appendix E of the HP publication
22972 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
22973
22974 Except where otherwise indicated, the description of GNAT for OpenVMS
22975 applies to both the Alpha and I64 platforms.
22976
22977 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
22978 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22979
22980 The discussion in this chapter addresses specifically the implementation
22981 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
22982 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
22983 GNAT always follows the Alpha implementation.
22984
22985 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
22986 attributes are recognized, although only a subset of them can sensibly
22987 be implemented.  The description of pragmas in the
22988 @cite{GNAT Reference Manual} indicates whether or not they are applicable
22989 to non-VMS systems.
22990
22991 @menu
22992 * Ada Language Compatibility::
22993 * Differences in the Definition of Package System::
22994 * Language-Related Features::
22995 * The Package STANDARD::
22996 * The Package SYSTEM::
22997 * Tasking and Task-Related Features::
22998 * Pragmas and Pragma-Related Features::
22999 * Library of Predefined Units::
23000 * Bindings::
23001 * Main Program Definition::
23002 * Implementation-Defined Attributes::
23003 * Compiler and Run-Time Interfacing::
23004 * Program Compilation and Library Management::
23005 * Input-Output::
23006 * Implementation Limits::
23007 * Tools and Utilities::
23008 @end menu
23009
23010 @node Ada Language Compatibility
23011 @section Ada Language Compatibility
23012
23013 @noindent
23014 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
23015 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
23016 with Ada 83, and therefore Ada 83 programs will compile
23017 and run under GNAT with
23018 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
23019 provides details on specific incompatibilities.
23020
23021 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
23022 as well as the pragma @code{ADA_83}, to force the compiler to
23023 operate in Ada 83 mode. This mode does not guarantee complete
23024 conformance to Ada 83, but in practice is sufficient to
23025 eliminate most sources of incompatibilities.
23026 In particular, it eliminates the recognition of the
23027 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
23028 in Ada 83 programs is legal, and handles the cases of packages
23029 with optional bodies, and generics that instantiate unconstrained
23030 types without the use of @code{(<>)}.
23031
23032 @node Differences in the Definition of Package System
23033 @section Differences in the Definition of Package @code{System}
23034
23035 @noindent
23036 An Ada compiler is allowed to add
23037 implementation-dependent declarations to package @code{System}.
23038 In normal mode,
23039 GNAT does not take advantage of this permission, and the version of
23040 @code{System} provided by GNAT exactly matches that defined in the Ada
23041 Reference Manual.
23042
23043 However, HP Ada adds an extensive set of declarations to package
23044 @code{System},
23045 as fully documented in the HP Ada manuals. To minimize changes required
23046 for programs that make use of these extensions, GNAT provides the pragma
23047 @code{Extend_System} for extending the definition of package System. By using:
23048 @cindex pragma @code{Extend_System}
23049 @cindex @code{Extend_System} pragma
23050
23051 @smallexample @c ada
23052 @group
23053 @cartouche
23054 pragma Extend_System (Aux_DEC);
23055 @end cartouche
23056 @end group
23057 @end smallexample
23058
23059 @noindent
23060 the set of definitions in @code{System} is extended to include those in
23061 package @code{System.Aux_DEC}.
23062 @cindex @code{System.Aux_DEC} package
23063 @cindex @code{Aux_DEC} package (child of @code{System})
23064 These definitions are incorporated directly into package @code{System},
23065 as though they had been declared there. For a
23066 list of the declarations added, see the specification of this package,
23067 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
23068 @cindex @file{s-auxdec.ads} file
23069 The pragma @code{Extend_System} is a configuration pragma, which means that
23070 it can be placed in the file @file{gnat.adc}, so that it will automatically
23071 apply to all subsequent compilations. See @ref{Configuration Pragmas},
23072 for further details.
23073
23074 An alternative approach that avoids the use of the non-standard
23075 @code{Extend_System} pragma is to add a context clause to the unit that
23076 references these facilities:
23077
23078 @smallexample @c ada
23079 @cartouche
23080 with System.Aux_DEC;
23081 use  System.Aux_DEC;
23082 @end cartouche
23083 @end smallexample
23084
23085 @noindent
23086 The effect is not quite semantically identical to incorporating
23087 the declarations directly into package @code{System},
23088 but most programs will not notice a difference
23089 unless they use prefix notation (e.g.@: @code{System.Integer_8})
23090 to reference the entities directly in package @code{System}.
23091 For units containing such references,
23092 the prefixes must either be removed, or the pragma @code{Extend_System}
23093 must be used.
23094
23095 @node Language-Related Features
23096 @section Language-Related Features
23097
23098 @noindent
23099 The following sections highlight differences in types,
23100 representations of types, operations, alignment, and
23101 related topics.
23102
23103 @menu
23104 * Integer Types and Representations::
23105 * Floating-Point Types and Representations::
23106 * Pragmas Float_Representation and Long_Float::
23107 * Fixed-Point Types and Representations::
23108 * Record and Array Component Alignment::
23109 * Address Clauses::
23110 * Other Representation Clauses::
23111 @end menu
23112
23113 @node Integer Types and Representations
23114 @subsection Integer Types and Representations
23115
23116 @noindent
23117 The set of predefined integer types is identical in HP Ada and GNAT.
23118 Furthermore the representation of these integer types is also identical,
23119 including the capability of size clauses forcing biased representation.
23120
23121 In addition,
23122 HP Ada for OpenVMS Alpha systems has defined the
23123 following additional integer types in package @code{System}:
23124
23125 @itemize @bullet
23126
23127 @item
23128 @code{INTEGER_8}
23129
23130 @item
23131 @code{INTEGER_16}
23132
23133 @item
23134 @code{INTEGER_32}
23135
23136 @item
23137 @code{INTEGER_64}
23138
23139 @item
23140 @code{LARGEST_INTEGER}
23141 @end itemize
23142
23143 @noindent
23144 In GNAT, the first four of these types may be obtained from the
23145 standard Ada package @code{Interfaces}.
23146 Alternatively, by use of the pragma @code{Extend_System}, identical
23147 declarations can be referenced directly in package @code{System}.
23148 On both GNAT and HP Ada, the maximum integer size is 64 bits.
23149
23150 @node Floating-Point Types and Representations
23151 @subsection Floating-Point Types and Representations
23152 @cindex Floating-Point types
23153
23154 @noindent
23155 The set of predefined floating-point types is identical in HP Ada and GNAT.
23156 Furthermore the representation of these floating-point
23157 types is also identical. One important difference is that the default
23158 representation for HP Ada is @code{VAX_Float}, but the default representation
23159 for GNAT is IEEE.
23160
23161 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
23162 pragma @code{Float_Representation} as described in the HP Ada
23163 documentation.
23164 For example, the declarations:
23165
23166 @smallexample @c ada
23167 @cartouche
23168 type F_Float is digits 6;
23169 pragma Float_Representation (VAX_Float, F_Float);
23170 @end cartouche
23171 @end smallexample
23172
23173 @noindent
23174 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
23175 format.
23176 This set of declarations actually appears in @code{System.Aux_DEC},
23177 which contains
23178 the full set of additional floating-point declarations provided in
23179 the HP Ada version of package @code{System}.
23180 This and similar declarations may be accessed in a user program
23181 by using pragma @code{Extend_System}. The use of this
23182 pragma, and the related pragma @code{Long_Float} is described in further
23183 detail in the following section.
23184
23185 @node Pragmas Float_Representation and Long_Float
23186 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
23187
23188 @noindent
23189 HP Ada provides the pragma @code{Float_Representation}, which
23190 acts as a program library switch to allow control over
23191 the internal representation chosen for the predefined
23192 floating-point types declared in the package @code{Standard}.
23193 The format of this pragma is as follows:
23194
23195 @smallexample @c ada
23196 @cartouche
23197 pragma Float_Representation(VAX_Float | IEEE_Float);
23198 @end cartouche
23199 @end smallexample
23200
23201 @noindent
23202 This pragma controls the representation of floating-point
23203 types as follows:
23204
23205 @itemize @bullet
23206 @item
23207 @code{VAX_Float} specifies that floating-point
23208 types are represented by default with the VAX system hardware types
23209 @code{F-floating}, @code{D-floating}, @code{G-floating}.
23210 Note that the @code{H-floating}
23211 type was available only on VAX systems, and is not available
23212 in either HP Ada or GNAT.
23213
23214 @item
23215 @code{IEEE_Float} specifies that floating-point
23216 types are represented by default with the IEEE single and
23217 double floating-point types.
23218 @end itemize
23219
23220 @noindent
23221 GNAT provides an identical implementation of the pragma
23222 @code{Float_Representation}, except that it functions as a
23223 configuration pragma. Note that the
23224 notion of configuration pragma corresponds closely to the
23225 HP Ada notion of a program library switch.
23226
23227 When no pragma is used in GNAT, the default is @code{IEEE_Float},
23228 which is different
23229 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
23230 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
23231 advisable to change the format of numbers passed to standard library
23232 routines, and if necessary explicit type conversions may be needed.
23233
23234 The use of @code{IEEE_Float} is recommended in GNAT since it is more
23235 efficient, and (given that it conforms to an international standard)
23236 potentially more portable.
23237 The situation in which @code{VAX_Float} may be useful is in interfacing
23238 to existing code and data that expect the use of @code{VAX_Float}.
23239 In such a situation use the predefined @code{VAX_Float}
23240 types in package @code{System}, as extended by
23241 @code{Extend_System}. For example, use @code{System.F_Float}
23242 to specify the 32-bit @code{F-Float} format.
23243
23244 @noindent
23245 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
23246 to allow control over the internal representation chosen
23247 for the predefined type @code{Long_Float} and for floating-point
23248 type declarations with digits specified in the range 7 .. 15.
23249 The format of this pragma is as follows:
23250
23251 @smallexample @c ada
23252 @cartouche
23253 pragma Long_Float (D_FLOAT | G_FLOAT);
23254 @end cartouche
23255 @end smallexample
23256
23257 @node Fixed-Point Types and Representations
23258 @subsection Fixed-Point Types and Representations
23259
23260 @noindent
23261 On HP Ada for OpenVMS Alpha systems, rounding is
23262 away from zero for both positive and negative numbers.
23263 Therefore, @code{+0.5} rounds to @code{1},
23264 and @code{-0.5} rounds to @code{-1}.
23265
23266 On GNAT the results of operations
23267 on fixed-point types are in accordance with the Ada
23268 rules. In particular, results of operations on decimal
23269 fixed-point types are truncated.
23270
23271 @node Record and Array Component Alignment
23272 @subsection Record and Array Component Alignment
23273
23274 @noindent
23275 On HP Ada for OpenVMS Alpha, all non-composite components
23276 are aligned on natural boundaries. For example, 1-byte
23277 components are aligned on byte boundaries, 2-byte
23278 components on 2-byte boundaries, 4-byte components on 4-byte
23279 byte boundaries, and so on. The OpenVMS Alpha hardware
23280 runs more efficiently with naturally aligned data.
23281
23282 On GNAT, alignment rules are compatible
23283 with HP Ada for OpenVMS Alpha.
23284
23285 @node Address Clauses
23286 @subsection Address Clauses
23287
23288 @noindent
23289 In HP Ada and GNAT, address clauses are supported for
23290 objects and imported subprograms.
23291 The predefined type @code{System.Address} is a private type
23292 in both compilers on Alpha OpenVMS, with the same representation
23293 (it is simply a machine pointer). Addition, subtraction, and comparison
23294 operations are available in the standard Ada package
23295 @code{System.Storage_Elements}, or in package @code{System}
23296 if it is extended to include @code{System.Aux_DEC} using a
23297 pragma @code{Extend_System} as previously described.
23298
23299 Note that code that @code{with}'s both this extended package @code{System}
23300 and the package @code{System.Storage_Elements} should not @code{use}
23301 both packages, or ambiguities will result. In general it is better
23302 not to mix these two sets of facilities. The Ada package was
23303 designed specifically to provide the kind of features that HP Ada
23304 adds directly to package @code{System}.
23305
23306 The type @code{System.Address} is a 64-bit integer type in GNAT for
23307 I64 OpenVMS.  For more information,
23308 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
23309
23310 GNAT is compatible with HP Ada in its handling of address
23311 clauses, except for some limitations in
23312 the form of address clauses for composite objects with
23313 initialization. Such address clauses are easily replaced
23314 by the use of an explicitly-defined constant as described
23315 in the Ada Reference Manual (13.1(22)). For example, the sequence
23316 of declarations:
23317
23318 @smallexample @c ada
23319 @cartouche
23320 X, Y : Integer := Init_Func;
23321 Q : String (X .. Y) := "abc";
23322 @dots{}
23323 for Q'Address use Compute_Address;
23324 @end cartouche
23325 @end smallexample
23326
23327 @noindent
23328 will be rejected by GNAT, since the address cannot be computed at the time
23329 that @code{Q} is declared. To achieve the intended effect, write instead:
23330
23331 @smallexample @c ada
23332 @group
23333 @cartouche
23334 X, Y : Integer := Init_Func;
23335 Q_Address : constant Address := Compute_Address;
23336 Q : String (X .. Y) := "abc";
23337 @dots{}
23338 for Q'Address use Q_Address;
23339 @end cartouche
23340 @end group
23341 @end smallexample
23342
23343 @noindent
23344 which will be accepted by GNAT (and other Ada compilers), and is also
23345 compatible with Ada 83. A fuller description of the restrictions
23346 on address specifications is found in the @cite{GNAT Reference Manual}.
23347
23348 @node Other Representation Clauses
23349 @subsection Other Representation Clauses
23350
23351 @noindent
23352 GNAT implements in a compatible manner all the representation
23353 clauses supported by HP Ada. In addition, GNAT
23354 implements the representation clause forms that were introduced in Ada 95,
23355 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
23356
23357 @node The Package STANDARD
23358 @section The Package @code{STANDARD}
23359
23360 @noindent
23361 The package @code{STANDARD}, as implemented by HP Ada, is fully
23362 described in the @cite{Ada Reference Manual} and in the
23363 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
23364 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
23365
23366 In addition, HP Ada supports the Latin-1 character set in
23367 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
23368 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
23369 the type @code{WIDE_CHARACTER}.
23370
23371 The floating-point types supported by GNAT are those
23372 supported by HP Ada, but the defaults are different, and are controlled by
23373 pragmas. See @ref{Floating-Point Types and Representations}, for details.
23374
23375 @node The Package SYSTEM
23376 @section The Package @code{SYSTEM}
23377
23378 @noindent
23379 HP Ada provides a specific version of the package
23380 @code{SYSTEM} for each platform on which the language is implemented.
23381 For the complete specification of the package @code{SYSTEM}, see
23382 Appendix F of the @cite{HP Ada Language Reference Manual}.
23383
23384 On HP Ada, the package @code{SYSTEM} includes the following conversion
23385 functions:
23386 @itemize @bullet
23387 @item @code{TO_ADDRESS(INTEGER)}
23388
23389 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
23390
23391 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
23392
23393 @item @code{TO_INTEGER(ADDRESS)}
23394
23395 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
23396
23397 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
23398               functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
23399 @end itemize
23400
23401 @noindent
23402 By default, GNAT supplies a version of @code{SYSTEM} that matches
23403 the definition given in the @cite{Ada Reference Manual}.
23404 This
23405 is a subset of the HP system definitions, which is as
23406 close as possible to the original definitions. The only difference
23407 is that the definition of @code{SYSTEM_NAME} is different:
23408
23409 @smallexample @c ada
23410 @cartouche
23411 type Name is (SYSTEM_NAME_GNAT);
23412 System_Name : constant Name := SYSTEM_NAME_GNAT;
23413 @end cartouche
23414 @end smallexample
23415
23416 @noindent
23417 Also, GNAT adds the Ada declarations for
23418 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
23419
23420 However, the use of the following pragma causes GNAT
23421 to extend the definition of package @code{SYSTEM} so that it
23422 encompasses the full set of HP-specific extensions,
23423 including the functions listed above:
23424
23425 @smallexample @c ada
23426 @cartouche
23427 pragma Extend_System (Aux_DEC);
23428 @end cartouche
23429 @end smallexample
23430
23431 @noindent
23432 The pragma @code{Extend_System} is a configuration pragma that
23433 is most conveniently placed in the @file{gnat.adc} file. See the
23434 @cite{GNAT Reference Manual} for further details.
23435
23436 HP Ada does not allow the recompilation of the package
23437 @code{SYSTEM}. Instead HP Ada provides several pragmas
23438 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
23439 to modify values in the package @code{SYSTEM}.
23440 On OpenVMS Alpha systems, the pragma
23441 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
23442 its single argument.
23443
23444 GNAT does permit the recompilation of package @code{SYSTEM} using
23445 the special switch @option{-gnatg}, and this switch can be used if
23446 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
23447 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
23448 or @code{MEMORY_SIZE} by any other means.
23449
23450 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
23451 enumeration literal @code{SYSTEM_NAME_GNAT}.
23452
23453 The definitions provided by the use of
23454
23455 @smallexample @c ada
23456 pragma Extend_System (AUX_Dec);
23457 @end smallexample
23458
23459 @noindent
23460 are virtually identical to those provided by the HP Ada 83 package
23461 @code{SYSTEM}. One important difference is that the name of the
23462 @code{TO_ADDRESS}
23463 function for type @code{UNSIGNED_LONGWORD} is changed to
23464 @code{TO_ADDRESS_LONG}.
23465 See the @cite{GNAT Reference Manual} for a discussion of why this change was
23466 necessary.
23467
23468 @noindent
23469 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
23470 is in fact
23471 an extension to Ada 83 not strictly compatible with the reference manual.
23472 GNAT, in order to be exactly compatible with the standard,
23473 does not provide this capability. In HP Ada 83, the
23474 point of this definition is to deal with a call like:
23475
23476 @smallexample @c ada
23477 TO_ADDRESS (16#12777#);
23478 @end smallexample
23479
23480 @noindent
23481 Normally, according to Ada 83 semantics, one would expect this to be
23482 ambiguous, since it matches both the @code{INTEGER} and
23483 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
23484 However, in HP Ada 83, there is no ambiguity, since the
23485 definition using @i{universal_integer} takes precedence.
23486
23487 In GNAT, since the version with @i{universal_integer} cannot be supplied,
23488 it is
23489 not possible to be 100% compatible. Since there are many programs using
23490 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
23491 GNAT was
23492 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
23493 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
23494
23495 @smallexample @c ada
23496 function To_Address (X : Integer) return Address;
23497 pragma Pure_Function (To_Address);
23498
23499 function To_Address_Long (X : Unsigned_Longword) return Address;
23500 pragma Pure_Function (To_Address_Long);
23501 @end smallexample
23502
23503 @noindent
23504 This means that programs using @code{TO_ADDRESS} for
23505 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
23506
23507 @node Tasking and Task-Related Features
23508 @section Tasking and Task-Related Features
23509
23510 @noindent
23511 This section compares the treatment of tasking in GNAT
23512 and in HP Ada for OpenVMS Alpha.
23513 The GNAT description applies to both Alpha and I64 OpenVMS.
23514 For detailed information on tasking in
23515 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
23516 relevant run-time reference manual.
23517
23518 @menu
23519 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
23520 * Assigning Task IDs::
23521 * Task IDs and Delays::
23522 * Task-Related Pragmas::
23523 * Scheduling and Task Priority::
23524 * The Task Stack::
23525 * External Interrupts::
23526 @end menu
23527
23528 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
23529 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
23530
23531 @noindent
23532 On OpenVMS Alpha systems, each Ada task (except a passive
23533 task) is implemented as a single stream of execution
23534 that is created and managed by the kernel. On these
23535 systems, HP Ada tasking support is based on DECthreads,
23536 an implementation of the POSIX standard for threads.
23537
23538 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
23539 code that calls DECthreads routines can be used together.
23540 The interaction between Ada tasks and DECthreads routines
23541 can have some benefits. For example when on OpenVMS Alpha,
23542 HP Ada can call C code that is already threaded.
23543
23544 GNAT uses the facilities of DECthreads,
23545 and Ada tasks are mapped to threads.
23546
23547 @node Assigning Task IDs
23548 @subsection Assigning Task IDs
23549
23550 @noindent
23551 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
23552 the environment task that executes the main program. On
23553 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
23554 that have been created but are not yet activated.
23555
23556 On OpenVMS Alpha systems, task IDs are assigned at
23557 activation. On GNAT systems, task IDs are also assigned at
23558 task creation but do not have the same form or values as
23559 task ID values in HP Ada. There is no null task, and the
23560 environment task does not have a specific task ID value.
23561
23562 @node Task IDs and Delays
23563 @subsection Task IDs and Delays
23564
23565 @noindent
23566 On OpenVMS Alpha systems, tasking delays are implemented
23567 using Timer System Services. The Task ID is used for the
23568 identification of the timer request (the @code{REQIDT} parameter).
23569 If Timers are used in the application take care not to use
23570 @code{0} for the identification, because cancelling such a timer
23571 will cancel all timers and may lead to unpredictable results.
23572
23573 @node Task-Related Pragmas
23574 @subsection Task-Related Pragmas
23575
23576 @noindent
23577 Ada supplies the pragma @code{TASK_STORAGE}, which allows
23578 specification of the size of the guard area for a task
23579 stack. (The guard area forms an area of memory that has no
23580 read or write access and thus helps in the detection of
23581 stack overflow.) On OpenVMS Alpha systems, if the pragma
23582 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
23583 area is created. In the absence of a pragma @code{TASK_STORAGE},
23584 a default guard area is created.
23585
23586 GNAT supplies the following task-related pragmas:
23587
23588 @itemize @bullet
23589 @item  @code{TASK_INFO}
23590
23591               This pragma appears within a task definition and
23592               applies to the task in which it appears. The argument
23593               must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
23594
23595 @item  @code{TASK_STORAGE}
23596
23597               GNAT implements pragma @code{TASK_STORAGE} in the same way as
23598               HP Ada.
23599               Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
23600               @code{SUPPRESS}, and @code{VOLATILE}.
23601 @end itemize
23602 @node Scheduling and Task Priority
23603 @subsection Scheduling and Task Priority
23604
23605 @noindent
23606 HP Ada implements the Ada language requirement that
23607 when two tasks are eligible for execution and they have
23608 different priorities, the lower priority task does not
23609 execute while the higher priority task is waiting. The HP
23610 Ada Run-Time Library keeps a task running until either the
23611 task is suspended or a higher priority task becomes ready.
23612
23613 On OpenVMS Alpha systems, the default strategy is round-
23614 robin with preemption. Tasks of equal priority take turns
23615 at the processor. A task is run for a certain period of
23616 time and then placed at the tail of the ready queue for
23617 its priority level.
23618
23619 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
23620 which can be used to enable or disable round-robin
23621 scheduling of tasks with the same priority.
23622 See the relevant HP Ada run-time reference manual for
23623 information on using the pragmas to control HP Ada task
23624 scheduling.
23625
23626 GNAT follows the scheduling rules of Annex D (Real-Time
23627 Annex) of the @cite{Ada Reference Manual}. In general, this
23628 scheduling strategy is fully compatible with HP Ada
23629 although it provides some additional constraints (as
23630 fully documented in Annex D).
23631 GNAT implements time slicing control in a manner compatible with
23632 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
23633 are identical to the HP Ada 83 pragma of the same name.
23634 Note that it is not possible to mix GNAT tasking and
23635 HP Ada 83 tasking in the same program, since the two run-time
23636 libraries are not compatible.
23637
23638 @node The Task Stack
23639 @subsection The Task Stack
23640
23641 @noindent
23642 In HP Ada, a task stack is allocated each time a
23643 non-passive task is activated. As soon as the task is
23644 terminated, the storage for the task stack is deallocated.
23645 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
23646 a default stack size is used. Also, regardless of the size
23647 specified, some additional space is allocated for task
23648 management purposes. On OpenVMS Alpha systems, at least
23649 one page is allocated.
23650
23651 GNAT handles task stacks in a similar manner. In accordance with
23652 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
23653 an alternative method for controlling the task stack size.
23654 The specification of the attribute @code{T'STORAGE_SIZE} is also
23655 supported in a manner compatible with HP Ada.
23656
23657 @node External Interrupts
23658 @subsection External Interrupts
23659
23660 @noindent
23661 On HP Ada, external interrupts can be associated with task entries.
23662 GNAT is compatible with HP Ada in its handling of external interrupts.
23663
23664 @node Pragmas and Pragma-Related Features
23665 @section Pragmas and Pragma-Related Features
23666
23667 @noindent
23668 Both HP Ada and GNAT supply all language-defined pragmas
23669 as specified by the Ada 83 standard. GNAT also supplies all
23670 language-defined pragmas introduced by Ada 95 and Ada 2005.
23671 In addition, GNAT implements the implementation-defined pragmas
23672 from HP Ada 83.
23673
23674 @itemize @bullet
23675 @item  @code{AST_ENTRY}
23676
23677 @item  @code{COMMON_OBJECT}
23678
23679 @item  @code{COMPONENT_ALIGNMENT}
23680
23681 @item  @code{EXPORT_EXCEPTION}
23682
23683 @item  @code{EXPORT_FUNCTION}
23684
23685 @item  @code{EXPORT_OBJECT}
23686
23687 @item  @code{EXPORT_PROCEDURE}
23688
23689 @item  @code{EXPORT_VALUED_PROCEDURE}
23690
23691 @item  @code{FLOAT_REPRESENTATION}
23692
23693 @item  @code{IDENT}
23694
23695 @item  @code{IMPORT_EXCEPTION}
23696
23697 @item  @code{IMPORT_FUNCTION}
23698
23699 @item  @code{IMPORT_OBJECT}
23700
23701 @item  @code{IMPORT_PROCEDURE}
23702
23703 @item  @code{IMPORT_VALUED_PROCEDURE}
23704
23705 @item  @code{INLINE_GENERIC}
23706
23707 @item  @code{INTERFACE_NAME}
23708
23709 @item  @code{LONG_FLOAT}
23710
23711 @item  @code{MAIN_STORAGE}
23712
23713 @item  @code{PASSIVE}
23714
23715 @item  @code{PSECT_OBJECT}
23716
23717 @item  @code{SHARE_GENERIC}
23718
23719 @item  @code{SUPPRESS_ALL}
23720
23721 @item  @code{TASK_STORAGE}
23722
23723 @item  @code{TIME_SLICE}
23724
23725 @item  @code{TITLE}
23726 @end itemize
23727
23728 @noindent
23729 These pragmas are all fully implemented, with the exception of @code{TITLE},
23730 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
23731 recognized, but which have no
23732 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
23733 use of Ada protected objects. In GNAT, all generics are inlined.
23734
23735 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
23736 a separate subprogram specification which must appear before the
23737 subprogram body.
23738
23739 GNAT also supplies a number of implementation-defined pragmas as follows:
23740 @itemize @bullet
23741 @item  @code{ABORT_DEFER}
23742
23743 @item  @code{ADA_83}
23744
23745 @item  @code{ADA_95}
23746
23747 @item  @code{ADA_05}
23748
23749 @item  @code{ANNOTATE}
23750
23751 @item  @code{ASSERT}
23752
23753 @item  @code{C_PASS_BY_COPY}
23754
23755 @item  @code{CPP_CLASS}
23756
23757 @item  @code{CPP_CONSTRUCTOR}
23758
23759 @item  @code{CPP_DESTRUCTOR}
23760
23761 @item  @code{DEBUG}
23762
23763 @item  @code{EXTEND_SYSTEM}
23764
23765 @item  @code{LINKER_ALIAS}
23766
23767 @item  @code{LINKER_SECTION}
23768
23769 @item  @code{MACHINE_ATTRIBUTE}
23770
23771 @item  @code{NO_RETURN}
23772
23773 @item  @code{PURE_FUNCTION}
23774
23775 @item  @code{SOURCE_FILE_NAME}
23776
23777 @item  @code{SOURCE_REFERENCE}
23778
23779 @item  @code{TASK_INFO}
23780
23781 @item  @code{UNCHECKED_UNION}
23782
23783 @item  @code{UNIMPLEMENTED_UNIT}
23784
23785 @item  @code{UNIVERSAL_DATA}
23786
23787 @item  @code{UNSUPPRESS}
23788
23789 @item  @code{WARNINGS}
23790
23791 @item  @code{WEAK_EXTERNAL}
23792 @end itemize
23793
23794 @noindent
23795 For full details on these GNAT implementation-defined pragmas, see
23796 the GNAT Reference Manual.
23797
23798 @menu
23799 * Restrictions on the Pragma INLINE::
23800 * Restrictions on the Pragma INTERFACE::
23801 * Restrictions on the Pragma SYSTEM_NAME::
23802 @end menu
23803
23804 @node Restrictions on the Pragma INLINE
23805 @subsection Restrictions on Pragma @code{INLINE}
23806
23807 @noindent
23808 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
23809 @itemize @bullet
23810 @item  Parameters cannot have a task type.
23811
23812 @item  Function results cannot be task types, unconstrained
23813 array types, or unconstrained types with discriminants.
23814
23815 @item  Bodies cannot declare the following:
23816 @itemize @bullet
23817 @item  Subprogram body or stub (imported subprogram is allowed)
23818
23819 @item  Tasks
23820
23821 @item  Generic declarations
23822
23823 @item  Instantiations
23824
23825 @item  Exceptions
23826
23827 @item  Access types (types derived from access types allowed)
23828
23829 @item  Array or record types
23830
23831 @item  Dependent tasks
23832
23833 @item  Direct recursive calls of subprogram or containing
23834 subprogram, directly or via a renaming
23835
23836 @end itemize
23837 @end itemize
23838
23839 @noindent
23840 In GNAT, the only restriction on pragma @code{INLINE} is that the
23841 body must occur before the call if both are in the same
23842 unit, and the size must be appropriately small. There are
23843 no other specific restrictions which cause subprograms to
23844 be incapable of being inlined.
23845
23846 @node  Restrictions on the Pragma INTERFACE
23847 @subsection  Restrictions on Pragma @code{INTERFACE}
23848
23849 @noindent
23850 The following restrictions on pragma @code{INTERFACE}
23851 are enforced by both HP Ada and GNAT:
23852 @itemize @bullet
23853 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
23854 Default is the default on OpenVMS Alpha systems.
23855
23856 @item  Parameter passing: Language specifies default
23857 mechanisms but can be overridden with an @code{EXPORT} pragma.
23858
23859 @itemize @bullet
23860 @item  Ada: Use internal Ada rules.
23861
23862 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
23863 record or task type. Result cannot be a string, an
23864 array, or a record.
23865
23866 @item  Fortran: Parameters cannot have a task type. Result cannot
23867 be a string, an array, or a record.
23868 @end itemize
23869 @end itemize
23870
23871 @noindent
23872 GNAT is entirely upwards compatible with HP Ada, and in addition allows
23873 record parameters for all languages.
23874
23875 @node  Restrictions on the Pragma SYSTEM_NAME
23876 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
23877
23878 @noindent
23879 For HP Ada for OpenVMS Alpha, the enumeration literal
23880 for the type @code{NAME} is @code{OPENVMS_AXP}.
23881 In GNAT, the enumeration
23882 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
23883
23884 @node  Library of Predefined Units
23885 @section  Library of Predefined Units
23886
23887 @noindent
23888 A library of predefined units is provided as part of the
23889 HP Ada and GNAT implementations. HP Ada does not provide
23890 the package @code{MACHINE_CODE} but instead recommends importing
23891 assembler code.
23892
23893 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
23894 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
23895 version.
23896 The HP Ada Predefined Library units are modified to remove post-Ada 83
23897 incompatibilities and to make them interoperable with GNAT
23898 (@pxref{Changes to DECLIB}, for details).
23899 The units are located in the @file{DECLIB} directory.
23900
23901 The GNAT RTL is contained in
23902 the @file{ADALIB} directory, and
23903 the default search path is set up to find @code{DECLIB} units in preference
23904 to @code{ADALIB} units with the same name (@code{TEXT_IO},
23905 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
23906
23907 @menu
23908 * Changes to DECLIB::
23909 @end menu
23910
23911 @node Changes to DECLIB
23912 @subsection Changes to @code{DECLIB}
23913
23914 @noindent
23915 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
23916 compatibility are minor and include the following:
23917
23918 @itemize @bullet
23919 @item  Adjusting the location of pragmas and record representation
23920 clauses to obey Ada 95 (and thus Ada 2005) rules
23921
23922 @item  Adding the proper notation to generic formal parameters
23923 that take unconstrained types in instantiation
23924
23925 @item  Adding pragma @code{ELABORATE_BODY} to package specifications
23926 that have package bodies not otherwise allowed
23927
23928 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
23929 ``@code{PROTECTD}''.
23930 Currently these are found only in the @code{STARLET} package spec.
23931
23932 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
23933 where the address size is constrained to 32 bits.
23934 @end itemize
23935
23936 @noindent
23937 None of the above changes is visible to users.
23938
23939 @node Bindings
23940 @section Bindings
23941
23942 @noindent
23943 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
23944 @itemize @bullet
23945
23946 @item  Command Language Interpreter (CLI interface)
23947
23948 @item  DECtalk Run-Time Library (DTK interface)
23949
23950 @item  Librarian utility routines (LBR interface)
23951
23952 @item  General Purpose Run-Time Library (LIB interface)
23953
23954 @item  Math Run-Time Library (MTH interface)
23955
23956 @item  National Character Set Run-Time Library (NCS interface)
23957
23958 @item  Compiled Code Support Run-Time Library (OTS interface)
23959
23960 @item  Parallel Processing Run-Time Library (PPL interface)
23961
23962 @item  Screen Management Run-Time Library (SMG interface)
23963
23964 @item  Sort Run-Time Library (SOR interface)
23965
23966 @item  String Run-Time Library (STR interface)
23967
23968 @item STARLET System Library
23969 @findex Starlet
23970
23971 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
23972
23973 @item  X Windows Toolkit (XT interface)
23974
23975 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
23976 @end itemize
23977
23978 @noindent
23979 GNAT provides implementations of these HP bindings in the @code{DECLIB}
23980 directory, on both the Alpha and I64 OpenVMS platforms.
23981
23982 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
23983 in the
23984 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
23985 A pragma @code{Linker_Options} has been added to packages @code{Xm},
23986 @code{Xt}, and @code{X_Lib}
23987 causing the default X/Motif sharable image libraries to be linked in. This
23988 is done via options files named @file{xm.opt}, @file{xt.opt}, and
23989 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
23990
23991 It may be necessary to edit these options files to update or correct the
23992 library names if, for example, the newer X/Motif bindings from
23993 @file{ADA$EXAMPLES}
23994 had been (previous to installing GNAT) copied and renamed to supersede the
23995 default @file{ADA$PREDEFINED} versions.
23996
23997 @menu
23998 * Shared Libraries and Options Files::
23999 * Interfaces to C::
24000 @end menu
24001
24002 @node Shared Libraries and Options Files
24003 @subsection Shared Libraries and Options Files
24004
24005 @noindent
24006 When using the HP Ada
24007 predefined X and Motif bindings, the linking with their sharable images is
24008 done automatically by @command{GNAT LINK}.
24009 When using other X and Motif bindings, you need
24010 to add the corresponding sharable images to the command line for
24011 @code{GNAT LINK}. When linking with shared libraries, or with
24012 @file{.OPT} files, you must
24013 also add them to the command line for @command{GNAT LINK}.
24014
24015 A shared library to be used with GNAT is built in the same way as other
24016 libraries under VMS. The VMS Link command can be used in standard fashion.
24017
24018 @node Interfaces to C
24019 @subsection Interfaces to C
24020
24021 @noindent
24022 HP Ada
24023 provides the following Ada types and operations:
24024
24025 @itemize @bullet
24026 @item C types package (@code{C_TYPES})
24027
24028 @item C strings (@code{C_TYPES.NULL_TERMINATED})
24029
24030 @item Other_types (@code{SHORT_INT})
24031 @end itemize
24032
24033 @noindent
24034 Interfacing to C with GNAT, you can use the above approach
24035 described for HP Ada or the facilities of Annex B of
24036 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
24037 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
24038 information, see the section ``Interfacing to C'' in the
24039 @cite{GNAT Reference Manual}.
24040
24041 The @option{-gnatF} qualifier forces default and explicit
24042 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
24043 to be uppercased for compatibility with the default behavior
24044 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
24045
24046 @node Main Program Definition
24047 @section Main Program Definition
24048
24049 @noindent
24050 The following section discusses differences in the
24051 definition of main programs on HP Ada and GNAT.
24052 On HP Ada, main programs are defined to meet the
24053 following conditions:
24054 @itemize @bullet
24055 @item  Procedure with no formal parameters (returns @code{0} upon
24056        normal completion)
24057
24058 @item  Procedure with no formal parameters (returns @code{42} when
24059        an unhandled exception is raised)
24060
24061 @item  Function with no formal parameters whose returned value
24062        is of a discrete type
24063
24064 @item  Procedure with one @code{out} formal of a discrete type for
24065        which a specification of pragma @code{EXPORT_VALUED_PROCEDURE}
24066        is given.
24067
24068 @end itemize
24069
24070 @noindent
24071 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
24072 a main function or main procedure returns a discrete
24073 value whose size is less than 64 bits (32 on VAX systems),
24074 the value is zero- or sign-extended as appropriate.
24075 On GNAT, main programs are defined as follows:
24076 @itemize @bullet
24077 @item  Must be a non-generic, parameterless subprogram that
24078 is either a procedure or function returning an Ada
24079 @code{STANDARD.INTEGER} (the predefined type)
24080
24081 @item  Cannot be a generic subprogram or an instantiation of a
24082 generic subprogram
24083 @end itemize
24084
24085 @node Implementation-Defined Attributes
24086 @section Implementation-Defined Attributes
24087
24088 @noindent
24089 GNAT provides all HP Ada implementation-defined
24090 attributes.
24091
24092 @node Compiler and Run-Time Interfacing
24093 @section Compiler and Run-Time Interfacing
24094
24095 @noindent
24096 HP Ada provides the following qualifiers to pass options to the linker
24097 (ACS LINK):
24098 @itemize @bullet
24099 @item  @option{/WAIT} and @option{/SUBMIT}
24100
24101 @item  @option{/COMMAND}
24102
24103 @item  @option{/[NO]MAP}
24104
24105 @item  @option{/OUTPUT=@i{file-spec}}
24106
24107 @item  @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
24108 @end itemize
24109
24110 @noindent
24111 To pass options to the linker, GNAT provides the following
24112 switches:
24113
24114 @itemize @bullet
24115 @item   @option{/EXECUTABLE=@i{exec-name}}
24116
24117 @item   @option{/VERBOSE}
24118
24119 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
24120 @end itemize
24121
24122 @noindent
24123 For more information on these switches, see
24124 @ref{Switches for gnatlink}.
24125 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
24126 to control optimization. HP Ada also supplies the
24127 following pragmas:
24128 @itemize @bullet
24129 @item  @code{OPTIMIZE}
24130
24131 @item  @code{INLINE}
24132
24133 @item  @code{INLINE_GENERIC}
24134
24135 @item  @code{SUPPRESS_ALL}
24136
24137 @item  @code{PASSIVE}
24138 @end itemize
24139
24140 @noindent
24141 In GNAT, optimization is controlled strictly by command
24142 line parameters, as described in the corresponding section of this guide.
24143 The HP pragmas for control of optimization are
24144 recognized but ignored.
24145
24146 Note that in GNAT, the default is optimization off, whereas in HP Ada
24147 the default is that optimization is turned on.
24148
24149 @node Program Compilation and Library Management
24150 @section Program Compilation and Library Management
24151
24152 @noindent
24153 HP Ada and GNAT provide a comparable set of commands to
24154 build programs. HP Ada also provides a program library,
24155 which is a concept that does not exist on GNAT. Instead,
24156 GNAT provides directories of sources that are compiled as
24157 needed.
24158
24159 The following table summarizes
24160 the HP Ada commands and provides
24161 equivalent GNAT commands. In this table, some GNAT
24162 equivalents reflect the fact that GNAT does not use the
24163 concept of a program library. Instead, it uses a model
24164 in which collections of source and object files are used
24165 in a manner consistent with other languages like C and
24166 Fortran. Therefore, standard system file commands are used
24167 to manipulate these elements. Those GNAT commands are marked with
24168 an asterisk.
24169 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
24170
24171 @need 1500
24172 @multitable @columnfractions .35 .65
24173
24174 @item @emph{HP Ada Command}
24175 @tab @emph{GNAT Equivalent / Description}
24176
24177 @item @command{ADA}
24178 @tab @command{GNAT COMPILE}@*
24179 Invokes the compiler to compile one or more Ada source files.
24180
24181 @item @command{ACS ATTACH}@*
24182 @tab [No equivalent]@*
24183 Switches control of terminal from current process running the program
24184 library manager.
24185
24186 @item @command{ACS CHECK}
24187 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
24188 Forms the execution closure of one
24189 or more compiled units and checks completeness and currency.
24190
24191 @item @command{ACS COMPILE}
24192 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
24193 Forms the execution closure of one or
24194 more specified units, checks completeness and currency,
24195 identifies units that have revised source files, compiles same,
24196 and recompiles units that are or will become obsolete.
24197 Also completes incomplete generic instantiations.
24198
24199 @item @command{ACS COPY FOREIGN}
24200 @tab Copy (*)@*
24201 Copies a foreign object file into the program library as a
24202 library unit body.
24203
24204 @item @command{ACS COPY UNIT}
24205 @tab Copy (*)@*
24206 Copies a compiled unit from one program library to another.
24207
24208 @item @command{ACS CREATE LIBRARY}
24209 @tab Create /directory (*)@*
24210 Creates a program library.
24211
24212 @item @command{ACS CREATE SUBLIBRARY}
24213 @tab Create /directory (*)@*
24214 Creates a program sublibrary.
24215
24216 @item @command{ACS DELETE LIBRARY}
24217 @tab @*
24218 Deletes a program library and its contents.
24219
24220 @item @command{ACS DELETE SUBLIBRARY}
24221 @tab @*
24222 Deletes a program sublibrary and its contents.
24223
24224 @item @command{ACS DELETE UNIT}
24225 @tab Delete file (*)@*
24226 On OpenVMS systems, deletes one or more compiled units from
24227 the current program library.
24228
24229 @item @command{ACS DIRECTORY}
24230 @tab Directory (*)@*
24231 On OpenVMS systems, lists units contained in the current
24232 program library.
24233
24234 @item @command{ACS ENTER FOREIGN}
24235 @tab Copy (*)@*
24236 Allows the import of a foreign body as an Ada library
24237 specification and enters a reference to a pointer.
24238
24239 @item @command{ACS ENTER UNIT}
24240 @tab Copy (*)@*
24241 Enters a reference (pointer) from the current program library to
24242 a unit compiled into another program library.
24243
24244 @item @command{ACS EXIT}
24245 @tab [No equivalent]@*
24246 Exits from the program library manager.
24247
24248 @item @command{ACS EXPORT}
24249 @tab Copy (*)@*
24250 Creates an object file that contains system-specific object code
24251 for one or more units. With GNAT, object files can simply be copied
24252 into the desired directory.
24253
24254 @item @command{ACS EXTRACT SOURCE}
24255 @tab Copy (*)@*
24256 Allows access to the copied source file for each Ada compilation unit
24257
24258 @item @command{ACS HELP}
24259 @tab @command{HELP GNAT}@*
24260 Provides online help.
24261
24262 @item @command{ACS LINK}
24263 @tab @command{GNAT LINK}@*
24264 Links an object file containing Ada units into an executable file.
24265
24266 @item @command{ACS LOAD}
24267 @tab Copy (*)@*
24268 Loads (partially compiles) Ada units into the program library.
24269 Allows loading a program from a collection of files into a library
24270 without knowing the relationship among units.
24271
24272 @item @command{ACS MERGE}
24273 @tab Copy (*)@*
24274 Merges into the current program library, one or more units from
24275 another library where they were modified.
24276
24277 @item @command{ACS RECOMPILE}
24278 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
24279 Recompiles from   external or copied source files any obsolete
24280 unit in the closure. Also, completes any incomplete generic
24281 instantiations.
24282
24283 @item @command{ACS REENTER}
24284 @tab @command{GNAT MAKE}@*
24285 Reenters current references to units compiled after last entered
24286 with the @command{ACS ENTER UNIT} command.
24287
24288 @item @command{ACS SET LIBRARY}
24289 @tab Set default (*)@*
24290 Defines a program library to be the compilation context as well
24291 as the target library for compiler output and commands in general.
24292
24293 @item @command{ACS SET PRAGMA}
24294 @tab Edit @file{gnat.adc} (*)@*
24295 Redefines specified  values of the library characteristics
24296 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
24297 and @code{Float_Representation}.
24298
24299 @item @command{ACS SET SOURCE}
24300 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
24301 Defines the source file search list for the @command{ACS COMPILE} command.
24302
24303 @item @command{ACS SHOW LIBRARY}
24304 @tab Directory (*)@*
24305 Lists information about one or more program libraries.
24306
24307 @item @command{ACS SHOW PROGRAM}
24308 @tab [No equivalent]@*
24309 Lists information about the execution closure of one or
24310 more units in the program library.
24311
24312 @item @command{ACS SHOW SOURCE}
24313 @tab Show logical @code{ADA_INCLUDE_PATH}@*
24314 Shows the source file search used when compiling units.
24315
24316 @item @command{ACS SHOW VERSION}
24317 @tab Compile with @option{VERBOSE} option
24318 Displays the version number of the compiler and program library
24319 manager used.
24320
24321 @item @command{ACS SPAWN}
24322 @tab [No equivalent]@*
24323 Creates a subprocess of the current process (same as @command{DCL SPAWN}
24324 command).
24325
24326 @item @command{ACS VERIFY}
24327 @tab [No equivalent]@*
24328 Performs a series of consistency checks on a program library to
24329 determine whether the library structure and library files are in
24330 valid form.
24331 @end multitable
24332
24333 @noindent
24334
24335 @node Input-Output
24336 @section Input-Output
24337
24338 @noindent
24339 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
24340 Management Services (RMS) to perform operations on
24341 external files.
24342
24343 @noindent
24344 HP Ada and GNAT predefine an identical set of input-
24345 output packages. To make the use of the
24346 generic @code{TEXT_IO} operations more convenient, HP Ada
24347 provides predefined library packages that instantiate the
24348 integer and floating-point operations for the predefined
24349 integer and floating-point types as shown in the following table.
24350
24351 @multitable @columnfractions .45 .55
24352 @item @emph{Package Name} @tab Instantiation
24353
24354 @item @code{INTEGER_TEXT_IO}
24355 @tab @code{INTEGER_IO(INTEGER)}
24356
24357 @item @code{SHORT_INTEGER_TEXT_IO}
24358 @tab @code{INTEGER_IO(SHORT_INTEGER)}
24359
24360 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
24361 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
24362
24363 @item @code{FLOAT_TEXT_IO}
24364 @tab @code{FLOAT_IO(FLOAT)}
24365
24366 @item @code{LONG_FLOAT_TEXT_IO}
24367 @tab @code{FLOAT_IO(LONG_FLOAT)}
24368 @end multitable
24369
24370 @noindent
24371 The HP Ada predefined packages and their operations
24372 are implemented using OpenVMS Alpha files and input-output
24373 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
24374 Familiarity with the following is recommended:
24375 @itemize @bullet
24376 @item  RMS file organizations and access methods
24377
24378 @item  OpenVMS file specifications and directories
24379
24380 @item  OpenVMS File Definition Language (FDL)
24381 @end itemize
24382
24383 @noindent
24384 GNAT provides I/O facilities that are completely
24385 compatible with HP Ada. The distribution includes the
24386 standard HP Ada versions of all I/O packages, operating
24387 in a manner compatible with HP Ada. In particular, the
24388 following packages are by default the HP Ada (Ada 83)
24389 versions of these packages rather than the renamings
24390 suggested in Annex J of the Ada Reference Manual:
24391 @itemize @bullet
24392 @item  @code{TEXT_IO}
24393
24394 @item  @code{SEQUENTIAL_IO}
24395
24396 @item  @code{DIRECT_IO}
24397 @end itemize
24398
24399 @noindent
24400 The use of the standard child package syntax (for
24401 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
24402 packages.
24403 GNAT provides HP-compatible predefined instantiations
24404 of the @code{TEXT_IO} packages, and also
24405 provides the standard predefined instantiations required
24406 by the @cite{Ada Reference Manual}.
24407
24408 For further information on how GNAT interfaces to the file
24409 system or how I/O is implemented in programs written in
24410 mixed languages, see the chapter ``Implementation of the
24411 Standard I/O'' in the @cite{GNAT Reference Manual}.
24412 This chapter covers the following:
24413 @itemize @bullet
24414 @item  Standard I/O packages
24415
24416 @item  @code{FORM} strings
24417
24418 @item  @code{ADA.DIRECT_IO}
24419
24420 @item  @code{ADA.SEQUENTIAL_IO}
24421
24422 @item  @code{ADA.TEXT_IO}
24423
24424 @item  Stream pointer positioning
24425
24426 @item  Reading and writing non-regular files
24427
24428 @item  @code{GET_IMMEDIATE}
24429
24430 @item  Treating @code{TEXT_IO} files as streams
24431
24432 @item  Shared files
24433
24434 @item  Open modes
24435 @end itemize
24436
24437 @node Implementation Limits
24438 @section Implementation Limits
24439
24440 @noindent
24441 The following table lists implementation limits for HP Ada
24442 and GNAT systems.
24443 @multitable @columnfractions .60 .20 .20
24444 @sp 1
24445 @item  @emph{Compilation Parameter}
24446 @tab   @emph{HP Ada}
24447 @tab   @emph{GNAT}
24448 @sp 1
24449
24450 @item  In a subprogram or entry  declaration, maximum number of
24451        formal parameters that are of an unconstrained record type
24452 @tab   32
24453 @tab   No set limit
24454 @sp 1
24455
24456 @item  Maximum identifier length (number of characters)
24457 @tab   255
24458 @tab   32766
24459 @sp 1
24460
24461 @item  Maximum number of characters in a source line
24462 @tab   255
24463 @tab   32766
24464 @sp 1
24465
24466 @item  Maximum collection size   (number of bytes)
24467 @tab   2**31-1
24468 @tab   2**31-1
24469 @sp 1
24470
24471 @item  Maximum number of discriminants for a record type
24472 @tab   245
24473 @tab   No set limit
24474 @sp 1
24475
24476 @item  Maximum number of formal parameters in an entry or
24477        subprogram declaration
24478 @tab   246
24479 @tab    No set limit
24480 @sp 1
24481
24482 @item  Maximum number of dimensions in an array type
24483 @tab   255
24484 @tab   No set limit
24485 @sp 1
24486
24487 @item  Maximum number of library  units and subunits in a compilation.
24488 @tab   4095
24489 @tab   No set limit
24490 @sp 1
24491
24492 @item  Maximum number of library units and subunits in an execution.
24493 @tab   16383
24494 @tab   No set limit
24495 @sp 1
24496
24497 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
24498        or @code{PSECT_OBJECT}
24499 @tab   32757
24500 @tab   No set limit
24501 @sp 1
24502
24503 @item  Maximum number of enumeration literals in an enumeration type
24504        definition
24505 @tab   65535
24506 @tab   No set limit
24507 @sp 1
24508
24509 @item  Maximum number of lines in a source file
24510 @tab   65534
24511 @tab   No set limit
24512 @sp 1
24513
24514 @item  Maximum number of bits in any object
24515 @tab   2**31-1
24516 @tab   2**31-1
24517 @sp 1
24518
24519 @item  Maximum size of the static portion of a stack frame (approximate)
24520 @tab   2**31-1
24521 @tab   2**31-1
24522 @end multitable
24523
24524 @node Tools and Utilities
24525 @section Tools and Utilities
24526
24527 @noindent
24528 The following table lists some of the OpenVMS development tools
24529 available for HP Ada, and the corresponding tools for
24530 use with @value{EDITION} on Alpha and I64 platforms.
24531 Aside from the debugger, all the OpenVMS tools identified are part
24532 of the DECset package.
24533
24534 @iftex
24535 @c Specify table in TeX since Texinfo does a poor job
24536 @tex
24537 \smallskip
24538 \smallskip
24539 \settabs\+Language-Sensitive Editor\quad
24540    &Product with HP Ada\quad
24541    &\cr
24542 \+\it Tool
24543    &\it Product with HP Ada
24544    & \it Product with GNAT Pro\cr
24545 \smallskip
24546 \+Code Management System
24547    &HP CMS
24548    & HP CMS\cr
24549 \smallskip
24550 \+Language-Sensitive Editor
24551    &HP LSE
24552    & emacs or HP LSE (Alpha)\cr
24553 \+
24554    &
24555    & HP LSE (I64)\cr
24556 \smallskip
24557 \+Debugger
24558    &OpenVMS Debug
24559    & gdb (Alpha),\cr
24560 \+
24561    &
24562    & OpenVMS Debug (I64)\cr
24563 \smallskip
24564 \+Source Code Analyzer /
24565    &HP SCA
24566    & GNAT XREF\cr
24567 \+Cross Referencer
24568    &
24569    &\cr
24570 \smallskip
24571 \+Test Manager
24572    &HP Digital Test
24573    & HP DTM\cr
24574 \+
24575    &Manager (DTM)
24576    &\cr
24577 \smallskip
24578 \+Performance and
24579    & HP PCA
24580    & HP PCA\cr
24581 \+Coverage Analyzer
24582    &
24583    &\cr
24584 \smallskip
24585 \+Module Management
24586    & HP MMS
24587    & Not applicable\cr
24588 \+ System
24589    &
24590    &\cr
24591 \smallskip
24592 \smallskip
24593 @end tex
24594 @end iftex
24595
24596 @ifnottex
24597 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
24598 @c the TeX version above for the printed version
24599 @flushleft
24600 @c @multitable @columnfractions .3 .4 .4
24601 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
24602 @item @i{Tool}
24603  @tab @i{Tool with HP Ada}
24604  @tab @i{Tool with @value{EDITION}}
24605 @item Code Management@*System
24606  @tab HP CMS
24607  @tab HP CMS
24608 @item Language-Sensitive@*Editor
24609  @tab HP LSE
24610  @tab emacs or HP LSE (Alpha)
24611 @item
24612  @tab
24613  @tab HP LSE (I64)
24614 @item Debugger
24615  @tab OpenVMS Debug
24616  @tab gdb (Alpha),
24617 @item
24618  @tab
24619  @tab OpenVMS Debug (I64)
24620 @item Source Code Analyzer /@*Cross Referencer
24621  @tab HP SCA
24622  @tab GNAT XREF
24623 @item Test Manager
24624  @tab HP Digital Test@*Manager (DTM)
24625  @tab HP DTM
24626 @item Performance and@*Coverage Analyzer
24627  @tab HP PCA
24628  @tab HP PCA
24629 @item Module Management@*System
24630  @tab HP MMS
24631  @tab Not applicable
24632 @end multitable
24633 @end flushleft
24634 @end ifnottex
24635
24636 @end ifset
24637
24638 @c **************************************
24639 @node Platform-Specific Information for the Run-Time Libraries
24640 @appendix Platform-Specific Information for the Run-Time Libraries
24641 @cindex Tasking and threads libraries
24642 @cindex Threads libraries and tasking
24643 @cindex Run-time libraries (platform-specific information)
24644
24645 @noindent
24646 The GNAT run-time implementation may vary with respect to both the
24647 underlying threads library and the exception handling scheme.
24648 For threads support, one or more of the following are supplied:
24649 @itemize @bullet
24650 @item @b{native threads library}, a binding to the thread package from
24651 the underlying operating system
24652
24653 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
24654 POSIX thread package
24655 @end itemize
24656
24657 @noindent
24658 For exception handling, either or both of two models are supplied:
24659 @itemize @bullet
24660 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
24661 Most programs should experience a substantial speed improvement by
24662 being compiled with a ZCX run-time.
24663 This is especially true for
24664 tasking applications or applications with many exception handlers.}
24665 @cindex Zero-Cost Exceptions
24666 @cindex ZCX (Zero-Cost Exceptions)
24667 which uses binder-generated tables that
24668 are interrogated at run time to locate a handler
24669
24670 @item @b{setjmp / longjmp} (``SJLJ''),
24671 @cindex setjmp/longjmp Exception Model
24672 @cindex SJLJ (setjmp/longjmp Exception Model)
24673 which uses dynamically-set data to establish
24674 the set of handlers
24675 @end itemize
24676
24677 @noindent
24678 This appendix summarizes which combinations of threads and exception support
24679 are supplied on various GNAT platforms.
24680 It then shows how to select a particular library either
24681 permanently or temporarily,
24682 explains the properties of (and tradeoffs among) the various threads
24683 libraries, and provides some additional
24684 information about several specific platforms.
24685
24686 @menu
24687 * Summary of Run-Time Configurations::
24688 * Specifying a Run-Time Library::
24689 * Choosing the Scheduling Policy::
24690 * Solaris-Specific Considerations::
24691 * Linux-Specific Considerations::
24692 * AIX-Specific Considerations::
24693 @end menu
24694
24695 @node Summary of Run-Time Configurations
24696 @section Summary of Run-Time Configurations
24697
24698 @multitable @columnfractions .30 .70
24699 @item @b{alpha-openvms}
24700 @item @code{@ @ }@i{rts-native (default)}
24701 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
24702 @item @code{@ @ @ @ }Exceptions @tab ZCX
24703 @*
24704 @item @b{alpha-tru64}
24705 @item @code{@ @ }@i{rts-native (default)}
24706 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
24707 @item @code{@ @ @ @ }Exceptions @tab ZCX
24708 @*
24709 @item @code{@ @ }@i{rts-sjlj}
24710 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
24711 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24712 @*
24713 @item @b{ia64-hp_linux}
24714 @item @code{@ @ }@i{rts-native (default)}
24715 @item @code{@ @ @ @ }Tasking    @tab pthread library
24716 @item @code{@ @ @ @ }Exceptions @tab ZCX
24717 @*
24718 @item @b{ia64-hpux}
24719 @item @code{@ @ }@i{rts-native (default)}
24720 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
24721 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24722 @*
24723 @item @b{ia64-openvms}
24724 @item @code{@ @ }@i{rts-native (default)}
24725 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
24726 @item @code{@ @ @ @ }Exceptions @tab ZCX
24727 @*
24728 @item @b{ia64-sgi_linux}
24729 @item @code{@ @ }@i{rts-native (default)}
24730 @item @code{@ @ @ @ }Tasking    @tab pthread library
24731 @item @code{@ @ @ @ }Exceptions @tab ZCX
24732 @*
24733 @item @b{mips-irix}
24734 @item @code{@ @ }@i{rts-native (default)}
24735 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
24736 @item @code{@ @ @ @ }Exceptions @tab ZCX
24737 @*
24738 @item @b{pa-hpux}
24739 @item @code{@ @ }@i{rts-native (default)}
24740 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
24741 @item @code{@ @ @ @ }Exceptions @tab ZCX
24742 @*
24743 @item @code{@ @ }@i{rts-sjlj}
24744 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
24745 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24746 @*
24747 @item @b{ppc-aix}
24748 @item @code{@ @ }@i{rts-native (default)}
24749 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
24750 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24751 @*
24752 @item @b{ppc-darwin}
24753 @item @code{@ @ }@i{rts-native (default)}
24754 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
24755 @item @code{@ @ @ @ }Exceptions @tab ZCX
24756 @*
24757 @item @b{sparc-solaris}  @tab
24758 @item @code{@ @ }@i{rts-native (default)}
24759 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
24760 @item @code{@ @ @ @ }Exceptions @tab ZCX
24761 @*
24762 @item @code{@ @ }@i{rts-pthread}
24763 @item @code{@ @ @ @ }Tasking    @tab pthread library
24764 @item @code{@ @ @ @ }Exceptions @tab ZCX
24765 @*
24766 @item @code{@ @ }@i{rts-sjlj}
24767 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
24768 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24769 @*
24770 @item @b{sparc64-solaris}  @tab
24771 @item @code{@ @ }@i{rts-native (default)}
24772 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
24773 @item @code{@ @ @ @ }Exceptions @tab ZCX
24774 @*
24775 @item @b{x86-linux}
24776 @item @code{@ @ }@i{rts-native (default)}
24777 @item @code{@ @ @ @ }Tasking    @tab pthread library
24778 @item @code{@ @ @ @ }Exceptions @tab ZCX
24779 @*
24780 @item @code{@ @ }@i{rts-sjlj}
24781 @item @code{@ @ @ @ }Tasking    @tab pthread library
24782 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24783 @*
24784 @item @b{x86-lynx}
24785 @item @code{@ @ }@i{rts-native (default)}
24786 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
24787 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24788 @*
24789 @item @b{x86-solaris}
24790 @item @code{@ @ }@i{rts-native (default)}
24791 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
24792 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24793 @*
24794 @item @b{x86-windows}
24795 @item @code{@ @ }@i{rts-native (default)}
24796 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
24797 @item @code{@ @ @ @ }Exceptions @tab ZCX
24798 @*
24799 @item @code{@ @ }@i{rts-sjlj (default)}
24800 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
24801 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24802 @*
24803 @item @b{x86_64-linux}
24804 @item @code{@ @ }@i{rts-native (default)}
24805 @item @code{@ @ @ @ }Tasking    @tab pthread library
24806 @item @code{@ @ @ @ }Exceptions @tab ZCX
24807 @*
24808 @item @code{@ @ }@i{rts-sjlj}
24809 @item @code{@ @ @ @ }Tasking    @tab pthread library
24810 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24811 @*
24812 @end multitable
24813
24814 @node Specifying a Run-Time Library
24815 @section Specifying a Run-Time Library
24816
24817 @noindent
24818 The @file{adainclude} subdirectory containing the sources of the GNAT
24819 run-time library, and the @file{adalib} subdirectory containing the
24820 @file{ALI} files and the static and/or shared GNAT library, are located
24821 in the gcc target-dependent area:
24822
24823 @smallexample
24824 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
24825 @end smallexample
24826
24827 @noindent
24828 As indicated above, on some platforms several run-time libraries are supplied.
24829 These libraries are installed in the target dependent area and
24830 contain a complete source and binary subdirectory. The detailed description
24831 below explains the differences between the different libraries in terms of
24832 their thread support.
24833
24834 The default run-time library (when GNAT is installed) is @emph{rts-native}.
24835 This default run time is selected by the means of soft links.
24836 For example on x86-linux:
24837
24838 @smallexample
24839 @group
24840  $(target-dir)
24841      |
24842      +--- adainclude----------+
24843      |                        |
24844      +--- adalib-----------+  |
24845      |                     |  |
24846      +--- rts-native       |  |
24847      |    |                |  |
24848      |    +--- adainclude <---+
24849      |    |                |
24850      |    +--- adalib <----+
24851      |
24852      +--- rts-sjlj
24853           |
24854           +--- adainclude
24855           |
24856           +--- adalib
24857 @end group
24858 @end smallexample
24859
24860 @noindent
24861 If the @i{rts-sjlj} library is to be selected on a permanent basis,
24862 these soft links can be modified with the following commands:
24863
24864 @smallexample
24865 $ cd $target
24866 $ rm -f adainclude adalib
24867 $ ln -s rts-sjlj/adainclude adainclude
24868 $ ln -s rts-sjlj/adalib adalib
24869 @end smallexample
24870
24871 @noindent
24872 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
24873 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
24874 @file{$target/ada_object_path}.
24875
24876 Selecting another run-time library temporarily can be
24877 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
24878 @cindex @option{--RTS} option
24879
24880 @node Choosing the Scheduling Policy
24881 @section Choosing the Scheduling Policy
24882
24883 @noindent
24884 When using a POSIX threads implementation, you have a choice of several
24885 scheduling policies: @code{SCHED_FIFO},
24886 @cindex @code{SCHED_FIFO} scheduling policy
24887 @code{SCHED_RR}
24888 @cindex @code{SCHED_RR} scheduling policy
24889 and @code{SCHED_OTHER}.
24890 @cindex @code{SCHED_OTHER} scheduling policy
24891 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
24892 or @code{SCHED_RR} requires special (e.g., root) privileges.
24893
24894 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
24895 @code{SCHED_FIFO},
24896 @cindex @code{SCHED_FIFO} scheduling policy
24897 you can use one of the following:
24898
24899 @itemize @bullet
24900 @item
24901 @code{pragma Time_Slice (0.0)}
24902 @cindex pragma Time_Slice
24903 @item
24904 the corresponding binder option @option{-T0}
24905 @cindex @option{-T0} option
24906 @item
24907 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24908 @cindex pragma Task_Dispatching_Policy
24909 @end itemize
24910
24911 @noindent
24912 To specify @code{SCHED_RR},
24913 @cindex @code{SCHED_RR} scheduling policy
24914 you should use @code{pragma Time_Slice} with a
24915 value greater than @code{0.0}, or else use the corresponding @option{-T}
24916 binder option.
24917
24918 @node Solaris-Specific Considerations
24919 @section Solaris-Specific Considerations
24920 @cindex Solaris Sparc threads libraries
24921
24922 @noindent
24923 This section addresses some topics related to the various threads libraries
24924 on Sparc Solaris.
24925
24926 @menu
24927 * Solaris Threads Issues::
24928 @end menu
24929
24930 @node Solaris Threads Issues
24931 @subsection Solaris Threads Issues
24932
24933 @noindent
24934 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
24935 library based on POSIX threads --- @emph{rts-pthread}.
24936 @cindex rts-pthread threads library
24937 This run-time library has the advantage of being mostly shared across all
24938 POSIX-compliant thread implementations, and it also provides under
24939 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
24940 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
24941 and @code{PTHREAD_PRIO_PROTECT}
24942 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
24943 semantics that can be selected using the predefined pragma
24944 @code{Locking_Policy}
24945 @cindex pragma Locking_Policy (under rts-pthread)
24946 with respectively
24947 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
24948 @cindex @code{Inheritance_Locking} (under rts-pthread)
24949 @cindex @code{Ceiling_Locking} (under rts-pthread)
24950
24951 As explained above, the native run-time library is based on the Solaris thread
24952 library (@code{libthread}) and is the default library.
24953
24954 When the Solaris threads library is used (this is the default), programs
24955 compiled with GNAT can automatically take advantage of
24956 and can thus execute on multiple processors.
24957 The user can alternatively specify a processor on which the program should run
24958 to emulate a single-processor system. The multiprocessor / uniprocessor choice
24959 is made by
24960 setting the environment variable @env{GNAT_PROCESSOR}
24961 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
24962 to one of the following:
24963
24964 @table @code
24965 @item -2
24966 Use the default configuration (run the program on all
24967          available processors) - this is the same as having
24968          @code{GNAT_PROCESSOR} unset
24969
24970 @item -1
24971 Let the run-time implementation choose one processor and run the program on
24972          that processor
24973
24974 @item 0 .. Last_Proc
24975 Run the program on the specified processor.
24976   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
24977 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
24978 @end table
24979
24980 @node Linux-Specific Considerations
24981 @section Linux-Specific Considerations
24982 @cindex Linux threads libraries
24983
24984 @noindent
24985 On GNU/Linux without NPTL support (usually system with GNU C Library
24986 older than 2.3), the signal model is not POSIX compliant, which means
24987 that to send a signal to the process, you need to send the signal to all
24988 threads, e.g.@: by using @code{killpg()}.
24989
24990 @node AIX-Specific Considerations
24991 @section AIX-Specific Considerations
24992 @cindex AIX resolver library
24993
24994 @noindent
24995 On AIX, the resolver library initializes some internal structure on
24996 the first call to @code{get*by*} functions, which are used to implement
24997 @code{GNAT.Sockets.Get_Host_By_Name} and
24998 @code{GNAT.Sockets.Get_Host_By_Address}.
24999 If such initialization occurs within an Ada task, and the stack size for
25000 the task is the default size, a stack overflow may occur.
25001
25002 To avoid this overflow, the user should either ensure that the first call
25003 to @code{GNAT.Sockets.Get_Host_By_Name} or
25004 @code{GNAT.Sockets.Get_Host_By_Addrss}
25005 occurs in the environment task, or use @code{pragma Storage_Size} to
25006 specify a sufficiently large size for the stack of the task that contains
25007 this call.
25008
25009 @c *******************************
25010 @node Example of Binder Output File
25011 @appendix Example of Binder Output File
25012
25013 @noindent
25014 This Appendix displays the source code for @command{gnatbind}'s output
25015 file generated for a simple ``Hello World'' program.
25016 Comments have been added for clarification purposes.
25017
25018 @smallexample @c adanocomment
25019 @iftex
25020 @leftskip=0cm
25021 @end iftex
25022 --  The package is called Ada_Main unless this name is actually used
25023 --  as a unit name in the partition, in which case some other unique
25024 --  name is used.
25025
25026 with System;
25027 package ada_main is
25028
25029    Elab_Final_Code : Integer;
25030    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
25031
25032    --  The main program saves the parameters (argument count,
25033    --  argument values, environment pointer) in global variables
25034    --  for later access by other units including
25035    --  Ada.Command_Line.
25036
25037    gnat_argc : Integer;
25038    gnat_argv : System.Address;
25039    gnat_envp : System.Address;
25040
25041    --  The actual variables are stored in a library routine. This
25042    --  is useful for some shared library situations, where there
25043    --  are problems if variables are not in the library.
25044
25045    pragma Import (C, gnat_argc);
25046    pragma Import (C, gnat_argv);
25047    pragma Import (C, gnat_envp);
25048
25049    --  The exit status is similarly an external location
25050
25051    gnat_exit_status : Integer;
25052    pragma Import (C, gnat_exit_status);
25053
25054    GNAT_Version : constant String :=
25055                     "GNAT Version: 6.0.0w (20061115)";
25056    pragma Export (C, GNAT_Version, "__gnat_version");
25057
25058    --  This is the generated adafinal routine that performs
25059    --  finalization at the end of execution. In the case where
25060    --  Ada is the main program, this main program makes a call
25061    --  to adafinal at program termination.
25062
25063    procedure adafinal;
25064    pragma Export (C, adafinal, "adafinal");
25065
25066    --  This is the generated adainit routine that performs
25067    --  initialization at the start of execution. In the case
25068    --  where Ada is the main program, this main program makes
25069    --  a call to adainit at program startup.
25070
25071    procedure adainit;
25072    pragma Export (C, adainit, "adainit");
25073
25074    --  This routine is called at the start of execution. It is
25075    --  a dummy routine that is used by the debugger to breakpoint
25076    --  at the start of execution.
25077
25078    procedure Break_Start;
25079    pragma Import (C, Break_Start, "__gnat_break_start");
25080
25081    --  This is the actual generated main program (it would be
25082    --  suppressed if the no main program switch were used). As
25083    --  required by standard system conventions, this program has
25084    --  the external name main.
25085
25086    function main
25087      (argc : Integer;
25088       argv : System.Address;
25089       envp : System.Address)
25090       return Integer;
25091    pragma Export (C, main, "main");
25092
25093    --  The following set of constants give the version
25094    --  identification values for every unit in the bound
25095    --  partition. This identification is computed from all
25096    --  dependent semantic units, and corresponds to the
25097    --  string that would be returned by use of the
25098    --  Body_Version or Version attributes.
25099
25100    type Version_32 is mod 2 ** 32;
25101    u00001 : constant Version_32 := 16#7880BEB3#;
25102    u00002 : constant Version_32 := 16#0D24CBD0#;
25103    u00003 : constant Version_32 := 16#3283DBEB#;
25104    u00004 : constant Version_32 := 16#2359F9ED#;
25105    u00005 : constant Version_32 := 16#664FB847#;
25106    u00006 : constant Version_32 := 16#68E803DF#;
25107    u00007 : constant Version_32 := 16#5572E604#;
25108    u00008 : constant Version_32 := 16#46B173D8#;
25109    u00009 : constant Version_32 := 16#156A40CF#;
25110    u00010 : constant Version_32 := 16#033DABE0#;
25111    u00011 : constant Version_32 := 16#6AB38FEA#;
25112    u00012 : constant Version_32 := 16#22B6217D#;
25113    u00013 : constant Version_32 := 16#68A22947#;
25114    u00014 : constant Version_32 := 16#18CC4A56#;
25115    u00015 : constant Version_32 := 16#08258E1B#;
25116    u00016 : constant Version_32 := 16#367D5222#;
25117    u00017 : constant Version_32 := 16#20C9ECA4#;
25118    u00018 : constant Version_32 := 16#50D32CB6#;
25119    u00019 : constant Version_32 := 16#39A8BB77#;
25120    u00020 : constant Version_32 := 16#5CF8FA2B#;
25121    u00021 : constant Version_32 := 16#2F1EB794#;
25122    u00022 : constant Version_32 := 16#31AB6444#;
25123    u00023 : constant Version_32 := 16#1574B6E9#;
25124    u00024 : constant Version_32 := 16#5109C189#;
25125    u00025 : constant Version_32 := 16#56D770CD#;
25126    u00026 : constant Version_32 := 16#02F9DE3D#;
25127    u00027 : constant Version_32 := 16#08AB6B2C#;
25128    u00028 : constant Version_32 := 16#3FA37670#;
25129    u00029 : constant Version_32 := 16#476457A0#;
25130    u00030 : constant Version_32 := 16#731E1B6E#;
25131    u00031 : constant Version_32 := 16#23C2E789#;
25132    u00032 : constant Version_32 := 16#0F1BD6A1#;
25133    u00033 : constant Version_32 := 16#7C25DE96#;
25134    u00034 : constant Version_32 := 16#39ADFFA2#;
25135    u00035 : constant Version_32 := 16#571DE3E7#;
25136    u00036 : constant Version_32 := 16#5EB646AB#;
25137    u00037 : constant Version_32 := 16#4249379B#;
25138    u00038 : constant Version_32 := 16#0357E00A#;
25139    u00039 : constant Version_32 := 16#3784FB72#;
25140    u00040 : constant Version_32 := 16#2E723019#;
25141    u00041 : constant Version_32 := 16#623358EA#;
25142    u00042 : constant Version_32 := 16#107F9465#;
25143    u00043 : constant Version_32 := 16#6843F68A#;
25144    u00044 : constant Version_32 := 16#63305874#;
25145    u00045 : constant Version_32 := 16#31E56CE1#;
25146    u00046 : constant Version_32 := 16#02917970#;
25147    u00047 : constant Version_32 := 16#6CCBA70E#;
25148    u00048 : constant Version_32 := 16#41CD4204#;
25149    u00049 : constant Version_32 := 16#572E3F58#;
25150    u00050 : constant Version_32 := 16#20729FF5#;
25151    u00051 : constant Version_32 := 16#1D4F93E8#;
25152    u00052 : constant Version_32 := 16#30B2EC3D#;
25153    u00053 : constant Version_32 := 16#34054F96#;
25154    u00054 : constant Version_32 := 16#5A199860#;
25155    u00055 : constant Version_32 := 16#0E7F912B#;
25156    u00056 : constant Version_32 := 16#5760634A#;
25157    u00057 : constant Version_32 := 16#5D851835#;
25158
25159    --  The following Export pragmas export the version numbers
25160    --  with symbolic names ending in B (for body) or S
25161    --  (for spec) so that they can be located in a link. The
25162    --  information provided here is sufficient to track down
25163    --  the exact versions of units used in a given build.
25164
25165    pragma Export (C, u00001, "helloB");
25166    pragma Export (C, u00002, "system__standard_libraryB");
25167    pragma Export (C, u00003, "system__standard_libraryS");
25168    pragma Export (C, u00004, "adaS");
25169    pragma Export (C, u00005, "ada__text_ioB");
25170    pragma Export (C, u00006, "ada__text_ioS");
25171    pragma Export (C, u00007, "ada__exceptionsB");
25172    pragma Export (C, u00008, "ada__exceptionsS");
25173    pragma Export (C, u00009, "gnatS");
25174    pragma Export (C, u00010, "gnat__heap_sort_aB");
25175    pragma Export (C, u00011, "gnat__heap_sort_aS");
25176    pragma Export (C, u00012, "systemS");
25177    pragma Export (C, u00013, "system__exception_tableB");
25178    pragma Export (C, u00014, "system__exception_tableS");
25179    pragma Export (C, u00015, "gnat__htableB");
25180    pragma Export (C, u00016, "gnat__htableS");
25181    pragma Export (C, u00017, "system__exceptionsS");
25182    pragma Export (C, u00018, "system__machine_state_operationsB");
25183    pragma Export (C, u00019, "system__machine_state_operationsS");
25184    pragma Export (C, u00020, "system__machine_codeS");
25185    pragma Export (C, u00021, "system__storage_elementsB");
25186    pragma Export (C, u00022, "system__storage_elementsS");
25187    pragma Export (C, u00023, "system__secondary_stackB");
25188    pragma Export (C, u00024, "system__secondary_stackS");
25189    pragma Export (C, u00025, "system__parametersB");
25190    pragma Export (C, u00026, "system__parametersS");
25191    pragma Export (C, u00027, "system__soft_linksB");
25192    pragma Export (C, u00028, "system__soft_linksS");
25193    pragma Export (C, u00029, "system__stack_checkingB");
25194    pragma Export (C, u00030, "system__stack_checkingS");
25195    pragma Export (C, u00031, "system__tracebackB");
25196    pragma Export (C, u00032, "system__tracebackS");
25197    pragma Export (C, u00033, "ada__streamsS");
25198    pragma Export (C, u00034, "ada__tagsB");
25199    pragma Export (C, u00035, "ada__tagsS");
25200    pragma Export (C, u00036, "system__string_opsB");
25201    pragma Export (C, u00037, "system__string_opsS");
25202    pragma Export (C, u00038, "interfacesS");
25203    pragma Export (C, u00039, "interfaces__c_streamsB");
25204    pragma Export (C, u00040, "interfaces__c_streamsS");
25205    pragma Export (C, u00041, "system__file_ioB");
25206    pragma Export (C, u00042, "system__file_ioS");
25207    pragma Export (C, u00043, "ada__finalizationB");
25208    pragma Export (C, u00044, "ada__finalizationS");
25209    pragma Export (C, u00045, "system__finalization_rootB");
25210    pragma Export (C, u00046, "system__finalization_rootS");
25211    pragma Export (C, u00047, "system__finalization_implementationB");
25212    pragma Export (C, u00048, "system__finalization_implementationS");
25213    pragma Export (C, u00049, "system__string_ops_concat_3B");
25214    pragma Export (C, u00050, "system__string_ops_concat_3S");
25215    pragma Export (C, u00051, "system__stream_attributesB");
25216    pragma Export (C, u00052, "system__stream_attributesS");
25217    pragma Export (C, u00053, "ada__io_exceptionsS");
25218    pragma Export (C, u00054, "system__unsigned_typesS");
25219    pragma Export (C, u00055, "system__file_control_blockS");
25220    pragma Export (C, u00056, "ada__finalization__list_controllerB");
25221    pragma Export (C, u00057, "ada__finalization__list_controllerS");
25222
25223    -- BEGIN ELABORATION ORDER
25224    -- ada (spec)
25225    -- gnat (spec)
25226    -- gnat.heap_sort_a (spec)
25227    -- gnat.heap_sort_a (body)
25228    -- gnat.htable (spec)
25229    -- gnat.htable (body)
25230    -- interfaces (spec)
25231    -- system (spec)
25232    -- system.machine_code (spec)
25233    -- system.parameters (spec)
25234    -- system.parameters (body)
25235    -- interfaces.c_streams (spec)
25236    -- interfaces.c_streams (body)
25237    -- system.standard_library (spec)
25238    -- ada.exceptions (spec)
25239    -- system.exception_table (spec)
25240    -- system.exception_table (body)
25241    -- ada.io_exceptions (spec)
25242    -- system.exceptions (spec)
25243    -- system.storage_elements (spec)
25244    -- system.storage_elements (body)
25245    -- system.machine_state_operations (spec)
25246    -- system.machine_state_operations (body)
25247    -- system.secondary_stack (spec)
25248    -- system.stack_checking (spec)
25249    -- system.soft_links (spec)
25250    -- system.soft_links (body)
25251    -- system.stack_checking (body)
25252    -- system.secondary_stack (body)
25253    -- system.standard_library (body)
25254    -- system.string_ops (spec)
25255    -- system.string_ops (body)
25256    -- ada.tags (spec)
25257    -- ada.tags (body)
25258    -- ada.streams (spec)
25259    -- system.finalization_root (spec)
25260    -- system.finalization_root (body)
25261    -- system.string_ops_concat_3 (spec)
25262    -- system.string_ops_concat_3 (body)
25263    -- system.traceback (spec)
25264    -- system.traceback (body)
25265    -- ada.exceptions (body)
25266    -- system.unsigned_types (spec)
25267    -- system.stream_attributes (spec)
25268    -- system.stream_attributes (body)
25269    -- system.finalization_implementation (spec)
25270    -- system.finalization_implementation (body)
25271    -- ada.finalization (spec)
25272    -- ada.finalization (body)
25273    -- ada.finalization.list_controller (spec)
25274    -- ada.finalization.list_controller (body)
25275    -- system.file_control_block (spec)
25276    -- system.file_io (spec)
25277    -- system.file_io (body)
25278    -- ada.text_io (spec)
25279    -- ada.text_io (body)
25280    -- hello (body)
25281    -- END ELABORATION ORDER
25282
25283 end ada_main;
25284
25285 --  The following source file name pragmas allow the generated file
25286 --  names to be unique for different main programs. They are needed
25287 --  since the package name will always be Ada_Main.
25288
25289 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
25290 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
25291
25292 --  Generated package body for Ada_Main starts here
25293
25294 package body ada_main is
25295
25296    --  The actual finalization is performed by calling the
25297    --  library routine in System.Standard_Library.Adafinal
25298
25299    procedure Do_Finalize;
25300    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
25301
25302    -------------
25303    -- adainit --
25304    -------------
25305
25306 @findex adainit
25307    procedure adainit is
25308
25309       --  These booleans are set to True once the associated unit has
25310       --  been elaborated. It is also used to avoid elaborating the
25311       --  same unit twice.
25312
25313       E040 : Boolean;
25314       pragma Import (Ada, E040, "interfaces__c_streams_E");
25315
25316       E008 : Boolean;
25317       pragma Import (Ada, E008, "ada__exceptions_E");
25318
25319       E014 : Boolean;
25320       pragma Import (Ada, E014, "system__exception_table_E");
25321
25322       E053 : Boolean;
25323       pragma Import (Ada, E053, "ada__io_exceptions_E");
25324
25325       E017 : Boolean;
25326       pragma Import (Ada, E017, "system__exceptions_E");
25327
25328       E024 : Boolean;
25329       pragma Import (Ada, E024, "system__secondary_stack_E");
25330
25331       E030 : Boolean;
25332       pragma Import (Ada, E030, "system__stack_checking_E");
25333
25334       E028 : Boolean;
25335       pragma Import (Ada, E028, "system__soft_links_E");
25336
25337       E035 : Boolean;
25338       pragma Import (Ada, E035, "ada__tags_E");
25339
25340       E033 : Boolean;
25341       pragma Import (Ada, E033, "ada__streams_E");
25342
25343       E046 : Boolean;
25344       pragma Import (Ada, E046, "system__finalization_root_E");
25345
25346       E048 : Boolean;
25347       pragma Import (Ada, E048, "system__finalization_implementation_E");
25348
25349       E044 : Boolean;
25350       pragma Import (Ada, E044, "ada__finalization_E");
25351
25352       E057 : Boolean;
25353       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
25354
25355       E055 : Boolean;
25356       pragma Import (Ada, E055, "system__file_control_block_E");
25357
25358       E042 : Boolean;
25359       pragma Import (Ada, E042, "system__file_io_E");
25360
25361       E006 : Boolean;
25362       pragma Import (Ada, E006, "ada__text_io_E");
25363
25364       --  Set_Globals is a library routine that stores away the
25365       --  value of the indicated set of global values in global
25366       --  variables within the library.
25367
25368       procedure Set_Globals
25369         (Main_Priority            : Integer;
25370          Time_Slice_Value         : Integer;
25371          WC_Encoding              : Character;
25372          Locking_Policy           : Character;
25373          Queuing_Policy           : Character;
25374          Task_Dispatching_Policy  : Character;
25375          Adafinal                 : System.Address;
25376          Unreserve_All_Interrupts : Integer;
25377          Exception_Tracebacks     : Integer);
25378 @findex __gnat_set_globals
25379       pragma Import (C, Set_Globals, "__gnat_set_globals");
25380
25381       --  SDP_Table_Build is a library routine used to build the
25382       --  exception tables. See unit Ada.Exceptions in files
25383       --  a-except.ads/adb for full details of how zero cost
25384       --  exception handling works. This procedure, the call to
25385       --  it, and the two following tables are all omitted if the
25386       --  build is in longjmp/setjump exception mode.
25387
25388 @findex SDP_Table_Build
25389 @findex Zero Cost Exceptions
25390       procedure SDP_Table_Build
25391         (SDP_Addresses   : System.Address;
25392          SDP_Count       : Natural;
25393          Elab_Addresses  : System.Address;
25394          Elab_Addr_Count : Natural);
25395       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
25396
25397       --  Table of Unit_Exception_Table addresses. Used for zero
25398       --  cost exception handling to build the top level table.
25399
25400       ST : aliased constant array (1 .. 23) of System.Address := (
25401         Hello'UET_Address,
25402         Ada.Text_Io'UET_Address,
25403         Ada.Exceptions'UET_Address,
25404         Gnat.Heap_Sort_A'UET_Address,
25405         System.Exception_Table'UET_Address,
25406         System.Machine_State_Operations'UET_Address,
25407         System.Secondary_Stack'UET_Address,
25408         System.Parameters'UET_Address,
25409         System.Soft_Links'UET_Address,
25410         System.Stack_Checking'UET_Address,
25411         System.Traceback'UET_Address,
25412         Ada.Streams'UET_Address,
25413         Ada.Tags'UET_Address,
25414         System.String_Ops'UET_Address,
25415         Interfaces.C_Streams'UET_Address,
25416         System.File_Io'UET_Address,
25417         Ada.Finalization'UET_Address,
25418         System.Finalization_Root'UET_Address,
25419         System.Finalization_Implementation'UET_Address,
25420         System.String_Ops_Concat_3'UET_Address,
25421         System.Stream_Attributes'UET_Address,
25422         System.File_Control_Block'UET_Address,
25423         Ada.Finalization.List_Controller'UET_Address);
25424
25425       --  Table of addresses of elaboration routines. Used for
25426       --  zero cost exception handling to make sure these
25427       --  addresses are included in the top level procedure
25428       --  address table.
25429
25430       EA : aliased constant array (1 .. 23) of System.Address := (
25431         adainit'Code_Address,
25432         Do_Finalize'Code_Address,
25433         Ada.Exceptions'Elab_Spec'Address,
25434         System.Exceptions'Elab_Spec'Address,
25435         Interfaces.C_Streams'Elab_Spec'Address,
25436         System.Exception_Table'Elab_Body'Address,
25437         Ada.Io_Exceptions'Elab_Spec'Address,
25438         System.Stack_Checking'Elab_Spec'Address,
25439         System.Soft_Links'Elab_Body'Address,
25440         System.Secondary_Stack'Elab_Body'Address,
25441         Ada.Tags'Elab_Spec'Address,
25442         Ada.Tags'Elab_Body'Address,
25443         Ada.Streams'Elab_Spec'Address,
25444         System.Finalization_Root'Elab_Spec'Address,
25445         Ada.Exceptions'Elab_Body'Address,
25446         System.Finalization_Implementation'Elab_Spec'Address,
25447         System.Finalization_Implementation'Elab_Body'Address,
25448         Ada.Finalization'Elab_Spec'Address,
25449         Ada.Finalization.List_Controller'Elab_Spec'Address,
25450         System.File_Control_Block'Elab_Spec'Address,
25451         System.File_Io'Elab_Body'Address,
25452         Ada.Text_Io'Elab_Spec'Address,
25453         Ada.Text_Io'Elab_Body'Address);
25454
25455    --  Start of processing for adainit
25456
25457    begin
25458
25459       --  Call SDP_Table_Build to build the top level procedure
25460       --  table for zero cost exception handling (omitted in
25461       --  longjmp/setjump mode).
25462
25463       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
25464
25465       --  Call Set_Globals to record various information for
25466       --  this partition.  The values are derived by the binder
25467       --  from information stored in the ali files by the compiler.
25468
25469 @findex __gnat_set_globals
25470       Set_Globals
25471         (Main_Priority            => -1,
25472          --  Priority of main program, -1 if no pragma Priority used
25473
25474          Time_Slice_Value         => -1,
25475          --  Time slice from Time_Slice pragma, -1 if none used
25476
25477          WC_Encoding              => 'b',
25478          --  Wide_Character encoding used, default is brackets
25479
25480          Locking_Policy           => ' ',
25481          --  Locking_Policy used, default of space means not
25482          --  specified, otherwise it is the first character of
25483          --  the policy name.
25484
25485          Queuing_Policy           => ' ',
25486          --  Queuing_Policy used, default of space means not
25487          --  specified, otherwise it is the first character of
25488          --  the policy name.
25489
25490          Task_Dispatching_Policy  => ' ',
25491          --  Task_Dispatching_Policy used, default of space means
25492          --  not specified, otherwise first character of the
25493          --  policy name.
25494
25495          Adafinal                 => System.Null_Address,
25496          --  Address of Adafinal routine, not used anymore
25497
25498          Unreserve_All_Interrupts => 0,
25499          --  Set true if pragma Unreserve_All_Interrupts was used
25500
25501          Exception_Tracebacks     => 0);
25502          --  Indicates if exception tracebacks are enabled
25503
25504       Elab_Final_Code := 1;
25505
25506       --  Now we have the elaboration calls for all units in the partition.
25507       --  The Elab_Spec and Elab_Body attributes generate references to the
25508       --  implicit elaboration procedures generated by the compiler for
25509       --  each unit that requires elaboration.
25510
25511       if not E040 then
25512          Interfaces.C_Streams'Elab_Spec;
25513       end if;
25514       E040 := True;
25515       if not E008 then
25516          Ada.Exceptions'Elab_Spec;
25517       end if;
25518       if not E014 then
25519          System.Exception_Table'Elab_Body;
25520          E014 := True;
25521       end if;
25522       if not E053 then
25523          Ada.Io_Exceptions'Elab_Spec;
25524          E053 := True;
25525       end if;
25526       if not E017 then
25527          System.Exceptions'Elab_Spec;
25528          E017 := True;
25529       end if;
25530       if not E030 then
25531          System.Stack_Checking'Elab_Spec;
25532       end if;
25533       if not E028 then
25534          System.Soft_Links'Elab_Body;
25535          E028 := True;
25536       end if;
25537       E030 := True;
25538       if not E024 then
25539          System.Secondary_Stack'Elab_Body;
25540          E024 := True;
25541       end if;
25542       if not E035 then
25543          Ada.Tags'Elab_Spec;
25544       end if;
25545       if not E035 then
25546          Ada.Tags'Elab_Body;
25547          E035 := True;
25548       end if;
25549       if not E033 then
25550          Ada.Streams'Elab_Spec;
25551          E033 := True;
25552       end if;
25553       if not E046 then
25554          System.Finalization_Root'Elab_Spec;
25555       end if;
25556       E046 := True;
25557       if not E008 then
25558          Ada.Exceptions'Elab_Body;
25559          E008 := True;
25560       end if;
25561       if not E048 then
25562          System.Finalization_Implementation'Elab_Spec;
25563       end if;
25564       if not E048 then
25565          System.Finalization_Implementation'Elab_Body;
25566          E048 := True;
25567       end if;
25568       if not E044 then
25569          Ada.Finalization'Elab_Spec;
25570       end if;
25571       E044 := True;
25572       if not E057 then
25573          Ada.Finalization.List_Controller'Elab_Spec;
25574       end if;
25575       E057 := True;
25576       if not E055 then
25577          System.File_Control_Block'Elab_Spec;
25578          E055 := True;
25579       end if;
25580       if not E042 then
25581          System.File_Io'Elab_Body;
25582          E042 := True;
25583       end if;
25584       if not E006 then
25585          Ada.Text_Io'Elab_Spec;
25586       end if;
25587       if not E006 then
25588          Ada.Text_Io'Elab_Body;
25589          E006 := True;
25590       end if;
25591
25592       Elab_Final_Code := 0;
25593    end adainit;
25594
25595    --------------
25596    -- adafinal --
25597    --------------
25598
25599 @findex adafinal
25600    procedure adafinal is
25601    begin
25602       Do_Finalize;
25603    end adafinal;
25604
25605    ----------
25606    -- main --
25607    ----------
25608
25609    --  main is actually a function, as in the ANSI C standard,
25610    --  defined to return the exit status. The three parameters
25611    --  are the argument count, argument values and environment
25612    --  pointer.
25613
25614 @findex Main Program
25615    function main
25616      (argc : Integer;
25617       argv : System.Address;
25618       envp : System.Address)
25619       return Integer
25620    is
25621       --  The initialize routine performs low level system
25622       --  initialization using a standard library routine which
25623       --  sets up signal handling and performs any other
25624       --  required setup. The routine can be found in file
25625       --  a-init.c.
25626
25627 @findex __gnat_initialize
25628       procedure initialize;
25629       pragma Import (C, initialize, "__gnat_initialize");
25630
25631       --  The finalize routine performs low level system
25632       --  finalization using a standard library routine. The
25633       --  routine is found in file a-final.c and in the standard
25634       --  distribution is a dummy routine that does nothing, so
25635       --  really this is a hook for special user finalization.
25636
25637 @findex __gnat_finalize
25638       procedure finalize;
25639       pragma Import (C, finalize, "__gnat_finalize");
25640
25641       --  We get to the main program of the partition by using
25642       --  pragma Import because if we try to with the unit and
25643       --  call it Ada style, then not only do we waste time
25644       --  recompiling it, but also, we don't really know the right
25645       --  switches (e.g.@: identifier character set) to be used
25646       --  to compile it.
25647
25648       procedure Ada_Main_Program;
25649       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
25650
25651    --  Start of processing for main
25652
25653    begin
25654       --  Save global variables
25655
25656       gnat_argc := argc;
25657       gnat_argv := argv;
25658       gnat_envp := envp;
25659
25660       --  Call low level system initialization
25661
25662       Initialize;
25663
25664       --  Call our generated Ada initialization routine
25665
25666       adainit;
25667
25668       --  This is the point at which we want the debugger to get
25669       --  control
25670
25671       Break_Start;
25672
25673       --  Now we call the main program of the partition
25674
25675       Ada_Main_Program;
25676
25677       --  Perform Ada finalization
25678
25679       adafinal;
25680
25681       --  Perform low level system finalization
25682
25683       Finalize;
25684
25685       --  Return the proper exit status
25686       return (gnat_exit_status);
25687    end;
25688
25689 --  This section is entirely comments, so it has no effect on the
25690 --  compilation of the Ada_Main package. It provides the list of
25691 --  object files and linker options, as well as some standard
25692 --  libraries needed for the link. The gnatlink utility parses
25693 --  this b~hello.adb file to read these comment lines to generate
25694 --  the appropriate command line arguments for the call to the
25695 --  system linker. The BEGIN/END lines are used for sentinels for
25696 --  this parsing operation.
25697
25698 --  The exact file names will of course depend on the environment,
25699 --  host/target and location of files on the host system.
25700
25701 @findex Object file list
25702 -- BEGIN Object file/option list
25703    --   ./hello.o
25704    --   -L./
25705    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
25706    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
25707 -- END Object file/option list
25708
25709 end ada_main;
25710 @end smallexample
25711
25712 @noindent
25713 The Ada code in the above example is exactly what is generated by the
25714 binder. We have added comments to more clearly indicate the function
25715 of each part of the generated @code{Ada_Main} package.
25716
25717 The code is standard Ada in all respects, and can be processed by any
25718 tools that handle Ada. In particular, it is possible to use the debugger
25719 in Ada mode to debug the generated @code{Ada_Main} package. For example,
25720 suppose that for reasons that you do not understand, your program is crashing
25721 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
25722 you can place a breakpoint on the call:
25723
25724 @smallexample @c ada
25725 Ada.Text_Io'Elab_Body;
25726 @end smallexample
25727
25728 @noindent
25729 and trace the elaboration routine for this package to find out where
25730 the problem might be (more usually of course you would be debugging
25731 elaboration code in your own application).
25732
25733 @node Elaboration Order Handling in GNAT
25734 @appendix Elaboration Order Handling in GNAT
25735 @cindex Order of elaboration
25736 @cindex Elaboration control
25737
25738 @menu
25739 * Elaboration Code::
25740 * Checking the Elaboration Order::
25741 * Controlling the Elaboration Order::
25742 * Controlling Elaboration in GNAT - Internal Calls::
25743 * Controlling Elaboration in GNAT - External Calls::
25744 * Default Behavior in GNAT - Ensuring Safety::
25745 * Treatment of Pragma Elaborate::
25746 * Elaboration Issues for Library Tasks::
25747 * Mixing Elaboration Models::
25748 * What to Do If the Default Elaboration Behavior Fails::
25749 * Elaboration for Access-to-Subprogram Values::
25750 * Summary of Procedures for Elaboration Control::
25751 * Other Elaboration Order Considerations::
25752 @end menu
25753
25754 @noindent
25755 This chapter describes the handling of elaboration code in Ada and
25756 in GNAT, and discusses how the order of elaboration of program units can
25757 be controlled in GNAT, either automatically or with explicit programming
25758 features.
25759
25760 @node Elaboration Code
25761 @section Elaboration Code
25762
25763 @noindent
25764 Ada provides rather general mechanisms for executing code at elaboration
25765 time, that is to say before the main program starts executing. Such code arises
25766 in three contexts:
25767
25768 @table @asis
25769 @item Initializers for variables.
25770 Variables declared at the library level, in package specs or bodies, can
25771 require initialization that is performed at elaboration time, as in:
25772 @smallexample @c ada
25773 @cartouche
25774 Sqrt_Half : Float := Sqrt (0.5);
25775 @end cartouche
25776 @end smallexample
25777
25778 @item Package initialization code
25779 Code in a @code{BEGIN-END} section at the outer level of a package body is
25780 executed as part of the package body elaboration code.
25781
25782 @item Library level task allocators
25783 Tasks that are declared using task allocators at the library level
25784 start executing immediately and hence can execute at elaboration time.
25785 @end table
25786
25787 @noindent
25788 Subprogram calls are possible in any of these contexts, which means that
25789 any arbitrary part of the program may be executed as part of the elaboration
25790 code. It is even possible to write a program which does all its work at
25791 elaboration time, with a null main program, although stylistically this
25792 would usually be considered an inappropriate way to structure
25793 a program.
25794
25795 An important concern arises in the context of elaboration code:
25796 we have to be sure that it is executed in an appropriate order. What we
25797 have is a series of elaboration code sections, potentially one section
25798 for each unit in the program. It is important that these execute
25799 in the correct order. Correctness here means that, taking the above
25800 example of the declaration of @code{Sqrt_Half},
25801 if some other piece of
25802 elaboration code references @code{Sqrt_Half},
25803 then it must run after the
25804 section of elaboration code that contains the declaration of
25805 @code{Sqrt_Half}.
25806
25807 There would never be any order of elaboration problem if we made a rule
25808 that whenever you @code{with} a unit, you must elaborate both the spec and body
25809 of that unit before elaborating the unit doing the @code{with}'ing:
25810
25811 @smallexample @c ada
25812 @group
25813 @cartouche
25814 with Unit_1;
25815 package Unit_2 is @dots{}
25816 @end cartouche
25817 @end group
25818 @end smallexample
25819
25820 @noindent
25821 would require that both the body and spec of @code{Unit_1} be elaborated
25822 before the spec of @code{Unit_2}. However, a rule like that would be far too
25823 restrictive. In particular, it would make it impossible to have routines
25824 in separate packages that were mutually recursive.
25825
25826 You might think that a clever enough compiler could look at the actual
25827 elaboration code and determine an appropriate correct order of elaboration,
25828 but in the general case, this is not possible. Consider the following
25829 example.
25830
25831 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
25832 that references
25833 the variable @code{Sqrt_1}, which is declared in the elaboration code
25834 of the body of @code{Unit_1}:
25835
25836 @smallexample @c ada
25837 @cartouche
25838 Sqrt_1 : Float := Sqrt (0.1);
25839 @end cartouche
25840 @end smallexample
25841
25842 @noindent
25843 The elaboration code of the body of @code{Unit_1} also contains:
25844
25845 @smallexample @c ada
25846 @group
25847 @cartouche
25848 if expression_1 = 1 then
25849    Q := Unit_2.Func_2;
25850 end if;
25851 @end cartouche
25852 @end group
25853 @end smallexample
25854
25855 @noindent
25856 @code{Unit_2} is exactly parallel,
25857 it has a procedure @code{Func_2} that references
25858 the variable @code{Sqrt_2}, which is declared in the elaboration code of
25859 the body @code{Unit_2}:
25860
25861 @smallexample @c ada
25862 @cartouche
25863 Sqrt_2 : Float := Sqrt (0.1);
25864 @end cartouche
25865 @end smallexample
25866
25867 @noindent
25868 The elaboration code of the body of @code{Unit_2} also contains:
25869
25870 @smallexample @c ada
25871 @group
25872 @cartouche
25873 if expression_2 = 2 then
25874    Q := Unit_1.Func_1;
25875 end if;
25876 @end cartouche
25877 @end group
25878 @end smallexample
25879
25880 @noindent
25881 Now the question is, which of the following orders of elaboration is
25882 acceptable:
25883
25884 @smallexample
25885 @group
25886 Spec of Unit_1
25887 Spec of Unit_2
25888 Body of Unit_1
25889 Body of Unit_2
25890 @end group
25891 @end smallexample
25892
25893 @noindent
25894 or
25895
25896 @smallexample
25897 @group
25898 Spec of Unit_2
25899 Spec of Unit_1
25900 Body of Unit_2
25901 Body of Unit_1
25902 @end group
25903 @end smallexample
25904
25905 @noindent
25906 If you carefully analyze the flow here, you will see that you cannot tell
25907 at compile time the answer to this question.
25908 If @code{expression_1} is not equal to 1,
25909 and @code{expression_2} is not equal to 2,
25910 then either order is acceptable, because neither of the function calls is
25911 executed. If both tests evaluate to true, then neither order is acceptable
25912 and in fact there is no correct order.
25913
25914 If one of the two expressions is true, and the other is false, then one
25915 of the above orders is correct, and the other is incorrect. For example,
25916 if @code{expression_1} /= 1 and @code{expression_2} = 2,
25917 then the call to @code{Func_1}
25918 will occur, but not the call to @code{Func_2.}
25919 This means that it is essential
25920 to elaborate the body of @code{Unit_1} before
25921 the body of @code{Unit_2}, so the first
25922 order of elaboration is correct and the second is wrong.
25923
25924 By making @code{expression_1} and @code{expression_2}
25925 depend on input data, or perhaps
25926 the time of day, we can make it impossible for the compiler or binder
25927 to figure out which of these expressions will be true, and hence it
25928 is impossible to guarantee a safe order of elaboration at run time.
25929
25930 @node Checking the Elaboration Order
25931 @section Checking the Elaboration Order
25932
25933 @noindent
25934 In some languages that involve the same kind of elaboration problems,
25935 e.g.@: Java and C++, the programmer is expected to worry about these
25936 ordering problems himself, and it is common to
25937 write a program in which an incorrect elaboration order  gives
25938 surprising results, because it references variables before they
25939 are initialized.
25940 Ada is designed to be a safe language, and a programmer-beware approach is
25941 clearly not sufficient. Consequently, the language provides three lines
25942 of defense:
25943
25944 @table @asis
25945 @item Standard rules
25946 Some standard rules restrict the possible choice of elaboration
25947 order. In particular, if you @code{with} a unit, then its spec is always
25948 elaborated before the unit doing the @code{with}. Similarly, a parent
25949 spec is always elaborated before the child spec, and finally
25950 a spec is always elaborated before its corresponding body.
25951
25952 @item Dynamic elaboration checks
25953 @cindex Elaboration checks
25954 @cindex Checks, elaboration
25955 Dynamic checks are made at run time, so that if some entity is accessed
25956 before it is elaborated (typically  by means of a subprogram call)
25957 then the exception (@code{Program_Error}) is raised.
25958
25959 @item Elaboration control
25960 Facilities are provided for the programmer to specify the desired order
25961 of elaboration.
25962 @end table
25963
25964 Let's look at these facilities in more detail. First, the rules for
25965 dynamic checking. One possible rule would be simply to say that the
25966 exception is raised if you access a variable which has not yet been
25967 elaborated. The trouble with this approach is that it could require
25968 expensive checks on every variable reference. Instead Ada has two
25969 rules which are a little more restrictive, but easier to check, and
25970 easier to state:
25971
25972 @table @asis
25973 @item Restrictions on calls
25974 A subprogram can only be called at elaboration time if its body
25975 has been elaborated. The rules for elaboration given above guarantee
25976 that the spec of the subprogram has been elaborated before the
25977 call, but not the body. If this rule is violated, then the
25978 exception @code{Program_Error} is raised.
25979
25980 @item Restrictions on instantiations
25981 A generic unit can only be instantiated if the body of the generic
25982 unit has been elaborated. Again, the rules for elaboration given above
25983 guarantee that the spec of the generic unit has been elaborated
25984 before the instantiation, but not the body. If this rule is
25985 violated, then the exception @code{Program_Error} is raised.
25986 @end table
25987
25988 @noindent
25989 The idea is that if the body has been elaborated, then any variables
25990 it references must have been elaborated; by checking for the body being
25991 elaborated we guarantee that none of its references causes any
25992 trouble. As we noted above, this is a little too restrictive, because a
25993 subprogram that has no non-local references in its body may in fact be safe
25994 to call. However, it really would be unsafe to rely on this, because
25995 it would mean that the caller was aware of details of the implementation
25996 in the body. This goes against the basic tenets of Ada.
25997
25998 A plausible implementation can be described as follows.
25999 A Boolean variable is associated with each subprogram
26000 and each generic unit. This variable is initialized to False, and is set to
26001 True at the point body is elaborated. Every call or instantiation checks the
26002 variable, and raises @code{Program_Error} if the variable is False.
26003
26004 Note that one might think that it would be good enough to have one Boolean
26005 variable for each package, but that would not deal with cases of trying
26006 to call a body in the same package as the call
26007 that has not been elaborated yet.
26008 Of course a compiler may be able to do enough analysis to optimize away
26009 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
26010 does such optimizations, but still the easiest conceptual model is to
26011 think of there being one variable per subprogram.
26012
26013 @node Controlling the Elaboration Order
26014 @section Controlling the Elaboration Order
26015
26016 @noindent
26017 In the previous section we discussed the rules in Ada which ensure
26018 that @code{Program_Error} is raised if an incorrect elaboration order is
26019 chosen. This prevents erroneous executions, but we need mechanisms to
26020 specify a correct execution and avoid the exception altogether.
26021 To achieve this, Ada provides a number of features for controlling
26022 the order of elaboration. We discuss these features in this section.
26023
26024 First, there are several ways of indicating to the compiler that a given
26025 unit has no elaboration problems:
26026
26027 @table @asis
26028 @item packages that do not require a body
26029 A library package that does not require a body does not permit
26030 a body (this rule was introduced in Ada 95).
26031 Thus if we have a such a package, as in:
26032
26033 @smallexample @c ada
26034 @group
26035 @cartouche
26036 package Definitions is
26037    generic
26038       type m is new integer;
26039    package Subp is
26040       type a is array (1 .. 10) of m;
26041       type b is array (1 .. 20) of m;
26042    end Subp;
26043 end Definitions;
26044 @end cartouche
26045 @end group
26046 @end smallexample
26047
26048 @noindent
26049 A package that @code{with}'s @code{Definitions} may safely instantiate
26050 @code{Definitions.Subp} because the compiler can determine that there
26051 definitely is no package body to worry about in this case
26052
26053 @item pragma Pure
26054 @cindex pragma Pure
26055 @findex Pure
26056 Places sufficient restrictions on a unit to guarantee that
26057 no call to any subprogram in the unit can result in an
26058 elaboration problem. This means that the compiler does not need
26059 to worry about the point of elaboration of such units, and in
26060 particular, does not need to check any calls to any subprograms
26061 in this unit.
26062
26063 @item pragma Preelaborate
26064 @findex Preelaborate
26065 @cindex pragma Preelaborate
26066 This pragma places slightly less stringent restrictions on a unit than
26067 does pragma Pure,
26068 but these restrictions are still sufficient to ensure that there
26069 are no elaboration problems with any calls to the unit.
26070
26071 @item pragma Elaborate_Body
26072 @findex Elaborate_Body
26073 @cindex pragma Elaborate_Body
26074 This pragma requires that the body of a unit be elaborated immediately
26075 after its spec. Suppose a unit @code{A} has such a pragma,
26076 and unit @code{B} does
26077 a @code{with} of unit @code{A}. Recall that the standard rules require
26078 the spec of unit @code{A}
26079 to be elaborated before the @code{with}'ing unit; given the pragma in
26080 @code{A}, we also know that the body of @code{A}
26081 will be elaborated before @code{B}, so
26082 that calls to @code{A} are safe and do not need a check.
26083 @end table
26084
26085 @noindent
26086 Note that,
26087 unlike pragma @code{Pure} and pragma @code{Preelaborate},
26088 the use of
26089 @code{Elaborate_Body} does not guarantee that the program is
26090 free of elaboration problems, because it may not be possible
26091 to satisfy the requested elaboration order.
26092 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
26093 If a programmer
26094 marks @code{Unit_1} as @code{Elaborate_Body},
26095 and not @code{Unit_2,} then the order of
26096 elaboration will be:
26097
26098 @smallexample
26099 @group
26100 Spec of Unit_2
26101 Spec of Unit_1
26102 Body of Unit_1
26103 Body of Unit_2
26104 @end group
26105 @end smallexample
26106
26107 @noindent
26108 Now that means that the call to @code{Func_1} in @code{Unit_2}
26109 need not be checked,
26110 it must be safe. But the call to @code{Func_2} in
26111 @code{Unit_1} may still fail if
26112 @code{Expression_1} is equal to 1,
26113 and the programmer must still take
26114 responsibility for this not being the case.
26115
26116 If all units carry a pragma @code{Elaborate_Body}, then all problems are
26117 eliminated, except for calls entirely within a body, which are
26118 in any case fully under programmer control. However, using the pragma
26119 everywhere is not always possible.
26120 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
26121 we marked both of them as having pragma @code{Elaborate_Body}, then
26122 clearly there would be no possible elaboration order.
26123
26124 The above pragmas allow a server to guarantee safe use by clients, and
26125 clearly this is the preferable approach. Consequently a good rule
26126 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
26127 and if this is not possible,
26128 mark them as @code{Elaborate_Body} if possible.
26129 As we have seen, there are situations where neither of these
26130 three pragmas can be used.
26131 So we also provide methods for clients to control the
26132 order of elaboration of the servers on which they depend:
26133
26134 @table @asis
26135 @item pragma Elaborate (unit)
26136 @findex Elaborate
26137 @cindex pragma Elaborate
26138 This pragma is placed in the context clause, after a @code{with} clause,
26139 and it requires that the body of the named unit be elaborated before
26140 the unit in which the pragma occurs. The idea is to use this pragma
26141 if the current unit calls at elaboration time, directly or indirectly,
26142 some subprogram in the named unit.
26143
26144 @item pragma Elaborate_All (unit)
26145 @findex Elaborate_All
26146 @cindex pragma Elaborate_All
26147 This is a stronger version of the Elaborate pragma. Consider the
26148 following example:
26149
26150 @smallexample
26151 Unit A @code{with}'s unit B and calls B.Func in elab code
26152 Unit B @code{with}'s unit C, and B.Func calls C.Func
26153 @end smallexample
26154
26155 @noindent
26156 Now if we put a pragma @code{Elaborate (B)}
26157 in unit @code{A}, this ensures that the
26158 body of @code{B} is elaborated before the call, but not the
26159 body of @code{C}, so
26160 the call to @code{C.Func} could still cause @code{Program_Error} to
26161 be raised.
26162
26163 The effect of a pragma @code{Elaborate_All} is stronger, it requires
26164 not only that the body of the named unit be elaborated before the
26165 unit doing the @code{with}, but also the bodies of all units that the
26166 named unit uses, following @code{with} links transitively. For example,
26167 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
26168 then it requires
26169 not only that the body of @code{B} be elaborated before @code{A},
26170 but also the
26171 body of @code{C}, because @code{B} @code{with}'s @code{C}.
26172 @end table
26173
26174 @noindent
26175 We are now in a position to give a usage rule in Ada for avoiding
26176 elaboration problems, at least if dynamic dispatching and access to
26177 subprogram values are not used. We will handle these cases separately
26178 later.
26179
26180 The rule is simple. If a unit has elaboration code that can directly or
26181 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
26182 a generic package in a @code{with}'ed unit,
26183 then if the @code{with}'ed unit does not have
26184 pragma @code{Pure} or @code{Preelaborate}, then the client should have
26185 a pragma @code{Elaborate_All}
26186 for the @code{with}'ed unit. By following this rule a client is
26187 assured that calls can be made without risk of an exception.
26188
26189 For generic subprogram instantiations, the rule can be relaxed to
26190 require only a pragma @code{Elaborate} since elaborating the body
26191 of a subprogram cannot cause any transitive elaboration (we are
26192 not calling the subprogram in this case, just elaborating its
26193 declaration).
26194
26195 If this rule is not followed, then a program may be in one of four
26196 states:
26197
26198 @table @asis
26199 @item No order exists
26200 No order of elaboration exists which follows the rules, taking into
26201 account any @code{Elaborate}, @code{Elaborate_All},
26202 or @code{Elaborate_Body} pragmas. In
26203 this case, an Ada compiler must diagnose the situation at bind
26204 time, and refuse to build an executable program.
26205
26206 @item One or more orders exist, all incorrect
26207 One or more acceptable elaboration orders exist, and all of them
26208 generate an elaboration order problem. In this case, the binder
26209 can build an executable program, but @code{Program_Error} will be raised
26210 when the program is run.
26211
26212 @item Several orders exist, some right, some incorrect
26213 One or more acceptable elaboration orders exists, and some of them
26214 work, and some do not. The programmer has not controlled
26215 the order of elaboration, so the binder may or may not pick one of
26216 the correct orders, and the program may or may not raise an
26217 exception when it is run. This is the worst case, because it means
26218 that the program may fail when moved to another compiler, or even
26219 another version of the same compiler.
26220
26221 @item One or more orders exists, all correct
26222 One ore more acceptable elaboration orders exist, and all of them
26223 work. In this case the program runs successfully. This state of
26224 affairs can be guaranteed by following the rule we gave above, but
26225 may be true even if the rule is not followed.
26226 @end table
26227
26228 @noindent
26229 Note that one additional advantage of following our rules on the use
26230 of @code{Elaborate} and @code{Elaborate_All}
26231 is that the program continues to stay in the ideal (all orders OK) state
26232 even if maintenance
26233 changes some bodies of some units. Conversely, if a program that does
26234 not follow this rule happens to be safe at some point, this state of affairs
26235 may deteriorate silently as a result of maintenance changes.
26236
26237 You may have noticed that the above discussion did not mention
26238 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
26239 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
26240 code in the body makes calls to some other unit, so it is still necessary
26241 to use @code{Elaborate_All} on such units.
26242
26243 @node Controlling Elaboration in GNAT - Internal Calls
26244 @section Controlling Elaboration in GNAT - Internal Calls
26245
26246 @noindent
26247 In the case of internal calls, i.e., calls within a single package, the
26248 programmer has full control over the order of elaboration, and it is up
26249 to the programmer to elaborate declarations in an appropriate order. For
26250 example writing:
26251
26252 @smallexample @c ada
26253 @group
26254 @cartouche
26255 function One return Float;
26256
26257 Q : Float := One;
26258
26259 function One return Float is
26260 begin
26261      return 1.0;
26262 end One;
26263 @end cartouche
26264 @end group
26265 @end smallexample
26266
26267 @noindent
26268 will obviously raise @code{Program_Error} at run time, because function
26269 One will be called before its body is elaborated. In this case GNAT will
26270 generate a warning that the call will raise @code{Program_Error}:
26271
26272 @smallexample
26273 @group
26274 @cartouche
26275  1. procedure y is
26276  2.    function One return Float;
26277  3.
26278  4.    Q : Float := One;
26279                     |
26280     >>> warning: cannot call "One" before body is elaborated
26281     >>> warning: Program_Error will be raised at run time
26282
26283  5.
26284  6.    function One return Float is
26285  7.    begin
26286  8.         return 1.0;
26287  9.    end One;
26288 10.
26289 11. begin
26290 12.    null;
26291 13. end;
26292 @end cartouche
26293 @end group
26294 @end smallexample
26295
26296 @noindent
26297 Note that in this particular case, it is likely that the call is safe, because
26298 the function @code{One} does not access any global variables.
26299 Nevertheless in Ada, we do not want the validity of the check to depend on
26300 the contents of the body (think about the separate compilation case), so this
26301 is still wrong, as we discussed in the previous sections.
26302
26303 The error is easily corrected by rearranging the declarations so that the
26304 body of @code{One} appears before the declaration containing the call
26305 (note that in Ada 95 and Ada 2005,
26306 declarations can appear in any order, so there is no restriction that
26307 would prevent this reordering, and if we write:
26308
26309 @smallexample @c ada
26310 @group
26311 @cartouche
26312 function One return Float;
26313
26314 function One return Float is
26315 begin
26316      return 1.0;
26317 end One;
26318
26319 Q : Float := One;
26320 @end cartouche
26321 @end group
26322 @end smallexample
26323
26324 @noindent
26325 then all is well, no warning is generated, and no
26326 @code{Program_Error} exception
26327 will be raised.
26328 Things are more complicated when a chain of subprograms is executed:
26329
26330 @smallexample @c ada
26331 @group
26332 @cartouche
26333 function A return Integer;
26334 function B return Integer;
26335 function C return Integer;
26336
26337 function B return Integer is begin return A; end;
26338 function C return Integer is begin return B; end;
26339
26340 X : Integer := C;
26341
26342 function A return Integer is begin return 1; end;
26343 @end cartouche
26344 @end group
26345 @end smallexample
26346
26347 @noindent
26348 Now the call to @code{C}
26349 at elaboration time in the declaration of @code{X} is correct, because
26350 the body of @code{C} is already elaborated,
26351 and the call to @code{B} within the body of
26352 @code{C} is correct, but the call
26353 to @code{A} within the body of @code{B} is incorrect, because the body
26354 of @code{A} has not been elaborated, so @code{Program_Error}
26355 will be raised on the call to @code{A}.
26356 In this case GNAT will generate a
26357 warning that @code{Program_Error} may be
26358 raised at the point of the call. Let's look at the warning:
26359
26360 @smallexample
26361 @group
26362 @cartouche
26363  1. procedure x is
26364  2.    function A return Integer;
26365  3.    function B return Integer;
26366  4.    function C return Integer;
26367  5.
26368  6.    function B return Integer is begin return A; end;
26369                                                     |
26370     >>> warning: call to "A" before body is elaborated may
26371                  raise Program_Error
26372     >>> warning: "B" called at line 7
26373     >>> warning: "C" called at line 9
26374
26375  7.    function C return Integer is begin return B; end;
26376  8.
26377  9.    X : Integer := C;
26378 10.
26379 11.    function A return Integer is begin return 1; end;
26380 12.
26381 13. begin
26382 14.    null;
26383 15. end;
26384 @end cartouche
26385 @end group
26386 @end smallexample
26387
26388 @noindent
26389 Note that the message here says ``may raise'', instead of the direct case,
26390 where the message says ``will be raised''. That's because whether
26391 @code{A} is
26392 actually called depends in general on run-time flow of control.
26393 For example, if the body of @code{B} said
26394
26395 @smallexample @c ada
26396 @group
26397 @cartouche
26398 function B return Integer is
26399 begin
26400    if some-condition-depending-on-input-data then
26401       return A;
26402    else
26403       return 1;
26404    end if;
26405 end B;
26406 @end cartouche
26407 @end group
26408 @end smallexample
26409
26410 @noindent
26411 then we could not know until run time whether the incorrect call to A would
26412 actually occur, so @code{Program_Error} might
26413 or might not be raised. It is possible for a compiler to
26414 do a better job of analyzing bodies, to
26415 determine whether or not @code{Program_Error}
26416 might be raised, but it certainly
26417 couldn't do a perfect job (that would require solving the halting problem
26418 and is provably impossible), and because this is a warning anyway, it does
26419 not seem worth the effort to do the analysis. Cases in which it
26420 would be relevant are rare.
26421
26422 In practice, warnings of either of the forms given
26423 above will usually correspond to
26424 real errors, and should be examined carefully and eliminated.
26425 In the rare case where a warning is bogus, it can be suppressed by any of
26426 the following methods:
26427
26428 @itemize @bullet
26429 @item
26430 Compile with the @option{-gnatws} switch set
26431
26432 @item
26433 Suppress @code{Elaboration_Check} for the called subprogram
26434
26435 @item
26436 Use pragma @code{Warnings_Off} to turn warnings off for the call
26437 @end itemize
26438
26439 @noindent
26440 For the internal elaboration check case,
26441 GNAT by default generates the
26442 necessary run-time checks to ensure
26443 that @code{Program_Error} is raised if any
26444 call fails an elaboration check. Of course this can only happen if a
26445 warning has been issued as described above. The use of pragma
26446 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
26447 some of these checks, meaning that it may be possible (but is not
26448 guaranteed) for a program to be able to call a subprogram whose body
26449 is not yet elaborated, without raising a @code{Program_Error} exception.
26450
26451 @node Controlling Elaboration in GNAT - External Calls
26452 @section Controlling Elaboration in GNAT - External Calls
26453
26454 @noindent
26455 The previous section discussed the case in which the execution of a
26456 particular thread of elaboration code occurred entirely within a
26457 single unit. This is the easy case to handle, because a programmer
26458 has direct and total control over the order of elaboration, and
26459 furthermore, checks need only be generated in cases which are rare
26460 and which the compiler can easily detect.
26461 The situation is more complex when separate compilation is taken into account.
26462 Consider the following:
26463
26464 @smallexample @c ada
26465 @cartouche
26466 @group
26467 package Math is
26468    function Sqrt (Arg : Float) return Float;
26469 end Math;
26470
26471 package body Math is
26472    function Sqrt (Arg : Float) return Float is
26473    begin
26474          @dots{}
26475    end Sqrt;
26476 end Math;
26477 @end group
26478 @group
26479 with Math;
26480 package Stuff is
26481    X : Float := Math.Sqrt (0.5);
26482 end Stuff;
26483
26484 with Stuff;
26485 procedure Main is
26486 begin
26487    @dots{}
26488 end Main;
26489 @end group
26490 @end cartouche
26491 @end smallexample
26492
26493 @noindent
26494 where @code{Main} is the main program. When this program is executed, the
26495 elaboration code must first be executed, and one of the jobs of the
26496 binder is to determine the order in which the units of a program are
26497 to be elaborated. In this case we have four units: the spec and body
26498 of @code{Math},
26499 the spec of @code{Stuff} and the body of @code{Main}).
26500 In what order should the four separate sections of elaboration code
26501 be executed?
26502
26503 There are some restrictions in the order of elaboration that the binder
26504 can choose. In particular, if unit U has a @code{with}
26505 for a package @code{X}, then you
26506 are assured that the spec of @code{X}
26507 is elaborated before U , but you are
26508 not assured that the body of @code{X}
26509 is elaborated before U.
26510 This means that in the above case, the binder is allowed to choose the
26511 order:
26512
26513 @smallexample
26514 spec of Math
26515 spec of Stuff
26516 body of Math
26517 body of Main
26518 @end smallexample
26519
26520 @noindent
26521 but that's not good, because now the call to @code{Math.Sqrt}
26522 that happens during
26523 the elaboration of the @code{Stuff}
26524 spec happens before the body of @code{Math.Sqrt} is
26525 elaborated, and hence causes @code{Program_Error} exception to be raised.
26526 At first glance, one might say that the binder is misbehaving, because
26527 obviously you want to elaborate the body of something you @code{with}
26528 first, but
26529 that is not a general rule that can be followed in all cases. Consider
26530
26531 @smallexample @c ada
26532 @group
26533 @cartouche
26534 package X is @dots{}
26535
26536 package Y is @dots{}
26537
26538 with X;
26539 package body Y is @dots{}
26540
26541 with Y;
26542 package body X is @dots{}
26543 @end cartouche
26544 @end group
26545 @end smallexample
26546
26547 @noindent
26548 This is a common arrangement, and, apart from the order of elaboration
26549 problems that might arise in connection with elaboration code, this works fine.
26550 A rule that says that you must first elaborate the body of anything you
26551 @code{with} cannot work in this case:
26552 the body of @code{X} @code{with}'s @code{Y},
26553 which means you would have to
26554 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
26555 which means
26556 you have to elaborate the body of @code{X} first, but @dots{} and we have a
26557 loop that cannot be broken.
26558
26559 It is true that the binder can in many cases guess an order of elaboration
26560 that is unlikely to cause a @code{Program_Error}
26561 exception to be raised, and it tries to do so (in the
26562 above example of @code{Math/Stuff/Spec}, the GNAT binder will
26563 by default
26564 elaborate the body of @code{Math} right after its spec, so all will be well).
26565
26566 However, a program that blindly relies on the binder to be helpful can
26567 get into trouble, as we discussed in the previous sections, so
26568 GNAT
26569 provides a number of facilities for assisting the programmer in
26570 developing programs that are robust with respect to elaboration order.
26571
26572 @node Default Behavior in GNAT - Ensuring Safety
26573 @section Default Behavior in GNAT - Ensuring Safety
26574
26575 @noindent
26576 The default behavior in GNAT ensures elaboration safety. In its
26577 default mode GNAT implements the
26578 rule we previously described as the right approach. Let's restate it:
26579
26580 @itemize
26581 @item
26582 @emph{If a unit has elaboration code that can directly or indirectly make a
26583 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
26584 package in a @code{with}'ed unit, then if the @code{with}'ed unit
26585 does not have pragma @code{Pure} or
26586 @code{Preelaborate}, then the client should have an
26587 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
26588
26589 @emph{In the case of instantiating a generic subprogram, it is always
26590 sufficient to have only an @code{Elaborate} pragma for the
26591 @code{with}'ed unit.}
26592 @end itemize
26593
26594 @noindent
26595 By following this rule a client is assured that calls and instantiations
26596 can be made without risk of an exception.
26597
26598 In this mode GNAT traces all calls that are potentially made from
26599 elaboration code, and puts in any missing implicit @code{Elaborate}
26600 and @code{Elaborate_All} pragmas.
26601 The advantage of this approach is that no elaboration problems
26602 are possible if the binder can find an elaboration order that is
26603 consistent with these implicit @code{Elaborate} and
26604 @code{Elaborate_All} pragmas. The
26605 disadvantage of this approach is that no such order may exist.
26606
26607 If the binder does not generate any diagnostics, then it means that it has
26608 found an elaboration order that is guaranteed to be safe. However, the binder
26609 may still be relying on implicitly generated @code{Elaborate} and
26610 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
26611 guaranteed.
26612
26613 If it is important to guarantee portability, then the compilations should
26614 use the
26615 @option{-gnatwl}
26616 (warn on elaboration problems) switch. This will cause warning messages
26617 to be generated indicating the missing @code{Elaborate} and
26618 @code{Elaborate_All} pragmas.
26619 Consider the following source program:
26620
26621 @smallexample @c ada
26622 @group
26623 @cartouche
26624 with k;
26625 package j is
26626   m : integer := k.r;
26627 end;
26628 @end cartouche
26629 @end group
26630 @end smallexample
26631
26632 @noindent
26633 where it is clear that there
26634 should be a pragma @code{Elaborate_All}
26635 for unit @code{k}. An implicit pragma will be generated, and it is
26636 likely that the binder will be able to honor it. However, if you want
26637 to port this program to some other Ada compiler than GNAT.
26638 it is safer to include the pragma explicitly in the source. If this
26639 unit is compiled with the
26640 @option{-gnatwl}
26641 switch, then the compiler outputs a warning:
26642
26643 @smallexample
26644 @group
26645 @cartouche
26646 1. with k;
26647 2. package j is
26648 3.   m : integer := k.r;
26649                      |
26650    >>> warning: call to "r" may raise Program_Error
26651    >>> warning: missing pragma Elaborate_All for "k"
26652
26653 4. end;
26654 @end cartouche
26655 @end group
26656 @end smallexample
26657
26658 @noindent
26659 and these warnings can be used as a guide for supplying manually
26660 the missing pragmas. It is usually a bad idea to use this warning
26661 option during development. That's because it will warn you when
26662 you need to put in a pragma, but cannot warn you when it is time
26663 to take it out. So the use of pragma @code{Elaborate_All} may lead to
26664 unnecessary dependencies and even false circularities.
26665
26666 This default mode is more restrictive than the Ada Reference
26667 Manual, and it is possible to construct programs which will compile
26668 using the dynamic model described there, but will run into a
26669 circularity using the safer static model we have described.
26670
26671 Of course any Ada compiler must be able to operate in a mode
26672 consistent with the requirements of the Ada Reference Manual,
26673 and in particular must have the capability of implementing the
26674 standard dynamic model of elaboration with run-time checks.
26675
26676 In GNAT, this standard mode can be achieved either by the use of
26677 the @option{-gnatE} switch on the compiler (@command{gcc} or
26678 @command{gnatmake}) command, or by the use of the configuration pragma:
26679
26680 @smallexample @c ada
26681 pragma Elaboration_Checks (RM);
26682 @end smallexample
26683
26684 @noindent
26685 Either approach will cause the unit affected to be compiled using the
26686 standard dynamic run-time elaboration checks described in the Ada
26687 Reference Manual. The static model is generally preferable, since it
26688 is clearly safer to rely on compile and link time checks rather than
26689 run-time checks. However, in the case of legacy code, it may be
26690 difficult to meet the requirements of the static model. This
26691 issue is further discussed in
26692 @ref{What to Do If the Default Elaboration Behavior Fails}.
26693
26694 Note that the static model provides a strict subset of the allowed
26695 behavior and programs of the Ada Reference Manual, so if you do
26696 adhere to the static model and no circularities exist,
26697 then you are assured that your program will
26698 work using the dynamic model, providing that you remove any
26699 pragma Elaborate statements from the source.
26700
26701 @node Treatment of Pragma Elaborate
26702 @section Treatment of Pragma Elaborate
26703 @cindex Pragma Elaborate
26704
26705 @noindent
26706 The use of @code{pragma Elaborate}
26707 should generally be avoided in Ada 95 and Ada 2005 programs,
26708 since there is no guarantee that transitive calls
26709 will be properly handled. Indeed at one point, this pragma was placed
26710 in Annex J (Obsolescent Features), on the grounds that it is never useful.
26711
26712 Now that's a bit restrictive. In practice, the case in which
26713 @code{pragma Elaborate} is useful is when the caller knows that there
26714 are no transitive calls, or that the called unit contains all necessary
26715 transitive @code{pragma Elaborate} statements, and legacy code often
26716 contains such uses.
26717
26718 Strictly speaking the static mode in GNAT should ignore such pragmas,
26719 since there is no assurance at compile time that the necessary safety
26720 conditions are met. In practice, this would cause GNAT to be incompatible
26721 with correctly written Ada 83 code that had all necessary
26722 @code{pragma Elaborate} statements in place. Consequently, we made the
26723 decision that GNAT in its default mode will believe that if it encounters
26724 a @code{pragma Elaborate} then the programmer knows what they are doing,
26725 and it will trust that no elaboration errors can occur.
26726
26727 The result of this decision is two-fold. First to be safe using the
26728 static mode, you should remove all @code{pragma Elaborate} statements.
26729 Second, when fixing circularities in existing code, you can selectively
26730 use @code{pragma Elaborate} statements to convince the static mode of
26731 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
26732 statement.
26733
26734 When using the static mode with @option{-gnatwl}, any use of
26735 @code{pragma Elaborate} will generate a warning about possible
26736 problems.
26737
26738 @node Elaboration Issues for Library Tasks
26739 @section Elaboration Issues for Library Tasks
26740 @cindex Library tasks, elaboration issues
26741 @cindex Elaboration of library tasks
26742
26743 @noindent
26744 In this section we examine special elaboration issues that arise for
26745 programs that declare library level tasks.
26746
26747 Generally the model of execution of an Ada program is that all units are
26748 elaborated, and then execution of the program starts. However, the
26749 declaration of library tasks definitely does not fit this model. The
26750 reason for this is that library tasks start as soon as they are declared
26751 (more precisely, as soon as the statement part of the enclosing package
26752 body is reached), that is to say before elaboration
26753 of the program is complete. This means that if such a task calls a
26754 subprogram, or an entry in another task, the callee may or may not be
26755 elaborated yet, and in the standard
26756 Reference Manual model of dynamic elaboration checks, you can even
26757 get timing dependent Program_Error exceptions, since there can be
26758 a race between the elaboration code and the task code.
26759
26760 The static model of elaboration in GNAT seeks to avoid all such
26761 dynamic behavior, by being conservative, and the conservative
26762 approach in this particular case is to assume that all the code
26763 in a task body is potentially executed at elaboration time if
26764 a task is declared at the library level.
26765
26766 This can definitely result in unexpected circularities. Consider
26767 the following example
26768
26769 @smallexample @c ada
26770 package Decls is
26771   task Lib_Task is
26772      entry Start;
26773   end Lib_Task;
26774
26775   type My_Int is new Integer;
26776
26777   function Ident (M : My_Int) return My_Int;
26778 end Decls;
26779
26780 with Utils;
26781 package body Decls is
26782   task body Lib_Task is
26783   begin
26784      accept Start;
26785      Utils.Put_Val (2);
26786   end Lib_Task;
26787
26788   function Ident (M : My_Int) return My_Int is
26789   begin
26790      return M;
26791   end Ident;
26792 end Decls;
26793
26794 with Decls;
26795 package Utils is
26796   procedure Put_Val (Arg : Decls.My_Int);
26797 end Utils;
26798
26799 with Text_IO;
26800 package body Utils is
26801   procedure Put_Val (Arg : Decls.My_Int) is
26802   begin
26803      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26804   end Put_Val;
26805 end Utils;
26806
26807 with Decls;
26808 procedure Main is
26809 begin
26810    Decls.Lib_Task.Start;
26811 end;
26812 @end smallexample
26813
26814 @noindent
26815 If the above example is compiled in the default static elaboration
26816 mode, then a circularity occurs. The circularity comes from the call
26817 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
26818 this call occurs in elaboration code, we need an implicit pragma
26819 @code{Elaborate_All} for @code{Utils}. This means that not only must
26820 the spec and body of @code{Utils} be elaborated before the body
26821 of @code{Decls}, but also the spec and body of any unit that is
26822 @code{with'ed} by the body of @code{Utils} must also be elaborated before
26823 the body of @code{Decls}. This is the transitive implication of
26824 pragma @code{Elaborate_All} and it makes sense, because in general
26825 the body of @code{Put_Val} might have a call to something in a
26826 @code{with'ed} unit.
26827
26828 In this case, the body of Utils (actually its spec) @code{with's}
26829 @code{Decls}. Unfortunately this means that the body of @code{Decls}
26830 must be elaborated before itself, in case there is a call from the
26831 body of @code{Utils}.
26832
26833 Here is the exact chain of events we are worrying about:
26834
26835 @enumerate
26836 @item
26837 In the body of @code{Decls} a call is made from within the body of a library
26838 task to a subprogram in the package @code{Utils}. Since this call may
26839 occur at elaboration time (given that the task is activated at elaboration
26840 time), we have to assume the worst, i.e., that the
26841 call does happen at elaboration time.
26842
26843 @item
26844 This means that the body and spec of @code{Util} must be elaborated before
26845 the body of @code{Decls} so that this call does not cause an access before
26846 elaboration.
26847
26848 @item
26849 Within the body of @code{Util}, specifically within the body of
26850 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
26851 by this package.
26852
26853 @item
26854 One such @code{with}'ed package is package @code{Decls}, so there
26855 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
26856 In fact there is such a call in this example, but we would have to
26857 assume that there was such a call even if it were not there, since
26858 we are not supposed to write the body of @code{Decls} knowing what
26859 is in the body of @code{Utils}; certainly in the case of the
26860 static elaboration model, the compiler does not know what is in
26861 other bodies and must assume the worst.
26862
26863 @item
26864 This means that the spec and body of @code{Decls} must also be
26865 elaborated before we elaborate the unit containing the call, but
26866 that unit is @code{Decls}! This means that the body of @code{Decls}
26867 must be elaborated before itself, and that's a circularity.
26868 @end enumerate
26869
26870 @noindent
26871 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
26872 the body of @code{Decls} you will get a true Ada Reference Manual
26873 circularity that makes the program illegal.
26874
26875 In practice, we have found that problems with the static model of
26876 elaboration in existing code often arise from library tasks, so
26877 we must address this particular situation.
26878
26879 Note that if we compile and run the program above, using the dynamic model of
26880 elaboration (that is to say use the @option{-gnatE} switch),
26881 then it compiles, binds,
26882 links, and runs, printing the expected result of 2. Therefore in some sense
26883 the circularity here is only apparent, and we need to capture
26884 the properties of this program that  distinguish it from other library-level
26885 tasks that have real elaboration problems.
26886
26887 We have four possible answers to this question:
26888
26889 @itemize @bullet
26890
26891 @item
26892 Use the dynamic model of elaboration.
26893
26894 If we use the @option{-gnatE} switch, then as noted above, the program works.
26895 Why is this? If we examine the task body, it is apparent that the task cannot
26896 proceed past the
26897 @code{accept} statement until after elaboration has been completed, because
26898 the corresponding entry call comes from the main program, not earlier.
26899 This is why the dynamic model works here. But that's really giving
26900 up on a precise analysis, and we prefer to take this approach only if we cannot
26901 solve the
26902 problem in any other manner. So let us examine two ways to reorganize
26903 the program to avoid the potential elaboration problem.
26904
26905 @item
26906 Split library tasks into separate packages.
26907
26908 Write separate packages, so that library tasks are isolated from
26909 other declarations as much as possible. Let us look at a variation on
26910 the above program.
26911
26912 @smallexample @c ada
26913 package Decls1 is
26914   task Lib_Task is
26915      entry Start;
26916   end Lib_Task;
26917 end Decls1;
26918
26919 with Utils;
26920 package body Decls1 is
26921   task body Lib_Task is
26922   begin
26923      accept Start;
26924      Utils.Put_Val (2);
26925   end Lib_Task;
26926 end Decls1;
26927
26928 package Decls2 is
26929   type My_Int is new Integer;
26930   function Ident (M : My_Int) return My_Int;
26931 end Decls2;
26932
26933 with Utils;
26934 package body Decls2 is
26935   function Ident (M : My_Int) return My_Int is
26936   begin
26937      return M;
26938   end Ident;
26939 end Decls2;
26940
26941 with Decls2;
26942 package Utils is
26943   procedure Put_Val (Arg : Decls2.My_Int);
26944 end Utils;
26945
26946 with Text_IO;
26947 package body Utils is
26948   procedure Put_Val (Arg : Decls2.My_Int) is
26949   begin
26950      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
26951   end Put_Val;
26952 end Utils;
26953
26954 with Decls1;
26955 procedure Main is
26956 begin
26957    Decls1.Lib_Task.Start;
26958 end;
26959 @end smallexample
26960
26961 @noindent
26962 All we have done is to split @code{Decls} into two packages, one
26963 containing the library task, and one containing everything else. Now
26964 there is no cycle, and the program compiles, binds, links and executes
26965 using the default static model of elaboration.
26966
26967 @item
26968 Declare separate task types.
26969
26970 A significant part of the problem arises because of the use of the
26971 single task declaration form. This means that the elaboration of
26972 the task type, and the elaboration of the task itself (i.e.@: the
26973 creation of the task) happen at the same time. A good rule
26974 of style in Ada is to always create explicit task types. By
26975 following the additional step of placing task objects in separate
26976 packages from the task type declaration, many elaboration problems
26977 are avoided. Here is another modified example of the example program:
26978
26979 @smallexample @c ada
26980 package Decls is
26981   task type Lib_Task_Type is
26982      entry Start;
26983   end Lib_Task_Type;
26984
26985   type My_Int is new Integer;
26986
26987   function Ident (M : My_Int) return My_Int;
26988 end Decls;
26989
26990 with Utils;
26991 package body Decls is
26992   task body Lib_Task_Type is
26993   begin
26994      accept Start;
26995      Utils.Put_Val (2);
26996   end Lib_Task_Type;
26997
26998   function Ident (M : My_Int) return My_Int is
26999   begin
27000      return M;
27001   end Ident;
27002 end Decls;
27003
27004 with Decls;
27005 package Utils is
27006   procedure Put_Val (Arg : Decls.My_Int);
27007 end Utils;
27008
27009 with Text_IO;
27010 package body Utils is
27011   procedure Put_Val (Arg : Decls.My_Int) is
27012   begin
27013      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27014   end Put_Val;
27015 end Utils;
27016
27017 with Decls;
27018 package Declst is
27019    Lib_Task : Decls.Lib_Task_Type;
27020 end Declst;
27021
27022 with Declst;
27023 procedure Main is
27024 begin
27025    Declst.Lib_Task.Start;
27026 end;
27027 @end smallexample
27028
27029 @noindent
27030 What we have done here is to replace the @code{task} declaration in
27031 package @code{Decls} with a @code{task type} declaration. Then we
27032 introduce a separate package @code{Declst} to contain the actual
27033 task object. This separates the elaboration issues for
27034 the @code{task type}
27035 declaration, which causes no trouble, from the elaboration issues
27036 of the task object, which is also unproblematic, since it is now independent
27037 of the elaboration of  @code{Utils}.
27038 This separation of concerns also corresponds to
27039 a generally sound engineering principle of separating declarations
27040 from instances. This version of the program also compiles, binds, links,
27041 and executes, generating the expected output.
27042
27043 @item
27044 Use No_Entry_Calls_In_Elaboration_Code restriction.
27045 @cindex No_Entry_Calls_In_Elaboration_Code
27046
27047 The previous two approaches described how a program can be restructured
27048 to avoid the special problems caused by library task bodies. in practice,
27049 however, such restructuring may be difficult to apply to existing legacy code,
27050 so we must consider solutions that do not require massive rewriting.
27051
27052 Let us consider more carefully why our original sample program works
27053 under the dynamic model of elaboration. The reason is that the code
27054 in the task body blocks immediately on the @code{accept}
27055 statement. Now of course there is nothing to prohibit elaboration
27056 code from making entry calls (for example from another library level task),
27057 so we cannot tell in isolation that
27058 the task will not execute the accept statement  during elaboration.
27059
27060 However, in practice it is very unusual to see elaboration code
27061 make any entry calls, and the pattern of tasks starting
27062 at elaboration time and then immediately blocking on @code{accept} or
27063 @code{select} statements is very common. What this means is that
27064 the compiler is being too pessimistic when it analyzes the
27065 whole package body as though it might be executed at elaboration
27066 time.
27067
27068 If we know that the elaboration code contains no entry calls, (a very safe
27069 assumption most of the time, that could almost be made the default
27070 behavior), then we can compile all units of the program under control
27071 of the following configuration pragma:
27072
27073 @smallexample
27074 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
27075 @end smallexample
27076
27077 @noindent
27078 This pragma can be placed in the @file{gnat.adc} file in the usual
27079 manner. If we take our original unmodified program and compile it
27080 in the presence of a @file{gnat.adc} containing the above pragma,
27081 then once again, we can compile, bind, link, and execute, obtaining
27082 the expected result. In the presence of this pragma, the compiler does
27083 not trace calls in a task body, that appear after the first @code{accept}
27084 or @code{select} statement, and therefore does not report a potential
27085 circularity in the original program.
27086
27087 The compiler will check to the extent it can that the above
27088 restriction is not violated, but it is not always possible to do a
27089 complete check at compile time, so it is important to use this
27090 pragma only if the stated restriction is in fact met, that is to say
27091 no task receives an entry call before elaboration of all units is completed.
27092
27093 @end itemize
27094
27095 @node Mixing Elaboration Models
27096 @section Mixing Elaboration Models
27097 @noindent
27098 So far, we have assumed that the entire program is either compiled
27099 using the dynamic model or static model, ensuring consistency. It
27100 is possible to mix the two models, but rules have to be followed
27101 if this mixing is done to ensure that elaboration checks are not
27102 omitted.
27103
27104 The basic rule is that @emph{a unit compiled with the static model cannot
27105 be @code{with'ed} by a unit compiled with the dynamic model}. The
27106 reason for this is that in the static model, a unit assumes that
27107 its clients guarantee to use (the equivalent of) pragma
27108 @code{Elaborate_All} so that no elaboration checks are required
27109 in inner subprograms, and this assumption is violated if the
27110 client is compiled with dynamic checks.
27111
27112 The precise rule is as follows. A unit that is compiled with dynamic
27113 checks can only @code{with} a unit that meets at least one of the
27114 following criteria:
27115
27116 @itemize @bullet
27117
27118 @item
27119 The @code{with'ed} unit is itself compiled with dynamic elaboration
27120 checks (that is with the @option{-gnatE} switch.
27121
27122 @item
27123 The @code{with'ed} unit is an internal GNAT implementation unit from
27124 the System, Interfaces, Ada, or GNAT hierarchies.
27125
27126 @item
27127 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
27128
27129 @item
27130 The @code{with'ing} unit (that is the client) has an explicit pragma
27131 @code{Elaborate_All} for the @code{with'ed} unit.
27132
27133 @end itemize
27134
27135 @noindent
27136 If this rule is violated, that is if a unit with dynamic elaboration
27137 checks @code{with's} a unit that does not meet one of the above four
27138 criteria, then the binder (@code{gnatbind}) will issue a warning
27139 similar to that in the following example:
27140
27141 @smallexample
27142 warning: "x.ads" has dynamic elaboration checks and with's
27143 warning:   "y.ads" which has static elaboration checks
27144 @end smallexample
27145
27146 @noindent
27147 These warnings indicate that the rule has been violated, and that as a result
27148 elaboration checks may be missed in the resulting executable file.
27149 This warning may be suppressed using the @option{-ws} binder switch
27150 in the usual manner.
27151
27152 One useful application of this mixing rule is in the case of a subsystem
27153 which does not itself @code{with} units from the remainder of the
27154 application. In this case, the entire subsystem can be compiled with
27155 dynamic checks to resolve a circularity in the subsystem, while
27156 allowing the main application that uses this subsystem to be compiled
27157 using the more reliable default static model.
27158
27159 @node What to Do If the Default Elaboration Behavior Fails
27160 @section What to Do If the Default Elaboration Behavior Fails
27161
27162 @noindent
27163 If the binder cannot find an acceptable order, it outputs detailed
27164 diagnostics. For example:
27165 @smallexample
27166 @group
27167 @iftex
27168 @leftskip=0cm
27169 @end iftex
27170 error: elaboration circularity detected
27171 info:   "proc (body)" must be elaborated before "pack (body)"
27172 info:     reason: Elaborate_All probably needed in unit "pack (body)"
27173 info:     recompile "pack (body)" with -gnatwl
27174 info:                             for full details
27175 info:       "proc (body)"
27176 info:         is needed by its spec:
27177 info:       "proc (spec)"
27178 info:         which is withed by:
27179 info:       "pack (body)"
27180 info:  "pack (body)" must be elaborated before "proc (body)"
27181 info:     reason: pragma Elaborate in unit "proc (body)"
27182 @end group
27183
27184 @end smallexample
27185
27186 @noindent
27187 In this case we have a cycle that the binder cannot break. On the one
27188 hand, there is an explicit pragma Elaborate in @code{proc} for
27189 @code{pack}. This means that the body of @code{pack} must be elaborated
27190 before the body of @code{proc}. On the other hand, there is elaboration
27191 code in @code{pack} that calls a subprogram in @code{proc}. This means
27192 that for maximum safety, there should really be a pragma
27193 Elaborate_All in @code{pack} for @code{proc} which would require that
27194 the body of @code{proc} be elaborated before the body of
27195 @code{pack}. Clearly both requirements cannot be satisfied.
27196 Faced with a circularity of this kind, you have three different options.
27197
27198 @table @asis
27199 @item Fix the program
27200 The most desirable option from the point of view of long-term maintenance
27201 is to rearrange the program so that the elaboration problems are avoided.
27202 One useful technique is to place the elaboration code into separate
27203 child packages. Another is to move some of the initialization code to
27204 explicitly called subprograms, where the program controls the order
27205 of initialization explicitly. Although this is the most desirable option,
27206 it may be impractical and involve too much modification, especially in
27207 the case of complex legacy code.
27208
27209 @item Perform dynamic checks
27210 If the compilations are done using the
27211 @option{-gnatE}
27212 (dynamic elaboration check) switch, then GNAT behaves in a quite different
27213 manner. Dynamic checks are generated for all calls that could possibly result
27214 in raising an exception. With this switch, the compiler does not generate
27215 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
27216 exactly as specified in the @cite{Ada Reference Manual}.
27217 The binder will generate
27218 an executable program that may or may not raise @code{Program_Error}, and then
27219 it is the programmer's job to ensure that it does not raise an exception. Note
27220 that it is important to compile all units with the switch, it cannot be used
27221 selectively.
27222
27223 @item Suppress checks
27224 The drawback of dynamic checks is that they generate a
27225 significant overhead at run time, both in space and time. If you
27226 are absolutely sure that your program cannot raise any elaboration
27227 exceptions, and you still want to use the dynamic elaboration model,
27228 then you can use the configuration pragma
27229 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
27230 example this pragma could be placed in the @file{gnat.adc} file.
27231
27232 @item Suppress checks selectively
27233 When you know that certain calls or instantiations in elaboration code cannot
27234 possibly lead to an elaboration error, and the binder nevertheless complains
27235 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
27236 elaboration circularities, it is possible to remove those warnings locally and
27237 obtain a program that will bind. Clearly this can be unsafe, and it is the
27238 responsibility of the programmer to make sure that the resulting program has no
27239 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
27240 used with different granularity to suppress warnings and break elaboration
27241 circularities:
27242
27243 @itemize @bullet
27244 @item
27245 Place the pragma that names the called subprogram in the declarative part
27246 that contains the call.
27247
27248 @item
27249 Place the pragma in the declarative part, without naming an entity. This
27250 disables warnings on all calls in the corresponding  declarative region.
27251
27252 @item
27253 Place the pragma in the package spec that declares the called subprogram,
27254 and name the subprogram. This disables warnings on all elaboration calls to
27255 that subprogram.
27256
27257 @item
27258 Place the pragma in the package spec that declares the called subprogram,
27259 without naming any entity. This disables warnings on all elaboration calls to
27260 all subprograms declared in this spec.
27261
27262 @item Use Pragma Elaborate
27263 As previously described in section @xref{Treatment of Pragma Elaborate},
27264 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
27265 that no elaboration checks are required on calls to the designated unit.
27266 There may be cases in which the caller knows that no transitive calls
27267 can occur, so that a @code{pragma Elaborate} will be sufficient in a
27268 case where @code{pragma Elaborate_All} would cause a circularity.
27269 @end itemize
27270
27271 @noindent
27272 These five cases are listed in order of decreasing safety, and therefore
27273 require increasing programmer care in their application. Consider the
27274 following program:
27275
27276 @smallexample @c adanocomment
27277 package Pack1 is
27278   function F1 return Integer;
27279   X1 : Integer;
27280 end Pack1;
27281
27282 package Pack2 is
27283   function F2 return Integer;
27284   function Pure (x : integer) return integer;
27285   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
27286   --  pragma Suppress (Elaboration_Check);              -- (4)
27287 end Pack2;
27288
27289 with Pack2;
27290 package body Pack1 is
27291   function F1 return Integer is
27292   begin
27293     return 100;
27294   end F1;
27295   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
27296 begin
27297   declare
27298     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
27299     --  pragma Suppress(Elaboration_Check);             -- (2)
27300   begin
27301     X1 := Pack2.F2 + 1;                --  Elab. call (2)
27302   end;
27303 end Pack1;
27304
27305 with Pack1;
27306 package body Pack2 is
27307   function F2 return Integer is
27308   begin
27309      return Pack1.F1;
27310   end F2;
27311   function Pure (x : integer) return integer is
27312   begin
27313      return x ** 3 - 3 * x;
27314   end;
27315 end Pack2;
27316
27317 with Pack1, Ada.Text_IO;
27318 procedure Proc3 is
27319 begin
27320   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
27321 end Proc3;
27322 @end smallexample
27323 In the absence of any pragmas, an attempt to bind this program produces
27324 the following diagnostics:
27325 @smallexample
27326 @group
27327 @iftex
27328 @leftskip=.5cm
27329 @end iftex
27330 error: elaboration circularity detected
27331 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
27332 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
27333 info:       recompile "pack1 (body)" with -gnatwl for full details
27334 info:          "pack1 (body)"
27335 info:             must be elaborated along with its spec:
27336 info:          "pack1 (spec)"
27337 info:             which is withed by:
27338 info:          "pack2 (body)"
27339 info:             which must be elaborated along with its spec:
27340 info:          "pack2 (spec)"
27341 info:             which is withed by:
27342 info:          "pack1 (body)"
27343 @end group
27344 @end smallexample
27345 The sources of the circularity are the two calls to @code{Pack2.Pure} and
27346 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
27347 F2 is safe, even though F2 calls F1, because the call appears after the
27348 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
27349 remove the warning on the call. It is also possible to use pragma (2)
27350 because there are no other potentially unsafe calls in the block.
27351
27352 @noindent
27353 The call to @code{Pure} is safe because this function does not depend on the
27354 state of @code{Pack2}. Therefore any call to this function is safe, and it
27355 is correct to place pragma (3) in the corresponding package spec.
27356
27357 @noindent
27358 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
27359 warnings on all calls to functions declared therein. Note that this is not
27360 necessarily safe, and requires more detailed examination of the subprogram
27361 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
27362 be already elaborated.
27363 @end table
27364
27365 @noindent
27366 It is hard to generalize on which of these four approaches should be
27367 taken. Obviously if it is possible to fix the program so that the default
27368 treatment works, this is preferable, but this may not always be practical.
27369 It is certainly simple enough to use
27370 @option{-gnatE}
27371 but the danger in this case is that, even if the GNAT binder
27372 finds a correct elaboration order, it may not always do so,
27373 and certainly a binder from another Ada compiler might not. A
27374 combination of testing and analysis (for which the warnings generated
27375 with the
27376 @option{-gnatwl}
27377 switch can be useful) must be used to ensure that the program is free
27378 of errors. One switch that is useful in this testing is the
27379 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
27380 switch for
27381 @code{gnatbind}.
27382 Normally the binder tries to find an order that has the best chance
27383 of avoiding elaboration problems. However, if this switch is used, the binder
27384 plays a devil's advocate role, and tries to choose the order that
27385 has the best chance of failing. If your program works even with this
27386 switch, then it has a better chance of being error free, but this is still
27387 not a guarantee.
27388
27389 For an example of this approach in action, consider the C-tests (executable
27390 tests) from the ACVC suite. If these are compiled and run with the default
27391 treatment, then all but one of them succeed without generating any error
27392 diagnostics from the binder. However, there is one test that fails, and
27393 this is not surprising, because the whole point of this test is to ensure
27394 that the compiler can handle cases where it is impossible to determine
27395 a correct order statically, and it checks that an exception is indeed
27396 raised at run time.
27397
27398 This one test must be compiled and run using the
27399 @option{-gnatE}
27400 switch, and then it passes. Alternatively, the entire suite can
27401 be run using this switch. It is never wrong to run with the dynamic
27402 elaboration switch if your code is correct, and we assume that the
27403 C-tests are indeed correct (it is less efficient, but efficiency is
27404 not a factor in running the ACVC tests.)
27405
27406 @node Elaboration for Access-to-Subprogram Values
27407 @section Elaboration for Access-to-Subprogram Values
27408 @cindex Access-to-subprogram
27409
27410 @noindent
27411 Access-to-subprogram types (introduced in Ada 95) complicate
27412 the handling of elaboration. The trouble is that it becomes
27413 impossible to tell at compile time which procedure
27414 is being called. This means that it is not possible for the binder
27415 to analyze the elaboration requirements in this case.
27416
27417 If at the point at which the access value is created
27418 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
27419 the body of the subprogram is
27420 known to have been elaborated, then the access value is safe, and its use
27421 does not require a check. This may be achieved by appropriate arrangement
27422 of the order of declarations if the subprogram is in the current unit,
27423 or, if the subprogram is in another unit, by using pragma
27424 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
27425 on the referenced unit.
27426
27427 If the referenced body is not known to have been elaborated at the point
27428 the access value is created, then any use of the access value must do a
27429 dynamic check, and this dynamic check will fail and raise a
27430 @code{Program_Error} exception if the body has not been elaborated yet.
27431 GNAT will generate the necessary checks, and in addition, if the
27432 @option{-gnatwl}
27433 switch is set, will generate warnings that such checks are required.
27434
27435 The use of dynamic dispatching for tagged types similarly generates
27436 a requirement for dynamic checks, and premature calls to any primitive
27437 operation of a tagged type before the body of the operation has been
27438 elaborated, will result in the raising of @code{Program_Error}.
27439
27440 @node Summary of Procedures for Elaboration Control
27441 @section Summary of Procedures for Elaboration Control
27442 @cindex Elaboration control
27443
27444 @noindent
27445 First, compile your program with the default options, using none of
27446 the special elaboration control switches. If the binder successfully
27447 binds your program, then you can be confident that, apart from issues
27448 raised by the use of access-to-subprogram types and dynamic dispatching,
27449 the program is free of elaboration errors. If it is important that the
27450 program be portable, then use the
27451 @option{-gnatwl}
27452 switch to generate warnings about missing @code{Elaborate} or
27453 @code{Elaborate_All} pragmas, and supply the missing pragmas.
27454
27455 If the program fails to bind using the default static elaboration
27456 handling, then you can fix the program to eliminate the binder
27457 message, or recompile the entire program with the
27458 @option{-gnatE} switch to generate dynamic elaboration checks,
27459 and, if you are sure there really are no elaboration problems,
27460 use a global pragma @code{Suppress (Elaboration_Check)}.
27461
27462 @node Other Elaboration Order Considerations
27463 @section Other Elaboration Order Considerations
27464 @noindent
27465 This section has been entirely concerned with the issue of finding a valid
27466 elaboration order, as defined by the Ada Reference Manual. In a case
27467 where several elaboration orders are valid, the task is to find one
27468 of the possible valid elaboration orders (and the static model in GNAT
27469 will ensure that this is achieved).
27470
27471 The purpose of the elaboration rules in the Ada Reference Manual is to
27472 make sure that no entity is accessed before it has been elaborated. For
27473 a subprogram, this means that the spec and body must have been elaborated
27474 before the subprogram is called. For an object, this means that the object
27475 must have been elaborated before its value is read or written. A violation
27476 of either of these two requirements is an access before elaboration order,
27477 and this section has been all about avoiding such errors.
27478
27479 In the case where more than one order of elaboration is possible, in the
27480 sense that access before elaboration errors are avoided, then any one of
27481 the orders is ``correct'' in the sense that it meets the requirements of
27482 the Ada Reference Manual, and no such error occurs.
27483
27484 However, it may be the case for a given program, that there are
27485 constraints on the order of elaboration that come not from consideration
27486 of avoiding elaboration errors, but rather from extra-lingual logic
27487 requirements. Consider this example:
27488
27489 @smallexample @c ada
27490 with Init_Constants;
27491 package Constants is
27492    X : Integer := 0;
27493    Y : Integer := 0;
27494 end Constants;
27495
27496 package Init_Constants is
27497    procedure P; -- require a body
27498 end Init_Constants;
27499
27500 with Constants;
27501 package body Init_Constants is
27502    procedure P is begin null; end;
27503 begin
27504    Constants.X := 3;
27505    Constants.Y := 4;
27506 end Init_Constants;
27507
27508 with Constants;
27509 package Calc is
27510    Z : Integer := Constants.X + Constants.Y;
27511 end Calc;
27512
27513 with Calc;
27514 with Text_IO; use Text_IO;
27515 procedure Main is
27516 begin
27517    Put_Line (Calc.Z'Img);
27518 end Main;
27519 @end smallexample
27520
27521 @noindent
27522 In this example, there is more than one valid order of elaboration. For
27523 example both the following are correct orders:
27524
27525 @smallexample
27526 Init_Constants spec
27527 Constants spec
27528 Calc spec
27529 Init_Constants body
27530 Main body
27531
27532   and
27533
27534 Init_Constants spec
27535 Init_Constants body
27536 Constants spec
27537 Calc spec
27538 Main body
27539 @end smallexample
27540
27541 @noindent
27542 There is no language rule to prefer one or the other, both are correct
27543 from an order of elaboration point of view. But the programmatic effects
27544 of the two orders are very different. In the first, the elaboration routine
27545 of @code{Calc} initializes @code{Z} to zero, and then the main program
27546 runs with this value of zero. But in the second order, the elaboration
27547 routine of @code{Calc} runs after the body of Init_Constants has set
27548 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
27549 runs.
27550
27551 One could perhaps by applying pretty clever non-artificial intelligence
27552 to the situation guess that it is more likely that the second order of
27553 elaboration is the one desired, but there is no formal linguistic reason
27554 to prefer one over the other. In fact in this particular case, GNAT will
27555 prefer the second order, because of the rule that bodies are elaborated
27556 as soon as possible, but it's just luck that this is what was wanted
27557 (if indeed the second order was preferred).
27558
27559 If the program cares about the order of elaboration routines in a case like
27560 this, it is important to specify the order required. In this particular
27561 case, that could have been achieved by adding to the spec of Calc:
27562
27563 @smallexample @c ada
27564 pragma Elaborate_All (Constants);
27565 @end smallexample
27566
27567 @noindent
27568 which requires that the body (if any) and spec of @code{Constants},
27569 as well as the body and spec of any unit @code{with}'ed by
27570 @code{Constants} be elaborated before @code{Calc} is elaborated.
27571
27572 Clearly no automatic method can always guess which alternative you require,
27573 and if you are working with legacy code that had constraints of this kind
27574 which were not properly specified by adding @code{Elaborate} or
27575 @code{Elaborate_All} pragmas, then indeed it is possible that two different
27576 compilers can choose different orders.
27577
27578 However, GNAT does attempt to diagnose the common situation where there
27579 are uninitialized variables in the visible part of a package spec, and the
27580 corresponding package body has an elaboration block that directly or
27581 indirectly initialized one or more of these variables. This is the situation
27582 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
27583 a warning that suggests this addition if it detects this situation.
27584
27585 The @code{gnatbind}
27586 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
27587 out problems. This switch causes bodies to be elaborated as late as possible
27588 instead of as early as possible. In the example above, it would have forced
27589 the choice of the first elaboration order. If you get different results
27590 when using this switch, and particularly if one set of results is right,
27591 and one is wrong as far as you are concerned, it shows that you have some
27592 missing @code{Elaborate} pragmas. For the example above, we have the
27593 following output:
27594
27595 @smallexample
27596 gnatmake -f -q main
27597 main
27598  7
27599 gnatmake -f -q main -bargs -p
27600 main
27601  0
27602 @end smallexample
27603
27604 @noindent
27605 It is of course quite unlikely that both these results are correct, so
27606 it is up to you in a case like this to investigate the source of the
27607 difference, by looking at the two elaboration orders that are chosen,
27608 and figuring out which is correct, and then adding the necessary
27609 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
27610
27611
27612
27613 @c *******************************
27614 @node Conditional Compilation
27615 @appendix Conditional Compilation
27616 @c *******************************
27617 @cindex Conditional compilation
27618
27619 @noindent
27620 It is often necessary to arrange for a single source program
27621 to serve multiple purposes, where it is compiled in different
27622 ways to achieve these different goals. Some examples of the
27623 need for this feature are
27624
27625 @itemize @bullet
27626 @item  Adapting a program to a different hardware environment
27627 @item  Adapting a program to a different target architecture
27628 @item  Turning debugging features on and off
27629 @item  Arranging for a program to compile with different compilers
27630 @end itemize
27631
27632 @noindent
27633 In C, or C++, the typical approach would be to use the preprocessor
27634 that is defined as part of the language. The Ada language does not
27635 contain such a feature. This is not an oversight, but rather a very
27636 deliberate design decision, based on the experience that overuse of
27637 the preprocessing features in C and C++ can result in programs that
27638 are extremely difficult to maintain. For example, if we have ten
27639 switches that can be on or off, this means that there are a thousand
27640 separate programs, any one of which might not even be syntactically
27641 correct, and even if syntactically correct, the resulting program
27642 might not work correctly. Testing all combinations can quickly become
27643 impossible.
27644
27645 Nevertheless, the need to tailor programs certainly exists, and in
27646 this Appendix we will discuss how this can
27647 be achieved using Ada in general, and GNAT in particular.
27648
27649 @menu
27650 * Use of Boolean Constants::
27651 * Debugging - A Special Case::
27652 * Conditionalizing Declarations::
27653 * Use of Alternative Implementations::
27654 * Preprocessing::
27655 @end menu
27656
27657 @node Use of Boolean Constants
27658 @section Use of Boolean Constants
27659
27660 @noindent
27661 In the case where the difference is simply which code
27662 sequence is executed, the cleanest solution is to use Boolean
27663 constants to control which code is executed.
27664
27665 @smallexample @c ada
27666 @group
27667 FP_Initialize_Required : constant Boolean := True;
27668 @dots{}
27669 if FP_Initialize_Required then
27670 @dots{}
27671 end if;
27672 @end group
27673 @end smallexample
27674
27675 @noindent
27676 Not only will the code inside the @code{if} statement not be executed if
27677 the constant Boolean is @code{False}, but it will also be completely
27678 deleted from the program.
27679 However, the code is only deleted after the @code{if} statement
27680 has been checked for syntactic and semantic correctness.
27681 (In contrast, with preprocessors the code is deleted before the
27682 compiler ever gets to see it, so it is not checked until the switch
27683 is turned on.)
27684 @cindex Preprocessors (contrasted with conditional compilation)
27685
27686 Typically the Boolean constants will be in a separate package,
27687 something like:
27688
27689 @smallexample @c ada
27690 @group
27691 package Config is
27692    FP_Initialize_Required : constant Boolean := True;
27693    Reset_Available        : constant Boolean := False;
27694    @dots{}
27695 end Config;
27696 @end group
27697 @end smallexample
27698
27699 @noindent
27700 The @code{Config} package exists in multiple forms for the various targets,
27701 with an appropriate script selecting the version of @code{Config} needed.
27702 Then any other unit requiring conditional compilation can do a @code{with}
27703 of @code{Config} to make the constants visible.
27704
27705
27706 @node Debugging - A Special Case
27707 @section Debugging - A Special Case
27708
27709 @noindent
27710 A common use of conditional code is to execute statements (for example
27711 dynamic checks, or output of intermediate results) under control of a
27712 debug switch, so that the debugging behavior can be turned on and off.
27713 This can be done using a Boolean constant to control whether the code
27714 is active:
27715
27716 @smallexample @c ada
27717 @group
27718 if Debugging then
27719    Put_Line ("got to the first stage!");
27720 end if;
27721 @end group
27722 @end smallexample
27723
27724 @noindent
27725 or
27726
27727 @smallexample @c ada
27728 @group
27729 if Debugging and then Temperature > 999.0 then
27730    raise Temperature_Crazy;
27731 end if;
27732 @end group
27733 @end smallexample
27734
27735 @noindent
27736 Since this is a common case, there are special features to deal with
27737 this in a convenient manner. For the case of tests, Ada 2005 has added
27738 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
27739 @cindex pragma @code{Assert}
27740 on the @code{Assert} pragma that has always been available in GNAT, so this
27741 feature may be used with GNAT even if you are not using Ada 2005 features.
27742 The use of pragma @code{Assert} is described in the
27743 @cite{GNAT Reference Manual}, but as an example, the last test could be written:
27744
27745 @smallexample @c ada
27746 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
27747 @end smallexample
27748
27749 @noindent
27750 or simply
27751
27752 @smallexample @c ada
27753 pragma Assert (Temperature <= 999.0);
27754 @end smallexample
27755
27756 @noindent
27757 In both cases, if assertions are active and the temperature is excessive,
27758 the exception @code{Assert_Failure} will be raised, with the given string in
27759 the first case or a string indicating the location of the pragma in the second
27760 case used as the exception message.
27761
27762 You can turn assertions on and off by using the @code{Assertion_Policy}
27763 pragma.
27764 @cindex pragma @code{Assertion_Policy}
27765 This is an Ada 2005 pragma which is implemented in all modes by
27766 GNAT, but only in the latest versions of GNAT which include Ada 2005
27767 capability. Alternatively, you can use the @option{-gnata} switch
27768 @cindex @option{-gnata} switch
27769 to enable assertions from the command line (this is recognized by all versions
27770 of GNAT).
27771
27772 For the example above with the @code{Put_Line}, the GNAT-specific pragma
27773 @code{Debug} can be used:
27774 @cindex pragma @code{Debug}
27775
27776 @smallexample @c ada
27777 pragma Debug (Put_Line ("got to the first stage!"));
27778 @end smallexample
27779
27780 @noindent
27781 If debug pragmas are enabled, the argument, which must be of the form of
27782 a procedure call, is executed (in this case, @code{Put_Line} will be called).
27783 Only one call can be present, but of course a special debugging procedure
27784 containing any code you like can be included in the program and then
27785 called in a pragma @code{Debug} argument as needed.
27786
27787 One advantage of pragma @code{Debug} over the @code{if Debugging then}
27788 construct is that pragma @code{Debug} can appear in declarative contexts,
27789 such as at the very beginning of a procedure, before local declarations have
27790 been elaborated.
27791
27792 Debug pragmas are enabled using either the @option{-gnata} switch that also
27793 controls assertions, or with a separate Debug_Policy pragma.
27794 @cindex pragma @code{Debug_Policy}
27795 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
27796 in Ada 95 and Ada 83 programs as well), and is analogous to
27797 pragma @code{Assertion_Policy} to control assertions.
27798
27799 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
27800 and thus they can appear in @file{gnat.adc} if you are not using a
27801 project file, or in the file designated to contain configuration pragmas
27802 in a project file.
27803 They then apply to all subsequent compilations. In practice the use of
27804 the @option{-gnata} switch is often the most convenient method of controlling
27805 the status of these pragmas.
27806
27807 Note that a pragma is not a statement, so in contexts where a statement
27808 sequence is required, you can't just write a pragma on its own. You have
27809 to add a @code{null} statement.
27810
27811 @smallexample @c ada
27812 @group
27813 if @dots{} then
27814    @dots{} -- some statements
27815 else
27816    pragma Assert (Num_Cases < 10);
27817    null;
27818 end if;
27819 @end group
27820 @end smallexample
27821
27822
27823 @node Conditionalizing Declarations
27824 @section Conditionalizing Declarations
27825
27826 @noindent
27827 In some cases, it may be necessary to conditionalize declarations to meet
27828 different requirements. For example we might want a bit string whose length
27829 is set to meet some hardware message requirement.
27830
27831 In some cases, it may be possible to do this using declare blocks controlled
27832 by conditional constants:
27833
27834 @smallexample @c ada
27835 @group
27836 if Small_Machine then
27837    declare
27838       X : Bit_String (1 .. 10);
27839    begin
27840       @dots{}
27841    end;
27842 else
27843    declare
27844       X : Large_Bit_String (1 .. 1000);
27845    begin
27846       @dots{}
27847    end;
27848 end if;
27849 @end group
27850 @end smallexample
27851
27852 @noindent
27853 Note that in this approach, both declarations are analyzed by the
27854 compiler so this can only be used where both declarations are legal,
27855 even though one of them will not be used.
27856
27857 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
27858 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
27859 that are parameterized by these constants. For example
27860
27861 @smallexample @c ada
27862 @group
27863 for Rec use
27864   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
27865 end record;
27866 @end group
27867 @end smallexample
27868
27869 @noindent
27870 If @code{Bits_Per_Word} is set to 32, this generates either
27871
27872 @smallexample @c ada
27873 @group
27874 for Rec use
27875   Field1 at 0 range 0 .. 32;
27876 end record;
27877 @end group
27878 @end smallexample
27879
27880 @noindent
27881 for the big endian case, or
27882
27883 @smallexample @c ada
27884 @group
27885 for Rec use record
27886   Field1 at 0 range 10 .. 32;
27887 end record;
27888 @end group
27889 @end smallexample
27890
27891 @noindent
27892 for the little endian case. Since a powerful subset of Ada expression
27893 notation is usable for creating static constants, clever use of this
27894 feature can often solve quite difficult problems in conditionalizing
27895 compilation (note incidentally that in Ada 95, the little endian
27896 constant was introduced as @code{System.Default_Bit_Order}, so you do not
27897 need to define this one yourself).
27898
27899
27900 @node Use of Alternative Implementations
27901 @section Use of Alternative Implementations
27902
27903 @noindent
27904 In some cases, none of the approaches described above are adequate. This
27905 can occur for example if the set of declarations required is radically
27906 different for two different configurations.
27907
27908 In this situation, the official Ada way of dealing with conditionalizing
27909 such code is to write separate units for the different cases. As long as
27910 this does not result in excessive duplication of code, this can be done
27911 without creating maintenance problems. The approach is to share common
27912 code as far as possible, and then isolate the code and declarations
27913 that are different. Subunits are often a convenient method for breaking
27914 out a piece of a unit that is to be conditionalized, with separate files
27915 for different versions of the subunit for different targets, where the
27916 build script selects the right one to give to the compiler.
27917 @cindex Subunits (and conditional compilation)
27918
27919 As an example, consider a situation where a new feature in Ada 2005
27920 allows something to be done in a really nice way. But your code must be able
27921 to compile with an Ada 95 compiler. Conceptually you want to say:
27922
27923 @smallexample @c ada
27924 @group
27925 if Ada_2005 then
27926    @dots{} neat Ada 2005 code
27927 else
27928    @dots{} not quite as neat Ada 95 code
27929 end if;
27930 @end group
27931 @end smallexample
27932
27933 @noindent
27934 where @code{Ada_2005} is a Boolean constant.
27935
27936 But this won't work when @code{Ada_2005} is set to @code{False},
27937 since the @code{then} clause will be illegal for an Ada 95 compiler.
27938 (Recall that although such unreachable code would eventually be deleted
27939 by the compiler, it still needs to be legal.  If it uses features
27940 introduced in Ada 2005, it will be illegal in Ada 95.)
27941
27942 So instead we write
27943
27944 @smallexample @c ada
27945 procedure Insert is separate;
27946 @end smallexample
27947
27948 @noindent
27949 Then we have two files for the subunit @code{Insert}, with the two sets of
27950 code.
27951 If the package containing this is called @code{File_Queries}, then we might
27952 have two files
27953
27954 @itemize @bullet
27955 @item    @file{file_queries-insert-2005.adb}
27956 @item    @file{file_queries-insert-95.adb}
27957 @end itemize
27958
27959 @noindent
27960 and the build script renames the appropriate file to
27961
27962 @smallexample
27963 file_queries-insert.adb
27964 @end smallexample
27965
27966 @noindent
27967 and then carries out the compilation.
27968
27969 This can also be done with project files' naming schemes. For example:
27970
27971 @smallexample @c project
27972 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
27973 @end smallexample
27974
27975 @noindent
27976 Note also that with project files it is desirable to use a different extension
27977 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
27978 conflict may arise through another commonly used feature: to declare as part
27979 of the project a set of directories containing all the sources obeying the
27980 default naming scheme.
27981
27982 The use of alternative units is certainly feasible in all situations,
27983 and for example the Ada part of the GNAT run-time is conditionalized
27984 based on the target architecture using this approach. As a specific example,
27985 consider the implementation of the AST feature in VMS. There is one
27986 spec:
27987
27988 @smallexample
27989 s-asthan.ads
27990 @end smallexample
27991
27992 @noindent
27993 which is the same for all architectures, and three bodies:
27994
27995 @table @file
27996 @item    s-asthan.adb
27997 used for all non-VMS operating systems
27998 @item    s-asthan-vms-alpha.adb
27999 used for VMS on the Alpha
28000 @item    s-asthan-vms-ia64.adb
28001 used for VMS on the ia64
28002 @end table
28003
28004 @noindent
28005 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
28006 this operating system feature is not available, and the two remaining
28007 versions interface with the corresponding versions of VMS to provide
28008 VMS-compatible AST handling. The GNAT build script knows the architecture
28009 and operating system, and automatically selects the right version,
28010 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
28011
28012 Another style for arranging alternative implementations is through Ada's
28013 access-to-subprogram facility.
28014 In case some functionality is to be conditionally included,
28015 you can declare an access-to-procedure variable @code{Ref} that is initialized
28016 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
28017 when appropriate.
28018 In some library package, set @code{Ref} to @code{Proc'Access} for some
28019 procedure @code{Proc} that performs the relevant processing.
28020 The initialization only occurs if the library package is included in the
28021 program.
28022 The same idea can also be implemented using tagged types and dispatching
28023 calls.
28024
28025
28026 @node Preprocessing
28027 @section Preprocessing
28028 @cindex Preprocessing
28029
28030 @noindent
28031 Although it is quite possible to conditionalize code without the use of
28032 C-style preprocessing, as described earlier in this section, it is
28033 nevertheless convenient in some cases to use the C approach. Moreover,
28034 older Ada compilers have often provided some preprocessing capability,
28035 so legacy code may depend on this approach, even though it is not
28036 standard.
28037
28038 To accommodate such use, GNAT provides a preprocessor (modeled to a large
28039 extent on the various preprocessors that have been used
28040 with legacy code on other compilers, to enable easier transition).
28041
28042 The preprocessor may be used in two separate modes. It can be used quite
28043 separately from the compiler, to generate a separate output source file
28044 that is then fed to the compiler as a separate step. This is the
28045 @code{gnatprep} utility, whose use is fully described in
28046 @ref{Preprocessing Using gnatprep}.
28047 @cindex @code{gnatprep}
28048
28049 The preprocessing language allows such constructs as
28050
28051 @smallexample
28052 @group
28053 #if DEBUG or PRIORITY > 4 then
28054    bunch of declarations
28055 #else
28056    completely different bunch of declarations
28057 #end if;
28058 @end group
28059 @end smallexample
28060
28061 @noindent
28062 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
28063 defined either on the command line or in a separate file.
28064
28065 The other way of running the preprocessor is even closer to the C style and
28066 often more convenient. In this approach the preprocessing is integrated into
28067 the compilation process. The compiler is fed the preprocessor input which
28068 includes @code{#if} lines etc, and then the compiler carries out the
28069 preprocessing internally and processes the resulting output.
28070 For more details on this approach, see @ref{Integrated Preprocessing}.
28071
28072
28073 @c *******************************
28074 @node Inline Assembler
28075 @appendix Inline Assembler
28076 @c *******************************
28077
28078 @noindent
28079 If you need to write low-level software that interacts directly
28080 with the hardware, Ada provides two ways to incorporate assembly
28081 language code into your program.  First, you can import and invoke
28082 external routines written in assembly language, an Ada feature fully
28083 supported by GNAT@.  However, for small sections of code it may be simpler
28084 or more efficient to include assembly language statements directly
28085 in your Ada source program, using the facilities of the implementation-defined
28086 package @code{System.Machine_Code}, which incorporates the gcc
28087 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
28088 including the following:
28089
28090 @itemize @bullet
28091 @item No need to use non-Ada tools
28092 @item Consistent interface over different targets
28093 @item Automatic usage of the proper calling conventions
28094 @item Access to Ada constants and variables
28095 @item Definition of intrinsic routines
28096 @item Possibility of inlining a subprogram comprising assembler code
28097 @item Code optimizer can take Inline Assembler code into account
28098 @end itemize
28099
28100 This chapter presents a series of examples to show you how to use
28101 the Inline Assembler.  Although it focuses on the Intel x86,
28102 the general approach applies also to other processors.
28103 It is assumed that you are familiar with Ada
28104 and with assembly language programming.
28105
28106 @menu
28107 * Basic Assembler Syntax::
28108 * A Simple Example of Inline Assembler::
28109 * Output Variables in Inline Assembler::
28110 * Input Variables in Inline Assembler::
28111 * Inlining Inline Assembler Code::
28112 * Other Asm Functionality::
28113 @end menu
28114
28115 @c ---------------------------------------------------------------------------
28116 @node Basic Assembler Syntax
28117 @section Basic Assembler Syntax
28118
28119 @noindent
28120 The assembler used by GNAT and gcc is based not on the Intel assembly
28121 language, but rather on a language that descends from the AT&T Unix
28122 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
28123 The following table summarizes the main features of @emph{as} syntax
28124 and points out the differences from the Intel conventions.
28125 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
28126 pre-processor) documentation for further information.
28127
28128 @table @asis
28129 @item Register names
28130 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
28131 @*
28132 Intel: No extra punctuation; for example @code{eax}
28133
28134 @item Immediate operand
28135 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
28136 @*
28137 Intel: No extra punctuation; for example @code{4}
28138
28139 @item Address
28140 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
28141 @*
28142 Intel: No extra punctuation; for example @code{loc}
28143
28144 @item Memory contents
28145 gcc / @emph{as}: No extra punctuation; for example @code{loc}
28146 @*
28147 Intel: Square brackets; for example @code{[loc]}
28148
28149 @item Register contents
28150 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
28151 @*
28152 Intel: Square brackets; for example @code{[eax]}
28153
28154 @item Hexadecimal numbers
28155 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
28156 @*
28157 Intel: Trailing ``h''; for example @code{A0h}
28158
28159 @item Operand size
28160 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
28161 a 16-bit word
28162 @*
28163 Intel: Implicit, deduced by assembler; for example @code{mov}
28164
28165 @item Instruction repetition
28166 gcc / @emph{as}: Split into two lines; for example
28167 @*
28168 @code{rep}
28169 @*
28170 @code{stosl}
28171 @*
28172 Intel: Keep on one line; for example @code{rep stosl}
28173
28174 @item Order of operands
28175 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
28176 @*
28177 Intel: Destination first; for example @code{mov eax, 4}
28178 @end table
28179
28180 @c ---------------------------------------------------------------------------
28181 @node A Simple Example of Inline Assembler
28182 @section A Simple Example of Inline Assembler
28183
28184 @noindent
28185 The following example will generate a single assembly language statement,
28186 @code{nop}, which does nothing.  Despite its lack of run-time effect,
28187 the example will be useful in illustrating the basics of
28188 the Inline Assembler facility.
28189
28190 @smallexample @c ada
28191 @group
28192 with System.Machine_Code; use System.Machine_Code;
28193 procedure Nothing is
28194 begin
28195    Asm ("nop");
28196 end Nothing;
28197 @end group
28198 @end smallexample
28199
28200 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
28201 here it takes one parameter, a @emph{template string} that must be a static
28202 expression and that will form the generated instruction.
28203 @code{Asm} may be regarded as a compile-time procedure that parses
28204 the template string and additional parameters (none here),
28205 from which it generates a sequence of assembly language instructions.
28206
28207 The examples in this chapter will illustrate several of the forms
28208 for invoking @code{Asm}; a complete specification of the syntax
28209 is found in the @cite{GNAT Reference Manual}.
28210
28211 Under the standard GNAT conventions, the @code{Nothing} procedure
28212 should be in a file named @file{nothing.adb}.
28213 You can build the executable in the usual way:
28214 @smallexample
28215 gnatmake nothing
28216 @end smallexample
28217 However, the interesting aspect of this example is not its run-time behavior
28218 but rather the generated assembly code.
28219 To see this output, invoke the compiler as follows:
28220 @smallexample
28221    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
28222 @end smallexample
28223 where the options are:
28224
28225 @table @code
28226 @item -c
28227 compile only (no bind or link)
28228 @item -S
28229 generate assembler listing
28230 @item -fomit-frame-pointer
28231 do not set up separate stack frames
28232 @item -gnatp
28233 do not add runtime checks
28234 @end table
28235
28236 This gives a human-readable assembler version of the code. The resulting
28237 file will have the same name as the Ada source file, but with a @code{.s}
28238 extension. In our example, the file @file{nothing.s} has the following
28239 contents:
28240
28241 @smallexample
28242 @group
28243 .file "nothing.adb"
28244 gcc2_compiled.:
28245 ___gnu_compiled_ada:
28246 .text
28247    .align 4
28248 .globl __ada_nothing
28249 __ada_nothing:
28250 #APP
28251    nop
28252 #NO_APP
28253    jmp L1
28254    .align 2,0x90
28255 L1:
28256    ret
28257 @end group
28258 @end smallexample
28259
28260 The assembly code you included is clearly indicated by
28261 the compiler, between the @code{#APP} and @code{#NO_APP}
28262 delimiters. The character before the 'APP' and 'NOAPP'
28263 can differ on different targets. For example, GNU/Linux uses '#APP' while
28264 on NT you will see '/APP'.
28265
28266 If you make a mistake in your assembler code (such as using the
28267 wrong size modifier, or using a wrong operand for the instruction) GNAT
28268 will report this error in a temporary file, which will be deleted when
28269 the compilation is finished.  Generating an assembler file will help
28270 in such cases, since you can assemble this file separately using the
28271 @emph{as} assembler that comes with gcc.
28272
28273 Assembling the file using the command
28274
28275 @smallexample
28276 as @file{nothing.s}
28277 @end smallexample
28278 @noindent
28279 will give you error messages whose lines correspond to the assembler
28280 input file, so you can easily find and correct any mistakes you made.
28281 If there are no errors, @emph{as} will generate an object file
28282 @file{nothing.out}.
28283
28284 @c ---------------------------------------------------------------------------
28285 @node Output Variables in Inline Assembler
28286 @section Output Variables in Inline Assembler
28287
28288 @noindent
28289 The examples in this section, showing how to access the processor flags,
28290 illustrate how to specify the destination operands for assembly language
28291 statements.
28292
28293 @smallexample @c ada
28294 @group
28295 with Interfaces; use Interfaces;
28296 with Ada.Text_IO; use Ada.Text_IO;
28297 with System.Machine_Code; use System.Machine_Code;
28298 procedure Get_Flags is
28299    Flags : Unsigned_32;
28300    use ASCII;
28301 begin
28302    Asm ("pushfl"          & LF & HT & -- push flags on stack
28303         "popl %%eax"      & LF & HT & -- load eax with flags
28304         "movl %%eax, %0",             -- store flags in variable
28305         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28306    Put_Line ("Flags register:" & Flags'Img);
28307 end Get_Flags;
28308 @end group
28309 @end smallexample
28310
28311 In order to have a nicely aligned assembly listing, we have separated
28312 multiple assembler statements in the Asm template string with linefeed
28313 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
28314 The resulting section of the assembly output file is:
28315
28316 @smallexample
28317 @group
28318 #APP
28319    pushfl
28320    popl %eax
28321    movl %eax, -40(%ebp)
28322 #NO_APP
28323 @end group
28324 @end smallexample
28325
28326 It would have been legal to write the Asm invocation as:
28327
28328 @smallexample
28329 Asm ("pushfl popl %%eax movl %%eax, %0")
28330 @end smallexample
28331
28332 but in the generated assembler file, this would come out as:
28333
28334 @smallexample
28335 #APP
28336    pushfl popl %eax movl %eax, -40(%ebp)
28337 #NO_APP
28338 @end smallexample
28339
28340 which is not so convenient for the human reader.
28341
28342 We use Ada comments
28343 at the end of each line to explain what the assembler instructions
28344 actually do.  This is a useful convention.
28345
28346 When writing Inline Assembler instructions, you need to precede each register
28347 and variable name with a percent sign.  Since the assembler already requires
28348 a percent sign at the beginning of a register name, you need two consecutive
28349 percent signs for such names in the Asm template string, thus @code{%%eax}.
28350 In the generated assembly code, one of the percent signs will be stripped off.
28351
28352 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
28353 variables: operands you later define using @code{Input} or @code{Output}
28354 parameters to @code{Asm}.
28355 An output variable is illustrated in
28356 the third statement in the Asm template string:
28357 @smallexample
28358 movl %%eax, %0
28359 @end smallexample
28360 The intent is to store the contents of the eax register in a variable that can
28361 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
28362 necessarily work, since the compiler might optimize by using a register
28363 to hold Flags, and the expansion of the @code{movl} instruction would not be
28364 aware of this optimization.  The solution is not to store the result directly
28365 but rather to advise the compiler to choose the correct operand form;
28366 that is the purpose of the @code{%0} output variable.
28367
28368 Information about the output variable is supplied in the @code{Outputs}
28369 parameter to @code{Asm}:
28370 @smallexample
28371 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28372 @end smallexample
28373
28374 The output is defined by the @code{Asm_Output} attribute of the target type;
28375 the general format is
28376 @smallexample
28377 Type'Asm_Output (constraint_string, variable_name)
28378 @end smallexample
28379
28380 The constraint string directs the compiler how
28381 to store/access the associated variable.  In the example
28382 @smallexample
28383 Unsigned_32'Asm_Output ("=m", Flags);
28384 @end smallexample
28385 the @code{"m"} (memory) constraint tells the compiler that the variable
28386 @code{Flags} should be stored in a memory variable, thus preventing
28387 the optimizer from keeping it in a register.  In contrast,
28388 @smallexample
28389 Unsigned_32'Asm_Output ("=r", Flags);
28390 @end smallexample
28391 uses the @code{"r"} (register) constraint, telling the compiler to
28392 store the variable in a register.
28393
28394 If the constraint is preceded by the equal character (@strong{=}), it tells
28395 the compiler that the variable will be used to store data into it.
28396
28397 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
28398 allowing the optimizer to choose whatever it deems best.
28399
28400 There are a fairly large number of constraints, but the ones that are
28401 most useful (for the Intel x86 processor) are the following:
28402
28403 @table @code
28404 @item =
28405 output constraint
28406 @item g
28407 global (i.e.@: can be stored anywhere)
28408 @item m
28409 in memory
28410 @item I
28411 a constant
28412 @item a
28413 use eax
28414 @item b
28415 use ebx
28416 @item c
28417 use ecx
28418 @item d
28419 use edx
28420 @item S
28421 use esi
28422 @item D
28423 use edi
28424 @item r
28425 use one of eax, ebx, ecx or edx
28426 @item q
28427 use one of eax, ebx, ecx, edx, esi or edi
28428 @end table
28429
28430 The full set of constraints is described in the gcc and @emph{as}
28431 documentation; note that it is possible to combine certain constraints
28432 in one constraint string.
28433
28434 You specify the association of an output variable with an assembler operand
28435 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
28436 integer.  Thus in
28437 @smallexample @c ada
28438 @group
28439 Asm ("pushfl"          & LF & HT & -- push flags on stack
28440      "popl %%eax"      & LF & HT & -- load eax with flags
28441      "movl %%eax, %0",             -- store flags in variable
28442      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28443 @end group
28444 @end smallexample
28445 @noindent
28446 @code{%0} will be replaced in the expanded code by the appropriate operand,
28447 whatever
28448 the compiler decided for the @code{Flags} variable.
28449
28450 In general, you may have any number of output variables:
28451 @itemize @bullet
28452 @item
28453 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
28454 @item
28455 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
28456 of @code{Asm_Output} attributes
28457 @end itemize
28458
28459 For example:
28460 @smallexample @c ada
28461 @group
28462 Asm ("movl %%eax, %0" & LF & HT &
28463      "movl %%ebx, %1" & LF & HT &
28464      "movl %%ecx, %2",
28465      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
28466                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
28467                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
28468 @end group
28469 @end smallexample
28470 @noindent
28471 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28472 in the Ada program.
28473
28474 As a variation on the @code{Get_Flags} example, we can use the constraints
28475 string to direct the compiler to store the eax register into the @code{Flags}
28476 variable, instead of including the store instruction explicitly in the
28477 @code{Asm} template string:
28478
28479 @smallexample @c ada
28480 @group
28481 with Interfaces; use Interfaces;
28482 with Ada.Text_IO; use Ada.Text_IO;
28483 with System.Machine_Code; use System.Machine_Code;
28484 procedure Get_Flags_2 is
28485    Flags : Unsigned_32;
28486    use ASCII;
28487 begin
28488    Asm ("pushfl"      & LF & HT & -- push flags on stack
28489         "popl %%eax",             -- save flags in eax
28490         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28491    Put_Line ("Flags register:" & Flags'Img);
28492 end Get_Flags_2;
28493 @end group
28494 @end smallexample
28495
28496 @noindent
28497 The @code{"a"} constraint tells the compiler that the @code{Flags}
28498 variable will come from the eax register. Here is the resulting code:
28499
28500 @smallexample
28501 @group
28502 #APP
28503    pushfl
28504    popl %eax
28505 #NO_APP
28506    movl %eax,-40(%ebp)
28507 @end group
28508 @end smallexample
28509
28510 @noindent
28511 The compiler generated the store of eax into Flags after
28512 expanding the assembler code.
28513
28514 Actually, there was no need to pop the flags into the eax register;
28515 more simply, we could just pop the flags directly into the program variable:
28516
28517 @smallexample @c ada
28518 @group
28519 with Interfaces; use Interfaces;
28520 with Ada.Text_IO; use Ada.Text_IO;
28521 with System.Machine_Code; use System.Machine_Code;
28522 procedure Get_Flags_3 is
28523    Flags : Unsigned_32;
28524    use ASCII;
28525 begin
28526    Asm ("pushfl"  & LF & HT & -- push flags on stack
28527         "pop %0",             -- save flags in Flags
28528         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28529    Put_Line ("Flags register:" & Flags'Img);
28530 end Get_Flags_3;
28531 @end group
28532 @end smallexample
28533
28534 @c ---------------------------------------------------------------------------
28535 @node Input Variables in Inline Assembler
28536 @section Input Variables in Inline Assembler
28537
28538 @noindent
28539 The example in this section illustrates how to specify the source operands
28540 for assembly language statements.
28541 The program simply increments its input value by 1:
28542
28543 @smallexample @c ada
28544 @group
28545 with Interfaces; use Interfaces;
28546 with Ada.Text_IO; use Ada.Text_IO;
28547 with System.Machine_Code; use System.Machine_Code;
28548 procedure Increment is
28549
28550    function Incr (Value : Unsigned_32) return Unsigned_32 is
28551       Result : Unsigned_32;
28552    begin
28553       Asm ("incl %0",
28554            Inputs  => Unsigned_32'Asm_Input ("a", Value),
28555            Outputs => Unsigned_32'Asm_Output ("=a", Result));
28556       return Result;
28557    end Incr;
28558
28559    Value : Unsigned_32;
28560
28561 begin
28562    Value := 5;
28563    Put_Line ("Value before is" & Value'Img);
28564    Value := Incr (Value);
28565    Put_Line ("Value after is" & Value'Img);
28566 end Increment;
28567 @end group
28568 @end smallexample
28569
28570 The @code{Outputs} parameter to @code{Asm} specifies
28571 that the result will be in the eax register and that it is to be stored
28572 in the @code{Result} variable.
28573
28574 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28575 but with an @code{Asm_Input} attribute.
28576 The @code{"="} constraint, indicating an output value, is not present.
28577
28578 You can have multiple input variables, in the same way that you can have more
28579 than one output variable.
28580
28581 The parameter count (%0, %1) etc, now starts at the first input
28582 statement, and continues with the output statements.
28583 When both parameters use the same variable, the
28584 compiler will treat them as the same %n operand, which is the case here.
28585
28586 Just as the @code{Outputs} parameter causes the register to be stored into the
28587 target variable after execution of the assembler statements, so does the
28588 @code{Inputs} parameter cause its variable to be loaded into the register
28589 before execution of the assembler statements.
28590
28591 Thus the effect of the @code{Asm} invocation is:
28592 @enumerate
28593 @item load the 32-bit value of @code{Value} into eax
28594 @item execute the @code{incl %eax} instruction
28595 @item store the contents of eax into the @code{Result} variable
28596 @end enumerate
28597
28598 The resulting assembler file (with @option{-O2} optimization) contains:
28599 @smallexample
28600 @group
28601 _increment__incr.1:
28602    subl $4,%esp
28603    movl 8(%esp),%eax
28604 #APP
28605    incl %eax
28606 #NO_APP
28607    movl %eax,%edx
28608    movl %ecx,(%esp)
28609    addl $4,%esp
28610    ret
28611 @end group
28612 @end smallexample
28613
28614 @c ---------------------------------------------------------------------------
28615 @node Inlining Inline Assembler Code
28616 @section Inlining Inline Assembler Code
28617
28618 @noindent
28619 For a short subprogram such as the @code{Incr} function in the previous
28620 section, the overhead of the call and return (creating / deleting the stack
28621 frame) can be significant, compared to the amount of code in the subprogram
28622 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
28623 which directs the compiler to expand invocations of the subprogram at the
28624 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28625 Here is the resulting program:
28626
28627 @smallexample @c ada
28628 @group
28629 with Interfaces; use Interfaces;
28630 with Ada.Text_IO; use Ada.Text_IO;
28631 with System.Machine_Code; use System.Machine_Code;
28632 procedure Increment_2 is
28633
28634    function Incr (Value : Unsigned_32) return Unsigned_32 is
28635       Result : Unsigned_32;
28636    begin
28637       Asm ("incl %0",
28638            Inputs  => Unsigned_32'Asm_Input ("a", Value),
28639            Outputs => Unsigned_32'Asm_Output ("=a", Result));
28640       return Result;
28641    end Incr;
28642    pragma Inline (Increment);
28643
28644    Value : Unsigned_32;
28645
28646 begin
28647    Value := 5;
28648    Put_Line ("Value before is" & Value'Img);
28649    Value := Increment (Value);
28650    Put_Line ("Value after is" & Value'Img);
28651 end Increment_2;
28652 @end group
28653 @end smallexample
28654
28655 Compile the program with both optimization (@option{-O2}) and inlining
28656 enabled (@option{-gnatpn} instead of @option{-gnatp}).
28657
28658 The @code{Incr} function is still compiled as usual, but at the
28659 point in @code{Increment} where our function used to be called:
28660
28661 @smallexample
28662 @group
28663 pushl %edi
28664 call _increment__incr.1
28665 @end group
28666 @end smallexample
28667
28668 @noindent
28669 the code for the function body directly appears:
28670
28671 @smallexample
28672 @group
28673 movl %esi,%eax
28674 #APP
28675    incl %eax
28676 #NO_APP
28677    movl %eax,%edx
28678 @end group
28679 @end smallexample
28680
28681 @noindent
28682 thus saving the overhead of stack frame setup and an out-of-line call.
28683
28684 @c ---------------------------------------------------------------------------
28685 @node Other Asm Functionality
28686 @section Other @code{Asm} Functionality
28687
28688 @noindent
28689 This section describes two important parameters to the @code{Asm}
28690 procedure: @code{Clobber}, which identifies register usage;
28691 and @code{Volatile}, which inhibits unwanted optimizations.
28692
28693 @menu
28694 * The Clobber Parameter::
28695 * The Volatile Parameter::
28696 @end menu
28697
28698 @c ---------------------------------------------------------------------------
28699 @node The Clobber Parameter
28700 @subsection The @code{Clobber} Parameter
28701
28702 @noindent
28703 One of the dangers of intermixing assembly language and a compiled language
28704 such as Ada is that the compiler needs to be aware of which registers are
28705 being used by the assembly code.  In some cases, such as the earlier examples,
28706 the constraint string is sufficient to indicate register usage (e.g.,
28707 @code{"a"} for
28708 the eax register).  But more generally, the compiler needs an explicit
28709 identification of the registers that are used by the Inline Assembly
28710 statements.
28711
28712 Using a register that the compiler doesn't know about
28713 could be a side effect of an instruction (like @code{mull}
28714 storing its result in both eax and edx).
28715 It can also arise from explicit register usage in your
28716 assembly code; for example:
28717 @smallexample
28718 @group
28719 Asm ("movl %0, %%ebx" & LF & HT &
28720      "movl %%ebx, %1",
28721      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
28722      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
28723 @end group
28724 @end smallexample
28725 @noindent
28726 where the compiler (since it does not analyze the @code{Asm} template string)
28727 does not know you are using the ebx register.
28728
28729 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
28730 to identify the registers that will be used by your assembly code:
28731
28732 @smallexample
28733 @group
28734 Asm ("movl %0, %%ebx" & LF & HT &
28735      "movl %%ebx, %1",
28736      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
28737      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28738      Clobber => "ebx");
28739 @end group
28740 @end smallexample
28741
28742 The Clobber parameter is a static string expression specifying the
28743 register(s) you are using.  Note that register names are @emph{not} prefixed
28744 by a percent sign. Also, if more than one register is used then their names
28745 are separated by commas; e.g., @code{"eax, ebx"}
28746
28747 The @code{Clobber} parameter has several additional uses:
28748 @enumerate
28749 @item Use ``register'' name @code{cc} to indicate that flags might have changed
28750 @item Use ``register'' name @code{memory} if you changed a memory location
28751 @end enumerate
28752
28753 @c ---------------------------------------------------------------------------
28754 @node The Volatile Parameter
28755 @subsection The @code{Volatile} Parameter
28756 @cindex Volatile parameter
28757
28758 @noindent
28759 Compiler optimizations in the presence of Inline Assembler may sometimes have
28760 unwanted effects.  For example, when an @code{Asm} invocation with an input
28761 variable is inside a loop, the compiler might move the loading of the input
28762 variable outside the loop, regarding it as a one-time initialization.
28763
28764 If this effect is not desired, you can disable such optimizations by setting
28765 the @code{Volatile} parameter to @code{True}; for example:
28766
28767 @smallexample @c ada
28768 @group
28769 Asm ("movl %0, %%ebx" & LF & HT &
28770      "movl %%ebx, %1",
28771      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
28772      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
28773      Clobber  => "ebx",
28774      Volatile => True);
28775 @end group
28776 @end smallexample
28777
28778 By default, @code{Volatile} is set to @code{False} unless there is no
28779 @code{Outputs} parameter.
28780
28781 Although setting @code{Volatile} to @code{True} prevents unwanted
28782 optimizations, it will also disable other optimizations that might be
28783 important for efficiency. In general, you should set @code{Volatile}
28784 to @code{True} only if the compiler's optimizations have created
28785 problems.
28786 @c END OF INLINE ASSEMBLER CHAPTER
28787 @c ===============================
28788
28789 @c ***********************************
28790 @c * Compatibility and Porting Guide *
28791 @c ***********************************
28792 @node Compatibility and Porting Guide
28793 @appendix Compatibility and Porting Guide
28794
28795 @noindent
28796 This chapter describes the compatibility issues that may arise between
28797 GNAT and other Ada compilation systems (including those for Ada 83),
28798 and shows how GNAT can expedite porting
28799 applications developed in other Ada environments.
28800
28801 @menu
28802 * Compatibility with Ada 83::
28803 * Compatibility between Ada 95 and Ada 2005::
28804 * Implementation-dependent characteristics::
28805 * Compatibility with Other Ada Systems::
28806 * Representation Clauses::
28807 @ifclear vms
28808 @c Brief section is only in non-VMS version
28809 @c Full chapter is in VMS version
28810 * Compatibility with HP Ada 83::
28811 @end ifclear
28812 @ifset vms
28813 * Transitioning to 64-Bit GNAT for OpenVMS::
28814 @end ifset
28815 @end menu
28816
28817 @node Compatibility with Ada 83
28818 @section Compatibility with Ada 83
28819 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
28820
28821 @noindent
28822 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
28823 particular, the design intention was that the difficulties associated
28824 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
28825 that occur when moving from one Ada 83 system to another.
28826
28827 However, there are a number of points at which there are minor
28828 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
28829 full details of these issues,
28830 and should be consulted for a complete treatment.
28831 In practice the
28832 following subsections treat the most likely issues to be encountered.
28833
28834 @menu
28835 * Legal Ada 83 programs that are illegal in Ada 95::
28836 * More deterministic semantics::
28837 * Changed semantics::
28838 * Other language compatibility issues::
28839 @end menu
28840
28841 @node Legal Ada 83 programs that are illegal in Ada 95
28842 @subsection Legal Ada 83 programs that are illegal in Ada 95
28843
28844 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
28845 Ada 95 and thus also in Ada 2005:
28846
28847 @table @emph
28848 @item Character literals
28849 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
28850 @code{Wide_Character} as a new predefined character type, some uses of
28851 character literals that were legal in Ada 83 are illegal in Ada 95.
28852 For example:
28853 @smallexample @c ada
28854    for Char in 'A' .. 'Z' loop @dots{} end loop;
28855 @end smallexample
28856
28857 @noindent
28858 The problem is that @code{'A'} and @code{'Z'} could be from either
28859 @code{Character} or @code{Wide_Character}.  The simplest correction
28860 is to make the type explicit; e.g.:
28861 @smallexample @c ada
28862    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
28863 @end smallexample
28864
28865 @item New reserved words
28866 The identifiers @code{abstract}, @code{aliased}, @code{protected},
28867 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
28868 Existing Ada 83 code using any of these identifiers must be edited to
28869 use some alternative name.
28870
28871 @item Freezing rules
28872 The rules in Ada 95 are slightly different with regard to the point at
28873 which entities are frozen, and representation pragmas and clauses are
28874 not permitted past the freeze point.  This shows up most typically in
28875 the form of an error message complaining that a representation item
28876 appears too late, and the appropriate corrective action is to move
28877 the item nearer to the declaration of the entity to which it refers.
28878
28879 A particular case is that representation pragmas
28880 @ifset vms
28881 (including the
28882 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
28883 @end ifset
28884 cannot be applied to a subprogram body.  If necessary, a separate subprogram
28885 declaration must be introduced to which the pragma can be applied.
28886
28887 @item Optional bodies for library packages
28888 In Ada 83, a package that did not require a package body was nevertheless
28889 allowed to have one.  This lead to certain surprises in compiling large
28890 systems (situations in which the body could be unexpectedly ignored by the
28891 binder).  In Ada 95, if a package does not require a body then it is not
28892 permitted to have a body.  To fix this problem, simply remove a redundant
28893 body if it is empty, or, if it is non-empty, introduce a dummy declaration
28894 into the spec that makes the body required.  One approach is to add a private
28895 part to the package declaration (if necessary), and define a parameterless
28896 procedure called @code{Requires_Body}, which must then be given a dummy
28897 procedure body in the package body, which then becomes required.
28898 Another approach (assuming that this does not introduce elaboration
28899 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
28900 since one effect of this pragma is to require the presence of a package body.
28901
28902 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
28903 In Ada 95, the exception @code{Numeric_Error} is a renaming of
28904 @code{Constraint_Error}.
28905 This means that it is illegal to have separate exception handlers for
28906 the two exceptions.  The fix is simply to remove the handler for the
28907 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
28908 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
28909
28910 @item Indefinite subtypes in generics
28911 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
28912 as the actual for a generic formal private type, but then the instantiation
28913 would be illegal if there were any instances of declarations of variables
28914 of this type in the generic body.  In Ada 95, to avoid this clear violation
28915 of the methodological principle known as the ``contract model'',
28916 the generic declaration explicitly indicates whether
28917 or not such instantiations are permitted.  If a generic formal parameter
28918 has explicit unknown discriminants, indicated by using @code{(<>)} after the
28919 type name, then it can be instantiated with indefinite types, but no
28920 stand-alone variables can be declared of this type.  Any attempt to declare
28921 such a variable will result in an illegality at the time the generic is
28922 declared.  If the @code{(<>)} notation is not used, then it is illegal
28923 to instantiate the generic with an indefinite type.
28924 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
28925 It will show up as a compile time error, and
28926 the fix is usually simply to add the @code{(<>)} to the generic declaration.
28927 @end table
28928
28929 @node More deterministic semantics
28930 @subsection More deterministic semantics
28931
28932 @table @emph
28933 @item Conversions
28934 Conversions from real types to integer types round away from 0.  In Ada 83
28935 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
28936 implementation freedom was intended to support unbiased rounding in
28937 statistical applications, but in practice it interfered with portability.
28938 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
28939 is required.  Numeric code may be affected by this change in semantics.
28940 Note, though, that this issue is no worse than already existed in Ada 83
28941 when porting code from one vendor to another.
28942
28943 @item Tasking
28944 The Real-Time Annex introduces a set of policies that define the behavior of
28945 features that were implementation dependent in Ada 83, such as the order in
28946 which open select branches are executed.
28947 @end table
28948
28949 @node Changed semantics
28950 @subsection Changed semantics
28951
28952 @noindent
28953 The worst kind of incompatibility is one where a program that is legal in
28954 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
28955 possible in Ada 83.  Fortunately this is extremely rare, but the one
28956 situation that you should be alert to is the change in the predefined type
28957 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
28958
28959 @table @emph
28960 @item Range of type @code{Character}
28961 The range of @code{Standard.Character} is now the full 256 characters
28962 of Latin-1, whereas in most Ada 83 implementations it was restricted
28963 to 128 characters. Although some of the effects of
28964 this change will be manifest in compile-time rejection of legal
28965 Ada 83 programs it is possible for a working Ada 83 program to have
28966 a different effect in Ada 95, one that was not permitted in Ada 83.
28967 As an example, the expression
28968 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
28969 delivers @code{255} as its value.
28970 In general, you should look at the logic of any
28971 character-processing Ada 83 program and see whether it needs to be adapted
28972 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
28973 character handling package that may be relevant if code needs to be adapted
28974 to account for the additional Latin-1 elements.
28975 The desirable fix is to
28976 modify the program to accommodate the full character set, but in some cases
28977 it may be convenient to define a subtype or derived type of Character that
28978 covers only the restricted range.
28979 @cindex Latin-1
28980 @end table
28981
28982 @node Other language compatibility issues
28983 @subsection Other language compatibility issues
28984
28985 @table @emph
28986 @item @option{-gnat83} switch
28987 All implementations of GNAT provide a switch that causes GNAT to operate
28988 in Ada 83 mode.  In this mode, some but not all compatibility problems
28989 of the type described above are handled automatically.  For example, the
28990 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
28991 as identifiers as in Ada 83.
28992 However,
28993 in practice, it is usually advisable to make the necessary modifications
28994 to the program to remove the need for using this switch.
28995 See @ref{Compiling Different Versions of Ada}.
28996
28997 @item Support for removed Ada 83 pragmas and attributes
28998 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
28999 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
29000 compilers are allowed, but not required, to implement these missing
29001 elements.  In contrast with some other compilers, GNAT implements all
29002 such pragmas and attributes, eliminating this compatibility concern.  These
29003 include @code{pragma Interface} and the floating point type attributes
29004 (@code{Emax}, @code{Mantissa}, etc.), among other items.
29005 @end table
29006
29007
29008 @node Compatibility between Ada 95 and Ada 2005
29009 @section Compatibility between Ada 95 and Ada 2005
29010 @cindex Compatibility between Ada 95 and Ada 2005
29011
29012 @noindent
29013 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
29014 a number of incompatibilities. Several are enumerated below;
29015 for a complete description please see the
29016 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
29017 @cite{Rationale for Ada 2005}.
29018
29019 @table @emph
29020 @item New reserved words.
29021 The words @code{interface}, @code{overriding} and @code{synchronized} are
29022 reserved in Ada 2005.
29023 A pre-Ada 2005 program that uses any of these as an identifier will be
29024 illegal.
29025
29026 @item New declarations in predefined packages.
29027 A number of packages in the predefined environment contain new declarations:
29028 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
29029 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
29030 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
29031 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
29032 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
29033 If an Ada 95 program does a @code{with} and @code{use} of any of these
29034 packages, the new declarations may cause name clashes.
29035
29036 @item Access parameters.
29037 A nondispatching subprogram with an access parameter cannot be renamed
29038 as a dispatching operation.  This was permitted in Ada 95.
29039
29040 @item Access types, discriminants, and constraints.
29041 Rule changes in this area have led to some incompatibilities; for example,
29042 constrained subtypes of some access types are not permitted in Ada 2005.
29043
29044 @item Aggregates for limited types.
29045 The allowance of aggregates for limited types in Ada 2005 raises the
29046 possibility of ambiguities in legal Ada 95 programs, since additional types
29047 now need to be considered in expression resolution.
29048
29049 @item Fixed-point multiplication and division.
29050 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
29051 were legal in Ada 95 and invoked the predefined versions of these operations,
29052 are now ambiguous.
29053 The ambiguity may be resolved either by applying a type conversion to the
29054 expression, or by explicitly invoking the operation from package
29055 @code{Standard}.
29056
29057 @item Return-by-reference types.
29058 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
29059 can declare a function returning a value from an anonymous access type.
29060 @end table
29061
29062
29063 @node Implementation-dependent characteristics
29064 @section Implementation-dependent characteristics
29065 @noindent
29066 Although the Ada language defines the semantics of each construct as
29067 precisely as practical, in some situations (for example for reasons of
29068 efficiency, or where the effect is heavily dependent on the host or target
29069 platform) the implementation is allowed some freedom.  In porting Ada 83
29070 code to GNAT, you need to be aware of whether / how the existing code
29071 exercised such implementation dependencies.  Such characteristics fall into
29072 several categories, and GNAT offers specific support in assisting the
29073 transition from certain Ada 83 compilers.
29074
29075 @menu
29076 * Implementation-defined pragmas::
29077 * Implementation-defined attributes::
29078 * Libraries::
29079 * Elaboration order::
29080 * Target-specific aspects::
29081 @end menu
29082
29083 @node Implementation-defined pragmas
29084 @subsection Implementation-defined pragmas
29085
29086 @noindent
29087 Ada compilers are allowed to supplement the language-defined pragmas, and
29088 these are a potential source of non-portability.  All GNAT-defined pragmas
29089 are described in the GNAT Reference Manual, and these include several that
29090 are specifically intended to correspond to other vendors' Ada 83 pragmas.
29091 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
29092 For
29093 compatibility with HP Ada 83, GNAT supplies the pragmas
29094 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
29095 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
29096 and @code{Volatile}.
29097 Other relevant pragmas include @code{External} and @code{Link_With}.
29098 Some vendor-specific
29099 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
29100 recognized, thus
29101 avoiding compiler rejection of units that contain such pragmas; they are not
29102 relevant in a GNAT context and hence are not otherwise implemented.
29103
29104 @node Implementation-defined attributes
29105 @subsection Implementation-defined attributes
29106
29107 Analogous to pragmas, the set of attributes may be extended by an
29108 implementation.  All GNAT-defined attributes are described in the
29109 @cite{GNAT Reference Manual}, and these include several that are specifically
29110 intended
29111 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
29112 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
29113 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
29114 @code{Type_Class}.
29115
29116 @node Libraries
29117 @subsection Libraries
29118 @noindent
29119 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
29120 code uses vendor-specific libraries then there are several ways to manage
29121 this in Ada 95 or Ada 2005:
29122 @enumerate
29123 @item
29124 If the source code for the libraries (specifications and bodies) are
29125 available, then the libraries can be migrated in the same way as the
29126 application.
29127 @item
29128 If the source code for the specifications but not the bodies are
29129 available, then you can reimplement the bodies.
29130 @item
29131 Some features introduced by Ada 95 obviate the need for library support.  For
29132 example most Ada 83 vendors supplied a package for unsigned integers.  The
29133 Ada 95 modular type feature is the preferred way to handle this need, so
29134 instead of migrating or reimplementing the unsigned integer package it may
29135 be preferable to retrofit the application using modular types.
29136 @end enumerate
29137
29138 @node Elaboration order
29139 @subsection Elaboration order
29140 @noindent
29141 The implementation can choose any elaboration order consistent with the unit
29142 dependency relationship.  This freedom means that some orders can result in
29143 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
29144 to invoke a subprogram its body has been elaborated, or to instantiate a
29145 generic before the generic body has been elaborated.  By default GNAT
29146 attempts to choose a safe order (one that will not encounter access before
29147 elaboration problems) by implicitly inserting @code{Elaborate} or
29148 @code{Elaborate_All} pragmas where
29149 needed.  However, this can lead to the creation of elaboration circularities
29150 and a resulting rejection of the program by gnatbind.  This issue is
29151 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
29152 In brief, there are several
29153 ways to deal with this situation:
29154
29155 @itemize @bullet
29156 @item
29157 Modify the program to eliminate the circularities, e.g.@: by moving
29158 elaboration-time code into explicitly-invoked procedures
29159 @item
29160 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
29161 @code{Elaborate} pragmas, and then inhibit the generation of implicit
29162 @code{Elaborate_All}
29163 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
29164 (by selectively suppressing elaboration checks via pragma
29165 @code{Suppress(Elaboration_Check)} when it is safe to do so).
29166 @end itemize
29167
29168 @node Target-specific aspects
29169 @subsection Target-specific aspects
29170 @noindent
29171 Low-level applications need to deal with machine addresses, data
29172 representations, interfacing with assembler code, and similar issues.  If
29173 such an Ada 83 application is being ported to different target hardware (for
29174 example where the byte endianness has changed) then you will need to
29175 carefully examine the program logic; the porting effort will heavily depend
29176 on the robustness of the original design.  Moreover, Ada 95 (and thus
29177 Ada 2005) are sometimes
29178 incompatible with typical Ada 83 compiler practices regarding implicit
29179 packing, the meaning of the Size attribute, and the size of access values.
29180 GNAT's approach to these issues is described in @ref{Representation Clauses}.
29181
29182 @node Compatibility with Other Ada Systems
29183 @section Compatibility with Other Ada Systems
29184
29185 @noindent
29186 If programs avoid the use of implementation dependent and
29187 implementation defined features, as documented in the @cite{Ada
29188 Reference Manual}, there should be a high degree of portability between
29189 GNAT and other Ada systems.  The following are specific items which
29190 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
29191 compilers, but do not affect porting code to GNAT@.
29192 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
29193 the following issues may or may not arise for Ada 2005 programs
29194 when other compilers appear.)
29195
29196 @table @emph
29197 @item Ada 83 Pragmas and Attributes
29198 Ada 95 compilers are allowed, but not required, to implement the missing
29199 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
29200 GNAT implements all such pragmas and attributes, eliminating this as
29201 a compatibility concern, but some other Ada 95 compilers reject these
29202 pragmas and attributes.
29203
29204 @item Specialized Needs Annexes
29205 GNAT implements the full set of special needs annexes.  At the
29206 current time, it is the only Ada 95 compiler to do so.  This means that
29207 programs making use of these features may not be portable to other Ada
29208 95 compilation systems.
29209
29210 @item Representation Clauses
29211 Some other Ada 95 compilers implement only the minimal set of
29212 representation clauses required by the Ada 95 reference manual.  GNAT goes
29213 far beyond this minimal set, as described in the next section.
29214 @end table
29215
29216 @node Representation Clauses
29217 @section Representation Clauses
29218
29219 @noindent
29220 The Ada 83 reference manual was quite vague in describing both the minimal
29221 required implementation of representation clauses, and also their precise
29222 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
29223 minimal set of capabilities required is still quite limited.
29224
29225 GNAT implements the full required set of capabilities in
29226 Ada 95 and Ada 2005, but also goes much further, and in particular
29227 an effort has been made to be compatible with existing Ada 83 usage to the
29228 greatest extent possible.
29229
29230 A few cases exist in which Ada 83 compiler behavior is incompatible with
29231 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
29232 intentional or accidental dependence on specific implementation dependent
29233 characteristics of these Ada 83 compilers.  The following is a list of
29234 the cases most likely to arise in existing Ada 83 code.
29235
29236 @table @emph
29237 @item Implicit Packing
29238 Some Ada 83 compilers allowed a Size specification to cause implicit
29239 packing of an array or record.  This could cause expensive implicit
29240 conversions for change of representation in the presence of derived
29241 types, and the Ada design intends to avoid this possibility.
29242 Subsequent AI's were issued to make it clear that such implicit
29243 change of representation in response to a Size clause is inadvisable,
29244 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
29245 Reference Manuals as implementation advice that is followed by GNAT@.
29246 The problem will show up as an error
29247 message rejecting the size clause.  The fix is simply to provide
29248 the explicit pragma @code{Pack}, or for more fine tuned control, provide
29249 a Component_Size clause.
29250
29251 @item Meaning of Size Attribute
29252 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
29253 the minimal number of bits required to hold values of the type.  For example,
29254 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
29255 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
29256 some 32 in this situation.  This problem will usually show up as a compile
29257 time error, but not always.  It is a good idea to check all uses of the
29258 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
29259 Object_Size can provide a useful way of duplicating the behavior of
29260 some Ada 83 compiler systems.
29261
29262 @item Size of Access Types
29263 A common assumption in Ada 83 code is that an access type is in fact a pointer,
29264 and that therefore it will be the same size as a System.Address value.  This
29265 assumption is true for GNAT in most cases with one exception.  For the case of
29266 a pointer to an unconstrained array type (where the bounds may vary from one
29267 value of the access type to another), the default is to use a ``fat pointer'',
29268 which is represented as two separate pointers, one to the bounds, and one to
29269 the array.  This representation has a number of advantages, including improved
29270 efficiency.  However, it may cause some difficulties in porting existing Ada 83
29271 code which makes the assumption that, for example, pointers fit in 32 bits on
29272 a machine with 32-bit addressing.
29273
29274 To get around this problem, GNAT also permits the use of ``thin pointers'' for
29275 access types in this case (where the designated type is an unconstrained array
29276 type).  These thin pointers are indeed the same size as a System.Address value.
29277 To specify a thin pointer, use a size clause for the type, for example:
29278
29279 @smallexample @c ada
29280 type X is access all String;
29281 for X'Size use Standard'Address_Size;
29282 @end smallexample
29283
29284 @noindent
29285 which will cause the type X to be represented using a single pointer.
29286 When using this representation, the bounds are right behind the array.
29287 This representation is slightly less efficient, and does not allow quite
29288 such flexibility in the use of foreign pointers or in using the
29289 Unrestricted_Access attribute to create pointers to non-aliased objects.
29290 But for any standard portable use of the access type it will work in
29291 a functionally correct manner and allow porting of existing code.
29292 Note that another way of forcing a thin pointer representation
29293 is to use a component size clause for the element size in an array,
29294 or a record representation clause for an access field in a record.
29295 @end table
29296
29297 @ifclear vms
29298 @c This brief section is only in the non-VMS version
29299 @c The complete chapter on HP Ada is in the VMS version
29300 @node Compatibility with HP Ada 83
29301 @section Compatibility with HP Ada 83
29302
29303 @noindent
29304 The VMS version of GNAT fully implements all the pragmas and attributes
29305 provided by HP Ada 83, as well as providing the standard HP Ada 83
29306 libraries, including Starlet.  In addition, data layouts and parameter
29307 passing conventions are highly compatible.  This means that porting
29308 existing HP Ada 83 code to GNAT in VMS systems should be easier than
29309 most other porting efforts.  The following are some of the most
29310 significant differences between GNAT and HP Ada 83.
29311
29312 @table @emph
29313 @item Default floating-point representation
29314 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
29315 it is VMS format.  GNAT does implement the necessary pragmas
29316 (Long_Float, Float_Representation) for changing this default.
29317
29318 @item System
29319 The package System in GNAT exactly corresponds to the definition in the
29320 Ada 95 reference manual, which means that it excludes many of the
29321 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
29322 that contains the additional definitions, and a special pragma,
29323 Extend_System allows this package to be treated transparently as an
29324 extension of package System.
29325
29326 @item To_Address
29327 The definitions provided by Aux_DEC are exactly compatible with those
29328 in the HP Ada 83 version of System, with one exception.
29329 HP Ada provides the following declarations:
29330
29331 @smallexample @c ada
29332 TO_ADDRESS (INTEGER)
29333 TO_ADDRESS (UNSIGNED_LONGWORD)
29334 TO_ADDRESS (@i{universal_integer})
29335 @end smallexample
29336
29337 @noindent
29338 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
29339 an extension to Ada 83 not strictly compatible with the reference manual.
29340 In GNAT, we are constrained to be exactly compatible with the standard,
29341 and this means we cannot provide this capability.  In HP Ada 83, the
29342 point of this definition is to deal with a call like:
29343
29344 @smallexample @c ada
29345 TO_ADDRESS (16#12777#);
29346 @end smallexample
29347
29348 @noindent
29349 Normally, according to the Ada 83 standard, one would expect this to be
29350 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
29351 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
29352 definition using @i{universal_integer} takes precedence.
29353
29354 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
29355 is not possible to be 100% compatible.  Since there are many programs using
29356 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
29357 to change the name of the function in the UNSIGNED_LONGWORD case, so the
29358 declarations provided in the GNAT version of AUX_Dec are:
29359
29360 @smallexample @c ada
29361 function To_Address (X : Integer) return Address;
29362 pragma Pure_Function (To_Address);
29363
29364 function To_Address_Long (X : Unsigned_Longword)
29365  return Address;
29366 pragma Pure_Function (To_Address_Long);
29367 @end smallexample
29368
29369 @noindent
29370 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
29371 change the name to TO_ADDRESS_LONG@.
29372
29373 @item Task_Id values
29374 The Task_Id values assigned will be different in the two systems, and GNAT
29375 does not provide a specified value for the Task_Id of the environment task,
29376 which in GNAT is treated like any other declared task.
29377 @end table
29378
29379 @noindent
29380 For full details on these and other less significant compatibility issues,
29381 see appendix E of the HP publication entitled @cite{HP Ada, Technical
29382 Overview and Comparison on HP Platforms}.
29383
29384 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
29385 attributes are recognized, although only a subset of them can sensibly
29386 be implemented.  The description of pragmas in the
29387 @cite{GNAT Reference Manual}
29388 indicates whether or not they are applicable to non-VMS systems.
29389 @end ifclear
29390
29391 @ifset vms
29392 @node Transitioning to 64-Bit GNAT for OpenVMS
29393 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
29394
29395 @noindent
29396 This section is meant to assist users of pre-2006 @value{EDITION}
29397 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
29398 the version of the GNAT technology supplied in 2006 and later for
29399 OpenVMS on both Alpha and I64.
29400
29401 @menu
29402 * Introduction to transitioning::
29403 * Migration of 32 bit code::
29404 * Taking advantage of 64 bit addressing::
29405 * Technical details::
29406 @end menu
29407
29408 @node Introduction to transitioning
29409 @subsection Introduction
29410
29411 @noindent
29412 64-bit @value{EDITION} for Open VMS has been designed to meet
29413 three main goals:
29414
29415 @enumerate
29416 @item
29417 Providing a full conforming implementation of Ada 95 and Ada 2005
29418
29419 @item
29420 Allowing maximum backward compatibility, thus easing migration of existing
29421 Ada source code
29422
29423 @item
29424 Supplying a path for exploiting the full 64-bit address range
29425 @end enumerate
29426
29427 @noindent
29428 Ada's strong typing semantics has made it
29429 impractical to have different 32-bit and 64-bit modes. As soon as
29430 one object could possibly be outside the 32-bit address space, this
29431 would make it necessary for the @code{System.Address} type to be 64 bits.
29432 In particular, this would cause inconsistencies if 32-bit code is
29433 called from 64-bit code that raises an exception.
29434
29435 This issue has been resolved by always using 64-bit addressing
29436 at the system level, but allowing for automatic conversions between
29437 32-bit and 64-bit addresses where required. Thus users who
29438 do not currently require 64-bit addressing capabilities, can
29439 recompile their code with only minimal changes (and indeed
29440 if the code is written in portable Ada, with no assumptions about
29441 the size of the @code{Address} type, then no changes at all are necessary).
29442 At the same time,
29443 this approach provides a simple, gradual upgrade path to future
29444 use of larger memories than available for 32-bit systems.
29445 Also, newly written applications or libraries will by default
29446 be fully compatible with future systems exploiting 64-bit
29447 addressing capabilities.
29448
29449 @ref{Migration of 32 bit code}, will focus on porting applications
29450 that do not require more than 2 GB of
29451 addressable memory. This code will be referred to as
29452 @emph{32-bit code}.
29453 For applications intending to exploit the full 64-bit address space,
29454 @ref{Taking advantage of 64 bit addressing},
29455 will consider further changes that may be required.
29456 Such code will be referred to below as @emph{64-bit code}.
29457
29458 @node Migration of 32 bit code
29459 @subsection Migration of 32-bit code
29460
29461 @menu
29462 * Address types::
29463 * Access types::
29464 * Unchecked conversions::
29465 * Predefined constants::
29466 * Interfacing with C::
29467 * Experience with source compatibility::
29468 @end menu
29469
29470 @node Address types
29471 @subsubsection Address types
29472
29473 @noindent
29474 To solve the problem of mixing 64-bit and 32-bit addressing,
29475 while maintaining maximum backward compatibility, the following
29476 approach has been taken:
29477
29478 @itemize @bullet
29479 @item
29480 @code{System.Address} always has a size of 64 bits
29481
29482 @item
29483 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
29484 @end itemize
29485
29486 @noindent
29487 Since @code{System.Short_Address} is a subtype of @code{System.Address},
29488 a @code{Short_Address}
29489 may be used where an @code{Address} is required, and vice versa, without
29490 needing explicit type conversions.
29491 By virtue of the Open VMS parameter passing conventions,
29492 even imported
29493 and exported subprograms that have 32-bit address parameters are
29494 compatible with those that have 64-bit address parameters.
29495 (See @ref{Making code 64 bit clean} for details.)
29496
29497 The areas that may need attention are those where record types have
29498 been defined that contain components of the type @code{System.Address}, and
29499 where objects of this type are passed to code expecting a record layout with
29500 32-bit addresses.
29501
29502 Different compilers on different platforms cannot be
29503 expected to represent the same type in the same way,
29504 since alignment constraints
29505 and other system-dependent properties affect the compiler's decision.
29506 For that reason, Ada code
29507 generally uses representation clauses to specify the expected
29508 layout where required.
29509
29510 If such a representation clause uses 32 bits for a component having
29511 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
29512 will detect that error and produce a specific diagnostic message.
29513 The developer should then determine whether the representation
29514 should be 64 bits or not and make either of two changes:
29515 change the size to 64 bits and leave the type as @code{System.Address}, or
29516 leave the size as 32 bits and change the type to @code{System.Short_Address}.
29517 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
29518 required in any code setting or accessing the field; the compiler will
29519 automatically perform any needed conversions between address
29520 formats.
29521
29522 @node Access types
29523 @subsubsection Access types
29524
29525 @noindent
29526 By default, objects designated by access values are always
29527 allocated in the 32-bit
29528 address space. Thus legacy code will never contain
29529 any objects that are not addressable with 32-bit addresses, and
29530 the compiler will never raise exceptions as result of mixing
29531 32-bit and 64-bit addresses.
29532
29533 However, the access values themselves are represented in 64 bits, for optimum
29534 performance and future compatibility with 64-bit code. As was
29535 the case with @code{System.Address}, the compiler will give an error message
29536 if an object or record component has a representation clause that
29537 requires the access value to fit in 32 bits. In such a situation,
29538 an explicit size clause for the access type, specifying 32 bits,
29539 will have the desired effect.
29540
29541 General access types (declared with @code{access all}) can never be
29542 32 bits, as values of such types must be able to refer to any object
29543 of the  designated type,
29544 including objects residing outside the 32-bit address range.
29545 Existing Ada 83 code will not contain such type definitions,
29546 however, since general access types were introduced in Ada 95.
29547
29548 @node Unchecked conversions
29549 @subsubsection Unchecked conversions
29550
29551 @noindent
29552 In the case of an @code{Unchecked_Conversion} where the source type is a
29553 64-bit access type or the type @code{System.Address}, and the target
29554 type is a 32-bit type, the compiler will generate a warning.
29555 Even though the generated code will still perform the required
29556 conversions, it is highly recommended in these cases to use
29557 respectively a 32-bit access type or @code{System.Short_Address}
29558 as the source type.
29559
29560 @node Predefined constants
29561 @subsubsection Predefined constants
29562
29563 @noindent
29564 The following table shows the correspondence between pre-2006 versions of
29565 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
29566 (``New''):
29567
29568 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
29569 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
29570 @item   @code{System.Word_Size}          @tab 32      @tab 64
29571 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
29572 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
29573 @item   @code{System.Address_Size}       @tab 32      @tab 64
29574 @end multitable
29575
29576 @noindent
29577 If you need to refer to the specific
29578 memory size of a 32-bit implementation, instead of the
29579 actual memory size, use @code{System.Short_Memory_Size}
29580 rather than @code{System.Memory_Size}.
29581 Similarly, references to @code{System.Address_Size} may need
29582 to be replaced by @code{System.Short_Address'Size}.
29583 The program @command{gnatfind} may be useful for locating
29584 references to the above constants, so that you can verify that they
29585 are still correct.
29586
29587 @node Interfacing with C
29588 @subsubsection Interfacing with C
29589
29590 @noindent
29591 In order to minimize the impact of the transition to 64-bit addresses on
29592 legacy programs, some fundamental types in the @code{Interfaces.C}
29593 package hierarchy continue to be represented in 32 bits.
29594 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
29595 This eases integration with the default HP C layout choices, for example
29596 as found in the system routines in @code{DECC$SHR.EXE}.
29597 Because of this implementation choice, the type fully compatible with
29598 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
29599 Depending on the context the compiler will issue a
29600 warning or an error when type @code{Address} is used, alerting the user to a
29601 potential problem. Otherwise 32-bit programs that use
29602 @code{Interfaces.C} should normally not require code modifications
29603
29604 The other issue arising with C interfacing concerns pragma @code{Convention}.
29605 For VMS 64-bit systems, there is an issue of the appropriate default size
29606 of C convention pointers in the absence of an explicit size clause. The HP
29607 C compiler can choose either 32 or 64 bits depending on compiler options.
29608 GNAT chooses 32-bits rather than 64-bits in the default case where no size
29609 clause is given. This proves a better choice for porting 32-bit legacy
29610 applications. In order to have a 64-bit representation, it is necessary to
29611 specify a size representation clause. For example:
29612
29613 @smallexample @c ada
29614 type int_star is access Interfaces.C.int;
29615 pragma Convention(C, int_star);
29616 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
29617 @end smallexample
29618
29619 @node Experience with source compatibility
29620 @subsubsection Experience with source compatibility
29621
29622 @noindent
29623 The Security Server and STARLET on I64 provide an interesting ``test case''
29624 for source compatibility issues, since it is in such system code
29625 where assumptions about @code{Address} size might be expected to occur.
29626 Indeed, there were a small number of occasions in the Security Server
29627 file @file{jibdef.ads}
29628 where a representation clause for a record type specified
29629 32 bits for a component of type @code{Address}.
29630 All of these errors were detected by the compiler.
29631 The repair was obvious and immediate; to simply replace @code{Address} by
29632 @code{Short_Address}.
29633
29634 In the case of STARLET, there were several record types that should
29635 have had representation clauses but did not.  In these record types
29636 there was an implicit assumption that an @code{Address} value occupied
29637 32 bits.
29638 These compiled without error, but their usage resulted in run-time error
29639 returns from STARLET system calls.
29640 Future GNAT technology enhancements may include a tool that detects and flags
29641 these sorts of potential source code porting problems.
29642
29643 @c ****************************************
29644 @node Taking advantage of 64 bit addressing
29645 @subsection Taking advantage of 64-bit addressing
29646
29647 @menu
29648 * Making code 64 bit clean::
29649 * Allocating memory from the 64 bit storage pool::
29650 * Restrictions on use of 64 bit objects::
29651 * Using 64 bit storage pools by default::
29652 * General access types::
29653 * STARLET and other predefined libraries::
29654 @end menu
29655
29656 @node Making code 64 bit clean
29657 @subsubsection Making code 64-bit clean
29658
29659 @noindent
29660 In order to prevent problems that may occur when (parts of) a
29661 system start using memory outside the 32-bit address range,
29662 we recommend some additional guidelines:
29663
29664 @itemize @bullet
29665 @item
29666 For imported subprograms that take parameters of the
29667 type @code{System.Address}, ensure that these subprograms can
29668 indeed handle 64-bit addresses. If not, or when in doubt,
29669 change the subprogram declaration to specify
29670 @code{System.Short_Address} instead.
29671
29672 @item
29673 Resolve all warnings related to size mismatches in
29674 unchecked conversions. Failing to do so causes
29675 erroneous execution if the source object is outside
29676 the 32-bit address space.
29677
29678 @item
29679 (optional) Explicitly use the 32-bit storage pool
29680 for access types used in a 32-bit context, or use
29681 generic access types where possible
29682 (@pxref{Restrictions on use of 64 bit objects}).
29683 @end itemize
29684
29685 @noindent
29686 If these rules are followed, the compiler will automatically insert
29687 any necessary checks to ensure that no addresses or access values
29688 passed to 32-bit code ever refer to objects outside the 32-bit
29689 address range.
29690 Any attempt to do this will raise @code{Constraint_Error}.
29691
29692 @node Allocating memory from the 64 bit storage pool
29693 @subsubsection Allocating memory from the 64-bit storage pool
29694
29695 @noindent
29696 For any access type @code{T} that potentially requires memory allocations
29697 beyond the 32-bit address space,
29698 use the following representation clause:
29699
29700 @smallexample @c ada
29701    for T'Storage_Pool use System.Pool_64;
29702 @end smallexample
29703
29704 @node Restrictions on use of 64 bit objects
29705 @subsubsection Restrictions on use of 64-bit objects
29706
29707 @noindent
29708 Taking the address of an object allocated from a 64-bit storage pool,
29709 and then passing this address to a subprogram expecting
29710 @code{System.Short_Address},
29711 or assigning it to a variable of type @code{Short_Address}, will cause
29712 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
29713 (@pxref{Making code 64 bit clean}), or checks are suppressed,
29714 no exception is raised and execution
29715 will become erroneous.
29716
29717 @node Using 64 bit storage pools by default
29718 @subsubsection Using 64-bit storage pools by default
29719
29720 @noindent
29721 In some cases it may be desirable to have the compiler allocate
29722 from 64-bit storage pools by default. This may be the case for
29723 libraries that are 64-bit clean, but may be used in both 32-bit
29724 and 64-bit contexts. For these cases the following configuration
29725 pragma may be specified:
29726
29727 @smallexample @c ada
29728   pragma Pool_64_Default;
29729 @end smallexample
29730
29731 @noindent
29732 Any code compiled in the context of this pragma will by default
29733 use the @code{System.Pool_64} storage pool. This default may be overridden
29734 for a specific access type @code{T} by the representation clause:
29735
29736 @smallexample @c ada
29737    for T'Storage_Pool use System.Pool_32;
29738 @end smallexample
29739
29740 @noindent
29741 Any object whose address may be passed to a subprogram with a
29742 @code{Short_Address} argument, or assigned to a variable of type
29743 @code{Short_Address}, needs to be allocated from this pool.
29744
29745 @node General access types
29746 @subsubsection General access types
29747
29748 @noindent
29749 Objects designated by access values from a
29750 general access type (declared with @code{access all}) are never allocated
29751 from a 64-bit storage pool. Code that uses general access types will
29752 accept objects allocated in either 32-bit or 64-bit address spaces,
29753 but never allocate objects outside the 32-bit address space.
29754 Using general access types ensures maximum compatibility with both
29755 32-bit and 64-bit code.
29756
29757 @node STARLET and other predefined libraries
29758 @subsubsection STARLET and other predefined libraries
29759
29760 @noindent
29761 All code that comes as part of GNAT is 64-bit clean, but the
29762 restrictions given in @ref{Restrictions on use of 64 bit objects},
29763 still apply. Look at the package
29764 specifications to see in which contexts objects allocated
29765 in 64-bit address space are acceptable.
29766
29767 @node Technical details
29768 @subsection Technical details
29769
29770 @noindent
29771 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
29772 Ada standard with respect to the type of @code{System.Address}. Previous
29773 versions of GNAT Pro have defined this type as private and implemented it as a
29774 modular type.
29775
29776 In order to allow defining @code{System.Short_Address} as a proper subtype,
29777 and to match the implicit sign extension in parameter passing,
29778 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
29779 visible (i.e., non-private) integer type.
29780 Standard operations on the type, such as the binary operators ``+'', ``-'',
29781 etc., that take @code{Address} operands and return an @code{Address} result,
29782 have been hidden by declaring these
29783 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
29784 ambiguities that would otherwise result from overloading.
29785 (Note that, although @code{Address} is a visible integer type,
29786 good programming practice dictates against exploiting the type's
29787 integer properties such as literals, since this will compromise
29788 code portability.)
29789
29790 Defining @code{Address} as a visible integer type helps achieve
29791 maximum compatibility for existing Ada code,
29792 without sacrificing the capabilities of the 64-bit architecture.
29793 @end ifset
29794
29795 @c ************************************************
29796 @ifset unw
29797 @node Microsoft Windows Topics
29798 @appendix Microsoft Windows Topics
29799 @cindex Windows NT
29800 @cindex Windows 95
29801 @cindex Windows 98
29802
29803 @noindent
29804 This chapter describes topics that are specific to the Microsoft Windows
29805 platforms (NT, 2000, and XP Professional).
29806
29807 @menu
29808 * Using GNAT on Windows::
29809 * Using a network installation of GNAT::
29810 * CONSOLE and WINDOWS subsystems::
29811 * Temporary Files::
29812 * Mixed-Language Programming on Windows::
29813 * Windows Calling Conventions::
29814 * Introduction to Dynamic Link Libraries (DLLs)::
29815 * Using DLLs with GNAT::
29816 * Building DLLs with GNAT::
29817 * Building DLLs with GNAT Project files::
29818 * Building DLLs with gnatdll::
29819 * GNAT and Windows Resources::
29820 * Debugging a DLL::
29821 * Setting Stack Size from gnatlink::
29822 * Setting Heap Size from gnatlink::
29823 @end menu
29824
29825 @node Using GNAT on Windows
29826 @section Using GNAT on Windows
29827
29828 @noindent
29829 One of the strengths of the GNAT technology is that its tool set
29830 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
29831 @code{gdb} debugger, etc.) is used in the same way regardless of the
29832 platform.
29833
29834 On Windows this tool set is complemented by a number of Microsoft-specific
29835 tools that have been provided to facilitate interoperability with Windows
29836 when this is required. With these tools:
29837
29838 @itemize @bullet
29839
29840 @item
29841 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
29842 subsystems.
29843
29844 @item
29845 You can use any Dynamically Linked Library (DLL) in your Ada code (both
29846 relocatable and non-relocatable DLLs are supported).
29847
29848 @item
29849 You can build Ada DLLs for use in other applications. These applications
29850 can be written in a language other than Ada (e.g., C, C++, etc). Again both
29851 relocatable and non-relocatable Ada DLLs are supported.
29852
29853 @item
29854 You can include Windows resources in your Ada application.
29855
29856 @item
29857 You can use or create COM/DCOM objects.
29858 @end itemize
29859
29860 @noindent
29861 Immediately below are listed all known general GNAT-for-Windows restrictions.
29862 Other restrictions about specific features like Windows Resources and DLLs
29863 are listed in separate sections below.
29864
29865 @itemize @bullet
29866
29867 @item
29868 It is not possible to use @code{GetLastError} and @code{SetLastError}
29869 when tasking, protected records, or exceptions are used. In these
29870 cases, in order to implement Ada semantics, the GNAT run-time system
29871 calls certain Win32 routines that set the last error variable to 0 upon
29872 success. It should be possible to use @code{GetLastError} and
29873 @code{SetLastError} when tasking, protected record, and exception
29874 features are not used, but it is not guaranteed to work.
29875
29876 @item
29877 It is not possible to link against Microsoft libraries except for
29878 import libraries. The library must be built to be compatible with
29879 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
29880 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
29881 not be compatible with the GNAT runtime. Even if the library is
29882 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
29883
29884 @item
29885 When the compilation environment is located on FAT32 drives, users may
29886 experience recompilations of the source files that have not changed if
29887 Daylight Saving Time (DST) state has changed since the last time files
29888 were compiled. NTFS drives do not have this problem.
29889
29890 @item
29891 No components of the GNAT toolset use any entries in the Windows
29892 registry. The only entries that can be created are file associations and
29893 PATH settings, provided the user has chosen to create them at installation
29894 time, as well as some minimal book-keeping information needed to correctly
29895 uninstall or integrate different GNAT products.
29896 @end itemize
29897
29898 @node Using a network installation of GNAT
29899 @section Using a network installation of GNAT
29900
29901 @noindent
29902 Make sure the system on which GNAT is installed is accessible from the
29903 current machine, i.e., the install location is shared over the network.
29904 Shared resources are accessed on Windows by means of UNC paths, which
29905 have the format @code{\\server\sharename\path}
29906
29907 In order to use such a network installation, simply add the UNC path of the
29908 @file{bin} directory of your GNAT installation in front of your PATH. For
29909 example, if GNAT is installed in @file{\GNAT} directory of a share location
29910 called @file{c-drive} on a machine @file{LOKI}, the following command will
29911 make it available:
29912
29913 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
29914
29915 Be aware that every compilation using the network installation results in the
29916 transfer of large amounts of data across the network and will likely cause
29917 serious performance penalty.
29918
29919 @node CONSOLE and WINDOWS subsystems
29920 @section CONSOLE and WINDOWS subsystems
29921 @cindex CONSOLE Subsystem
29922 @cindex WINDOWS Subsystem
29923 @cindex -mwindows
29924
29925 @noindent
29926 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
29927 (which is the default subsystem) will always create a console when
29928 launching the application. This is not something desirable when the
29929 application has a Windows GUI. To get rid of this console the
29930 application must be using the @code{WINDOWS} subsystem. To do so
29931 the @option{-mwindows} linker option must be specified.
29932
29933 @smallexample
29934 $ gnatmake winprog -largs -mwindows
29935 @end smallexample
29936
29937 @node Temporary Files
29938 @section Temporary Files
29939 @cindex Temporary files
29940
29941 @noindent
29942 It is possible to control where temporary files gets created by setting
29943 the @env{TMP} environment variable. The file will be created:
29944
29945 @itemize
29946 @item Under the directory pointed to by the @env{TMP} environment variable if
29947 this directory exists.
29948
29949 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
29950 set (or not pointing to a directory) and if this directory exists.
29951
29952 @item Under the current working directory otherwise.
29953 @end itemize
29954
29955 @noindent
29956 This allows you to determine exactly where the temporary
29957 file will be created. This is particularly useful in networked
29958 environments where you may not have write access to some
29959 directories.
29960
29961 @node Mixed-Language Programming on Windows
29962 @section Mixed-Language Programming on Windows
29963
29964 @noindent
29965 Developing pure Ada applications on Windows is no different than on
29966 other GNAT-supported platforms. However, when developing or porting an
29967 application that contains a mix of Ada and C/C++, the choice of your
29968 Windows C/C++ development environment conditions your overall
29969 interoperability strategy.
29970
29971 If you use @command{gcc} to compile the non-Ada part of your application,
29972 there are no Windows-specific restrictions that affect the overall
29973 interoperability with your Ada code. If you plan to use
29974 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
29975 the following limitations:
29976
29977 @itemize @bullet
29978 @item
29979 You cannot link your Ada code with an object or library generated with
29980 Microsoft tools if these use the @code{.tls} section (Thread Local
29981 Storage section) since the GNAT linker does not yet support this section.
29982
29983 @item
29984 You cannot link your Ada code with an object or library generated with
29985 Microsoft tools if these use I/O routines other than those provided in
29986 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
29987 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
29988 libraries can cause a conflict with @code{msvcrt.dll} services. For
29989 instance Visual C++ I/O stream routines conflict with those in
29990 @code{msvcrt.dll}.
29991 @end itemize
29992
29993 @noindent
29994 If you do want to use the Microsoft tools for your non-Ada code and hit one
29995 of the above limitations, you have two choices:
29996
29997 @enumerate
29998 @item
29999 Encapsulate your non-Ada code in a DLL to be linked with your Ada
30000 application. In this case, use the Microsoft or whatever environment to
30001 build the DLL and use GNAT to build your executable
30002 (@pxref{Using DLLs with GNAT}).
30003
30004 @item
30005 Or you can encapsulate your Ada code in a DLL to be linked with the
30006 other part of your application. In this case, use GNAT to build the DLL
30007 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
30008 environment to build your executable.
30009 @end enumerate
30010
30011 @node Windows Calling Conventions
30012 @section Windows Calling Conventions
30013 @findex Stdcall
30014 @findex APIENTRY
30015
30016 @menu
30017 * C Calling Convention::
30018 * Stdcall Calling Convention::
30019 * Win32 Calling Convention::
30020 * DLL Calling Convention::
30021 @end menu
30022
30023 @noindent
30024 When a subprogram @code{F} (caller) calls a subprogram @code{G}
30025 (callee), there are several ways to push @code{G}'s parameters on the
30026 stack and there are several possible scenarios to clean up the stack
30027 upon @code{G}'s return. A calling convention is an agreed upon software
30028 protocol whereby the responsibilities between the caller (@code{F}) and
30029 the callee (@code{G}) are clearly defined. Several calling conventions
30030 are available for Windows:
30031
30032 @itemize @bullet
30033 @item
30034 @code{C} (Microsoft defined)
30035
30036 @item
30037 @code{Stdcall} (Microsoft defined)
30038
30039 @item
30040 @code{Win32} (GNAT specific)
30041
30042 @item
30043 @code{DLL} (GNAT specific)
30044 @end itemize
30045
30046 @node C Calling Convention
30047 @subsection @code{C} Calling Convention
30048
30049 @noindent
30050 This is the default calling convention used when interfacing to C/C++
30051 routines compiled with either @command{gcc} or Microsoft Visual C++.
30052
30053 In the @code{C} calling convention subprogram parameters are pushed on the
30054 stack by the caller from right to left. The caller itself is in charge of
30055 cleaning up the stack after the call. In addition, the name of a routine
30056 with @code{C} calling convention is mangled by adding a leading underscore.
30057
30058 The name to use on the Ada side when importing (or exporting) a routine
30059 with @code{C} calling convention is the name of the routine. For
30060 instance the C function:
30061
30062 @smallexample
30063 int get_val (long);
30064 @end smallexample
30065
30066 @noindent
30067 should be imported from Ada as follows:
30068
30069 @smallexample @c ada
30070 @group
30071 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30072 pragma Import (C, Get_Val, External_Name => "get_val");
30073 @end group
30074 @end smallexample
30075
30076 @noindent
30077 Note that in this particular case the @code{External_Name} parameter could
30078 have been omitted since, when missing, this parameter is taken to be the
30079 name of the Ada entity in lower case. When the @code{Link_Name} parameter
30080 is missing, as in the above example, this parameter is set to be the
30081 @code{External_Name} with a leading underscore.
30082
30083 When importing a variable defined in C, you should always use the @code{C}
30084 calling convention unless the object containing the variable is part of a
30085 DLL (in which case you should use the @code{Stdcall} calling
30086 convention, @pxref{Stdcall Calling Convention}).
30087
30088 @node Stdcall Calling Convention
30089 @subsection @code{Stdcall} Calling Convention
30090
30091 @noindent
30092 This convention, which was the calling convention used for Pascal
30093 programs, is used by Microsoft for all the routines in the Win32 API for
30094 efficiency reasons. It must be used to import any routine for which this
30095 convention was specified.
30096
30097 In the @code{Stdcall} calling convention subprogram parameters are pushed
30098 on the stack by the caller from right to left. The callee (and not the
30099 caller) is in charge of cleaning the stack on routine exit. In addition,
30100 the name of a routine with @code{Stdcall} calling convention is mangled by
30101 adding a leading underscore (as for the @code{C} calling convention) and a
30102 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
30103 bytes) of the parameters passed to the routine.
30104
30105 The name to use on the Ada side when importing a C routine with a
30106 @code{Stdcall} calling convention is the name of the C routine. The leading
30107 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
30108 the compiler. For instance the Win32 function:
30109
30110 @smallexample
30111 @b{APIENTRY} int get_val (long);
30112 @end smallexample
30113
30114 @noindent
30115 should be imported from Ada as follows:
30116
30117 @smallexample @c ada
30118 @group
30119 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30120 pragma Import (Stdcall, Get_Val);
30121 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
30122 @end group
30123 @end smallexample
30124
30125 @noindent
30126 As for the @code{C} calling convention, when the @code{External_Name}
30127 parameter is missing, it is taken to be the name of the Ada entity in lower
30128 case. If instead of writing the above import pragma you write:
30129
30130 @smallexample @c ada
30131 @group
30132 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30133 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
30134 @end group
30135 @end smallexample
30136
30137 @noindent
30138 then the imported routine is @code{_retrieve_val@@4}. However, if instead
30139 of specifying the @code{External_Name} parameter you specify the
30140 @code{Link_Name} as in the following example:
30141
30142 @smallexample @c ada
30143 @group
30144 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30145 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
30146 @end group
30147 @end smallexample
30148
30149 @noindent
30150 then the imported routine is @code{retrieve_val}, that is, there is no
30151 decoration at all. No leading underscore and no Stdcall suffix
30152 @code{@@}@code{@i{nn}}.
30153
30154 @noindent
30155 This is especially important as in some special cases a DLL's entry
30156 point name lacks a trailing @code{@@}@code{@i{nn}} while the exported
30157 name generated for a call has it.
30158
30159 @noindent
30160 It is also possible to import variables defined in a DLL by using an
30161 import pragma for a variable. As an example, if a DLL contains a
30162 variable defined as:
30163
30164 @smallexample
30165 int my_var;
30166 @end smallexample
30167
30168 @noindent
30169 then, to access this variable from Ada you should write:
30170
30171 @smallexample @c ada
30172 @group
30173 My_Var : Interfaces.C.int;
30174 pragma Import (Stdcall, My_Var);
30175 @end group
30176 @end smallexample
30177
30178 @noindent
30179 Note that to ease building cross-platform bindings this convention
30180 will be handled as a @code{C} calling convention on non-Windows platforms.
30181
30182 @node Win32 Calling Convention
30183 @subsection @code{Win32} Calling Convention
30184
30185 @noindent
30186 This convention, which is GNAT-specific is fully equivalent to the
30187 @code{Stdcall} calling convention described above.
30188
30189 @node DLL Calling Convention
30190 @subsection @code{DLL} Calling Convention
30191
30192 @noindent
30193 This convention, which is GNAT-specific is fully equivalent to the
30194 @code{Stdcall} calling convention described above.
30195
30196 @node Introduction to Dynamic Link Libraries (DLLs)
30197 @section Introduction to Dynamic Link Libraries (DLLs)
30198 @findex DLL
30199
30200 @noindent
30201 A Dynamically Linked Library (DLL) is a library that can be shared by
30202 several applications running under Windows. A DLL can contain any number of
30203 routines and variables.
30204
30205 One advantage of DLLs is that you can change and enhance them without
30206 forcing all the applications that depend on them to be relinked or
30207 recompiled. However, you should be aware than all calls to DLL routines are
30208 slower since, as you will understand below, such calls are indirect.
30209
30210 To illustrate the remainder of this section, suppose that an application
30211 wants to use the services of a DLL @file{API.dll}. To use the services
30212 provided by @file{API.dll} you must statically link against the DLL or
30213 an import library which contains a jump table with an entry for each
30214 routine and variable exported by the DLL. In the Microsoft world this
30215 import library is called @file{API.lib}. When using GNAT this import
30216 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
30217 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
30218
30219 After you have linked your application with the DLL or the import library
30220 and you run your application, here is what happens:
30221
30222 @enumerate
30223 @item
30224 Your application is loaded into memory.
30225
30226 @item
30227 The DLL @file{API.dll} is mapped into the address space of your
30228 application. This means that:
30229
30230 @itemize @bullet
30231 @item
30232 The DLL will use the stack of the calling thread.
30233
30234 @item
30235 The DLL will use the virtual address space of the calling process.
30236
30237 @item
30238 The DLL will allocate memory from the virtual address space of the calling
30239 process.
30240
30241 @item
30242 Handles (pointers) can be safely exchanged between routines in the DLL
30243 routines and routines in the application using the DLL.
30244 @end itemize
30245
30246 @item
30247 The entries in the jump table (from the import library @file{libAPI.dll.a}
30248 or @file{API.lib} or automatically created when linking against a DLL)
30249 which is part of your application are initialized with the addresses
30250 of the routines and variables in @file{API.dll}.
30251
30252 @item
30253 If present in @file{API.dll}, routines @code{DllMain} or
30254 @code{DllMainCRTStartup} are invoked. These routines typically contain
30255 the initialization code needed for the well-being of the routines and
30256 variables exported by the DLL.
30257 @end enumerate
30258
30259 @noindent
30260 There is an additional point which is worth mentioning. In the Windows
30261 world there are two kind of DLLs: relocatable and non-relocatable
30262 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
30263 in the target application address space. If the addresses of two
30264 non-relocatable DLLs overlap and these happen to be used by the same
30265 application, a conflict will occur and the application will run
30266 incorrectly. Hence, when possible, it is always preferable to use and
30267 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
30268 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
30269 User's Guide) removes the debugging symbols from the DLL but the DLL can
30270 still be relocated.
30271
30272 As a side note, an interesting difference between Microsoft DLLs and
30273 Unix shared libraries, is the fact that on most Unix systems all public
30274 routines are exported by default in a Unix shared library, while under
30275 Windows it is possible (but not required) to list exported routines in
30276 a definition file (@pxref{The Definition File}).
30277
30278 @node Using DLLs with GNAT
30279 @section Using DLLs with GNAT
30280
30281 @menu
30282 * Creating an Ada Spec for the DLL Services::
30283 * Creating an Import Library::
30284 @end menu
30285
30286 @noindent
30287 To use the services of a DLL, say @file{API.dll}, in your Ada application
30288 you must have:
30289
30290 @enumerate
30291 @item
30292 The Ada spec for the routines and/or variables you want to access in
30293 @file{API.dll}. If not available this Ada spec must be built from the C/C++
30294 header files provided with the DLL.
30295
30296 @item
30297 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
30298 mentioned an import library is a statically linked library containing the
30299 import table which will be filled at load time to point to the actual
30300 @file{API.dll} routines. Sometimes you don't have an import library for the
30301 DLL you want to use. The following sections will explain how to build
30302 one. Note that this is optional.
30303
30304 @item
30305 The actual DLL, @file{API.dll}.
30306 @end enumerate
30307
30308 @noindent
30309 Once you have all the above, to compile an Ada application that uses the
30310 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
30311 you simply issue the command
30312
30313 @smallexample
30314 $ gnatmake my_ada_app -largs -lAPI
30315 @end smallexample
30316
30317 @noindent
30318 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
30319 tells the GNAT linker to look first for a library named @file{API.lib}
30320 (Microsoft-style name) and if not found for a libraries named
30321 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
30322 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
30323 contains the following pragma
30324
30325 @smallexample @c ada
30326 pragma Linker_Options ("-lAPI");
30327 @end smallexample
30328
30329 @noindent
30330 you do not have to add @option{-largs -lAPI} at the end of the
30331 @command{gnatmake} command.
30332
30333 If any one of the items above is missing you will have to create it
30334 yourself. The following sections explain how to do so using as an
30335 example a fictitious DLL called @file{API.dll}.
30336
30337 @node Creating an Ada Spec for the DLL Services
30338 @subsection Creating an Ada Spec for the DLL Services
30339
30340 @noindent
30341 A DLL typically comes with a C/C++ header file which provides the
30342 definitions of the routines and variables exported by the DLL. The Ada
30343 equivalent of this header file is a package spec that contains definitions
30344 for the imported entities. If the DLL you intend to use does not come with
30345 an Ada spec you have to generate one such spec yourself. For example if
30346 the header file of @file{API.dll} is a file @file{api.h} containing the
30347 following two definitions:
30348
30349 @smallexample
30350 @group
30351 @cartouche
30352 int some_var;
30353 int get (char *);
30354 @end cartouche
30355 @end group
30356 @end smallexample
30357
30358 @noindent
30359 then the equivalent Ada spec could be:
30360
30361 @smallexample @c ada
30362 @group
30363 @cartouche
30364 with Interfaces.C.Strings;
30365 package API is
30366    use Interfaces;
30367
30368    Some_Var : C.int;
30369    function Get (Str : C.Strings.Chars_Ptr) return C.int;
30370
30371 private
30372    pragma Import (C, Get);
30373    pragma Import (DLL, Some_Var);
30374 end API;
30375 @end cartouche
30376 @end group
30377 @end smallexample
30378
30379 @noindent
30380 Note that a variable is
30381 @strong{always imported with a Stdcall convention}. A function
30382 can have @code{C} or @code{Stdcall} convention.
30383 (@pxref{Windows Calling Conventions}).
30384
30385 @node Creating an Import Library
30386 @subsection Creating an Import Library
30387 @cindex Import library
30388
30389 @menu
30390 * The Definition File::
30391 * GNAT-Style Import Library::
30392 * Microsoft-Style Import Library::
30393 @end menu
30394
30395 @noindent
30396 If a Microsoft-style import library @file{API.lib} or a GNAT-style
30397 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
30398 with @file{API.dll} you can skip this section. You can also skip this
30399 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
30400 as in this case it is possible to link directly against the
30401 DLL. Otherwise read on.
30402
30403 @node The Definition File
30404 @subsubsection The Definition File
30405 @cindex Definition file
30406 @findex .def
30407
30408 @noindent
30409 As previously mentioned, and unlike Unix systems, the list of symbols
30410 that are exported from a DLL must be provided explicitly in Windows.
30411 The main goal of a definition file is precisely that: list the symbols
30412 exported by a DLL. A definition file (usually a file with a @code{.def}
30413 suffix) has the following structure:
30414
30415 @smallexample
30416 @group
30417 @cartouche
30418 [LIBRARY @i{name}]
30419 [DESCRIPTION @i{string}]
30420 EXPORTS
30421    @i{symbol1}
30422    @i{symbol2}
30423    @dots{}
30424 @end cartouche
30425 @end group
30426 @end smallexample
30427
30428 @table @code
30429 @item LIBRARY @i{name}
30430 This section, which is optional, gives the name of the DLL.
30431
30432 @item DESCRIPTION @i{string}
30433 This section, which is optional, gives a description string that will be
30434 embedded in the import library.
30435
30436 @item EXPORTS
30437 This section gives the list of exported symbols (procedures, functions or
30438 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
30439 section of @file{API.def} looks like:
30440
30441 @smallexample
30442 @group
30443 @cartouche
30444 EXPORTS
30445    some_var
30446    get
30447 @end cartouche
30448 @end group
30449 @end smallexample
30450 @end table
30451
30452 @noindent
30453 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
30454 (@pxref{Windows Calling Conventions}) for a Stdcall
30455 calling convention function in the exported symbols list.
30456
30457 @noindent
30458 There can actually be other sections in a definition file, but these
30459 sections are not relevant to the discussion at hand.
30460
30461 @node GNAT-Style Import Library
30462 @subsubsection GNAT-Style Import Library
30463
30464 @noindent
30465 To create a static import library from @file{API.dll} with the GNAT tools
30466 you should proceed as follows:
30467
30468 @enumerate
30469 @item
30470 Create the definition file @file{API.def} (@pxref{The Definition File}).
30471 For that use the @code{dll2def} tool as follows:
30472
30473 @smallexample
30474 $ dll2def API.dll > API.def
30475 @end smallexample
30476
30477 @noindent
30478 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
30479 to standard output the list of entry points in the DLL. Note that if
30480 some routines in the DLL have the @code{Stdcall} convention
30481 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
30482 suffix then you'll have to edit @file{api.def} to add it, and specify
30483 @option{-k} to @command{gnatdll} when creating the import library.
30484
30485 @noindent
30486 Here are some hints to find the right @code{@@}@i{nn} suffix.
30487
30488 @enumerate
30489 @item
30490 If you have the Microsoft import library (.lib), it is possible to get
30491 the right symbols by using Microsoft @code{dumpbin} tool (see the
30492 corresponding Microsoft documentation for further details).
30493
30494 @smallexample
30495 $ dumpbin /exports api.lib
30496 @end smallexample
30497
30498 @item
30499 If you have a message about a missing symbol at link time the compiler
30500 tells you what symbol is expected. You just have to go back to the
30501 definition file and add the right suffix.
30502 @end enumerate
30503
30504 @item
30505 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
30506 (@pxref{Using gnatdll}) as follows:
30507
30508 @smallexample
30509 $ gnatdll -e API.def -d API.dll
30510 @end smallexample
30511
30512 @noindent
30513 @code{gnatdll} takes as input a definition file @file{API.def} and the
30514 name of the DLL containing the services listed in the definition file
30515 @file{API.dll}. The name of the static import library generated is
30516 computed from the name of the definition file as follows: if the
30517 definition file name is @i{xyz}@code{.def}, the import library name will
30518 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
30519 @option{-e} could have been removed because the name of the definition
30520 file (before the ``@code{.def}'' suffix) is the same as the name of the
30521 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
30522 @end enumerate
30523
30524 @node Microsoft-Style Import Library
30525 @subsubsection Microsoft-Style Import Library
30526
30527 @noindent
30528 With GNAT you can either use a GNAT-style or Microsoft-style import
30529 library. A Microsoft import library is needed only if you plan to make an
30530 Ada DLL available to applications developed with Microsoft
30531 tools (@pxref{Mixed-Language Programming on Windows}).
30532
30533 To create a Microsoft-style import library for @file{API.dll} you
30534 should proceed as follows:
30535
30536 @enumerate
30537 @item
30538 Create the definition file @file{API.def} from the DLL. For this use either
30539 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
30540 tool (see the corresponding Microsoft documentation for further details).
30541
30542 @item
30543 Build the actual import library using Microsoft's @code{lib} utility:
30544
30545 @smallexample
30546 $ lib -machine:IX86 -def:API.def -out:API.lib
30547 @end smallexample
30548
30549 @noindent
30550 If you use the above command the definition file @file{API.def} must
30551 contain a line giving the name of the DLL:
30552
30553 @smallexample
30554 LIBRARY      "API"
30555 @end smallexample
30556
30557 @noindent
30558 See the Microsoft documentation for further details about the usage of
30559 @code{lib}.
30560 @end enumerate
30561
30562 @node Building DLLs with GNAT
30563 @section Building DLLs with GNAT
30564 @cindex DLLs, building
30565
30566 @noindent
30567 This section explain how to build DLLs using the GNAT built-in DLL
30568 support. With the following procedure it is straight forward to build
30569 and use DLLs with GNAT.
30570
30571 @enumerate
30572
30573 @item building object files
30574
30575 The first step is to build all objects files that are to be included
30576 into the DLL. This is done by using the standard @command{gnatmake} tool.
30577
30578 @item building the DLL
30579
30580 To build the DLL you must use @command{gcc}'s @option{-shared}
30581 option. It is quite simple to use this method:
30582
30583 @smallexample
30584 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
30585 @end smallexample
30586
30587 It is important to note that in this case all symbols found in the
30588 object files are automatically exported. It is possible to restrict
30589 the set of symbols to export by passing to @command{gcc} a definition
30590 file, @pxref{The Definition File}. For example:
30591
30592 @smallexample
30593 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
30594 @end smallexample
30595
30596 If you use a definition file you must export the elaboration procedures
30597 for every package that required one. Elaboration procedures are named
30598 using the package name followed by "_E".
30599
30600 @item preparing DLL to be used
30601
30602 For the DLL to be used by client programs the bodies must be hidden
30603 from it and the .ali set with read-only attribute. This is very important
30604 otherwise GNAT will recompile all packages and will not actually use
30605 the code in the DLL. For example:
30606
30607 @smallexample
30608 $ mkdir apilib
30609 $ copy *.ads *.ali api.dll apilib
30610 $ attrib +R apilib\*.ali
30611 @end smallexample
30612
30613 @end enumerate
30614
30615 At this point it is possible to use the DLL by directly linking
30616 against it. Note that you must use the GNAT shared runtime when using
30617 GNAT shared libraries. This is achieved by using @option{-shared} binder's
30618 option.
30619
30620 @smallexample
30621 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30622 @end smallexample
30623
30624 @node Building DLLs with GNAT Project files
30625 @section Building DLLs with GNAT Project files
30626 @cindex DLLs, building
30627
30628 @noindent
30629 There is nothing specific to Windows in the build process.
30630 @pxref{Library Projects}.
30631
30632 @noindent
30633 Due to a system limitation, it is not possible under Windows to create threads
30634 when inside the @code{DllMain} routine which is used for auto-initialization
30635 of shared libraries, so it is not possible to have library level tasks in SALs.
30636
30637 @node Building DLLs with gnatdll
30638 @section Building DLLs with gnatdll
30639 @cindex DLLs, building
30640
30641 @menu
30642 * Limitations When Using Ada DLLs from Ada::
30643 * Exporting Ada Entities::
30644 * Ada DLLs and Elaboration::
30645 * Ada DLLs and Finalization::
30646 * Creating a Spec for Ada DLLs::
30647 * Creating the Definition File::
30648 * Using gnatdll::
30649 @end menu
30650
30651 @noindent
30652 Note that it is preferred to use the built-in GNAT DLL support
30653 (@pxref{Building DLLs with GNAT}) or GNAT Project files
30654 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
30655
30656 This section explains how to build DLLs containing Ada code using
30657 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30658 remainder of this section.
30659
30660 The steps required to build an Ada DLL that is to be used by Ada as well as
30661 non-Ada applications are as follows:
30662
30663 @enumerate
30664 @item
30665 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
30666 @code{Stdcall} calling convention to avoid any Ada name mangling for the
30667 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
30668 skip this step if you plan to use the Ada DLL only from Ada applications.
30669
30670 @item
30671 Your Ada code must export an initialization routine which calls the routine
30672 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
30673 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
30674 routine exported by the Ada DLL must be invoked by the clients of the DLL
30675 to initialize the DLL.
30676
30677 @item
30678 When useful, the DLL should also export a finalization routine which calls
30679 routine @code{adafinal} generated by @command{gnatbind} to perform the
30680 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
30681 The finalization routine exported by the Ada DLL must be invoked by the
30682 clients of the DLL when the DLL services are no further needed.
30683
30684 @item
30685 You must provide a spec for the services exported by the Ada DLL in each
30686 of the programming languages to which you plan to make the DLL available.
30687
30688 @item
30689 You must provide a definition file listing the exported entities
30690 (@pxref{The Definition File}).
30691
30692 @item
30693 Finally you must use @code{gnatdll} to produce the DLL and the import
30694 library (@pxref{Using gnatdll}).
30695 @end enumerate
30696
30697 @noindent
30698 Note that a relocatable DLL stripped using the @code{strip}
30699 binutils tool will not be relocatable anymore. To build a DLL without
30700 debug information pass @code{-largs -s} to @code{gnatdll}. This
30701 restriction does not apply to a DLL built using a Library Project.
30702 @pxref{Library Projects}.
30703
30704 @node Limitations When Using Ada DLLs from Ada
30705 @subsection Limitations When Using Ada DLLs from Ada
30706
30707 @noindent
30708 When using Ada DLLs from Ada applications there is a limitation users
30709 should be aware of. Because on Windows the GNAT run time is not in a DLL of
30710 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
30711 each Ada DLL includes the services of the GNAT run time that are necessary
30712 to the Ada code inside the DLL. As a result, when an Ada program uses an
30713 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
30714 one in the main program.
30715
30716 It is therefore not possible to exchange GNAT run-time objects between the
30717 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
30718 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
30719 types, etc.
30720
30721 It is completely safe to exchange plain elementary, array or record types,
30722 Windows object handles, etc.
30723
30724 @node Exporting Ada Entities
30725 @subsection Exporting Ada Entities
30726 @cindex Export table
30727
30728 @noindent
30729 Building a DLL is a way to encapsulate a set of services usable from any
30730 application. As a result, the Ada entities exported by a DLL should be
30731 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
30732 any Ada name mangling. As an example here is an Ada package
30733 @code{API}, spec and body, exporting two procedures, a function, and a
30734 variable:
30735
30736 @smallexample @c ada
30737 @group
30738 @cartouche
30739 with Interfaces.C; use Interfaces;
30740 package API is
30741    Count : C.int := 0;
30742    function Factorial (Val : C.int) return C.int;
30743
30744    procedure Initialize_API;
30745    procedure Finalize_API;
30746    --  Initialization & Finalization routines. More in the next section.
30747 private
30748    pragma Export (C, Initialize_API);
30749    pragma Export (C, Finalize_API);
30750    pragma Export (C, Count);
30751    pragma Export (C, Factorial);
30752 end API;
30753 @end cartouche
30754 @end group
30755 @end smallexample
30756
30757 @smallexample @c ada
30758 @group
30759 @cartouche
30760 package body API is
30761    function Factorial (Val : C.int) return C.int is
30762       Fact : C.int := 1;
30763    begin
30764       Count := Count + 1;
30765       for K in 1 .. Val loop
30766          Fact := Fact * K;
30767       end loop;
30768       return Fact;
30769    end Factorial;
30770
30771    procedure Initialize_API is
30772       procedure Adainit;
30773       pragma Import (C, Adainit);
30774    begin
30775       Adainit;
30776    end Initialize_API;
30777
30778    procedure Finalize_API is
30779       procedure Adafinal;
30780       pragma Import (C, Adafinal);
30781    begin
30782       Adafinal;
30783    end Finalize_API;
30784 end API;
30785 @end cartouche
30786 @end group
30787 @end smallexample
30788
30789 @noindent
30790 If the Ada DLL you are building will only be used by Ada applications
30791 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
30792 convention. As an example, the previous package could be written as
30793 follows:
30794
30795 @smallexample @c ada
30796 @group
30797 @cartouche
30798 package API is
30799    Count : Integer := 0;
30800    function Factorial (Val : Integer) return Integer;
30801
30802    procedure Initialize_API;
30803    procedure Finalize_API;
30804    --  Initialization and Finalization routines.
30805 end API;
30806 @end cartouche
30807 @end group
30808 @end smallexample
30809
30810 @smallexample @c ada
30811 @group
30812 @cartouche
30813 package body API is
30814    function Factorial (Val : Integer) return Integer is
30815       Fact : Integer := 1;
30816    begin
30817       Count := Count + 1;
30818       for K in 1 .. Val loop
30819          Fact := Fact * K;
30820       end loop;
30821       return Fact;
30822    end Factorial;
30823
30824    @dots{}
30825    --  The remainder of this package body is unchanged.
30826 end API;
30827 @end cartouche
30828 @end group
30829 @end smallexample
30830
30831 @noindent
30832 Note that if you do not export the Ada entities with a @code{C} or
30833 @code{Stdcall} convention you will have to provide the mangled Ada names
30834 in the definition file of the Ada DLL
30835 (@pxref{Creating the Definition File}).
30836
30837 @node Ada DLLs and Elaboration
30838 @subsection Ada DLLs and Elaboration
30839 @cindex DLLs and elaboration
30840
30841 @noindent
30842 The DLL that you are building contains your Ada code as well as all the
30843 routines in the Ada library that are needed by it. The first thing a
30844 user of your DLL must do is elaborate the Ada code
30845 (@pxref{Elaboration Order Handling in GNAT}).
30846
30847 To achieve this you must export an initialization routine
30848 (@code{Initialize_API} in the previous example), which must be invoked
30849 before using any of the DLL services. This elaboration routine must call
30850 the Ada elaboration routine @code{adainit} generated by the GNAT binder
30851 (@pxref{Binding with Non-Ada Main Programs}). See the body of
30852 @code{Initialize_Api} for an example. Note that the GNAT binder is
30853 automatically invoked during the DLL build process by the @code{gnatdll}
30854 tool (@pxref{Using gnatdll}).
30855
30856 When a DLL is loaded, Windows systematically invokes a routine called
30857 @code{DllMain}. It would therefore be possible to call @code{adainit}
30858 directly from @code{DllMain} without having to provide an explicit
30859 initialization routine. Unfortunately, it is not possible to call
30860 @code{adainit} from the @code{DllMain} if your program has library level
30861 tasks because access to the @code{DllMain} entry point is serialized by
30862 the system (that is, only a single thread can execute ``through'' it at a
30863 time), which means that the GNAT run time will deadlock waiting for the
30864 newly created task to complete its initialization.
30865
30866 @node Ada DLLs and Finalization
30867 @subsection Ada DLLs and Finalization
30868 @cindex DLLs and finalization
30869
30870 @noindent
30871 When the services of an Ada DLL are no longer needed, the client code should
30872 invoke the DLL finalization routine, if available. The DLL finalization
30873 routine is in charge of releasing all resources acquired by the DLL. In the
30874 case of the Ada code contained in the DLL, this is achieved by calling
30875 routine @code{adafinal} generated by the GNAT binder
30876 (@pxref{Binding with Non-Ada Main Programs}).
30877 See the body of @code{Finalize_Api} for an
30878 example. As already pointed out the GNAT binder is automatically invoked
30879 during the DLL build process by the @code{gnatdll} tool
30880 (@pxref{Using gnatdll}).
30881
30882 @node Creating a Spec for Ada DLLs
30883 @subsection Creating a Spec for Ada DLLs
30884
30885 @noindent
30886 To use the services exported by the Ada DLL from another programming
30887 language (e.g.@: C), you have to translate the specs of the exported Ada
30888 entities in that language. For instance in the case of @code{API.dll},
30889 the corresponding C header file could look like:
30890
30891 @smallexample
30892 @group
30893 @cartouche
30894 extern int *_imp__count;
30895 #define count (*_imp__count)
30896 int factorial (int);
30897 @end cartouche
30898 @end group
30899 @end smallexample
30900
30901 @noindent
30902 It is important to understand that when building an Ada DLL to be used by
30903 other Ada applications, you need two different specs for the packages
30904 contained in the DLL: one for building the DLL and the other for using
30905 the DLL. This is because the @code{DLL} calling convention is needed to
30906 use a variable defined in a DLL, but when building the DLL, the variable
30907 must have either the @code{Ada} or @code{C} calling convention. As an
30908 example consider a DLL comprising the following package @code{API}:
30909
30910 @smallexample @c ada
30911 @group
30912 @cartouche
30913 package API is
30914    Count : Integer := 0;
30915    @dots{}
30916    --  Remainder of the package omitted.
30917 end API;
30918 @end cartouche
30919 @end group
30920 @end smallexample
30921
30922 @noindent
30923 After producing a DLL containing package @code{API}, the spec that
30924 must be used to import @code{API.Count} from Ada code outside of the
30925 DLL is:
30926
30927 @smallexample @c ada
30928 @group
30929 @cartouche
30930 package API is
30931    Count : Integer;
30932    pragma Import (DLL, Count);
30933 end API;
30934 @end cartouche
30935 @end group
30936 @end smallexample
30937
30938 @node Creating the Definition File
30939 @subsection Creating the Definition File
30940
30941 @noindent
30942 The definition file is the last file needed to build the DLL. It lists
30943 the exported symbols. As an example, the definition file for a DLL
30944 containing only package @code{API} (where all the entities are exported
30945 with a @code{C} calling convention) is:
30946
30947 @smallexample
30948 @group
30949 @cartouche
30950 EXPORTS
30951     count
30952     factorial
30953     finalize_api
30954     initialize_api
30955 @end cartouche
30956 @end group
30957 @end smallexample
30958
30959 @noindent
30960 If the @code{C} calling convention is missing from package @code{API},
30961 then the definition file contains the mangled Ada names of the above
30962 entities, which in this case are:
30963
30964 @smallexample
30965 @group
30966 @cartouche
30967 EXPORTS
30968     api__count
30969     api__factorial
30970     api__finalize_api
30971     api__initialize_api
30972 @end cartouche
30973 @end group
30974 @end smallexample
30975
30976 @node Using gnatdll
30977 @subsection Using @code{gnatdll}
30978 @findex gnatdll
30979
30980 @menu
30981 * gnatdll Example::
30982 * gnatdll behind the Scenes::
30983 * Using dlltool::
30984 @end menu
30985
30986 @noindent
30987 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
30988 and non-Ada sources that make up your DLL have been compiled.
30989 @code{gnatdll} is actually in charge of two distinct tasks: build the
30990 static import library for the DLL and the actual DLL. The form of the
30991 @code{gnatdll} command is
30992
30993 @smallexample
30994 @cartouche
30995 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
30996 @end cartouche
30997 @end smallexample
30998
30999 @noindent
31000 where @i{list-of-files} is a list of ALI and object files. The object
31001 file list must be the exact list of objects corresponding to the non-Ada
31002 sources whose services are to be included in the DLL. The ALI file list
31003 must be the exact list of ALI files for the corresponding Ada sources
31004 whose services are to be included in the DLL. If @i{list-of-files} is
31005 missing, only the static import library is generated.
31006
31007 @noindent
31008 You may specify any of the following switches to @code{gnatdll}:
31009
31010 @table @code
31011 @item -a[@var{address}]
31012 @cindex @option{-a} (@code{gnatdll})
31013 Build a non-relocatable DLL at @var{address}. If @var{address} is not
31014 specified the default address @var{0x11000000} will be used. By default,
31015 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
31016 advise the reader to build relocatable DLL.
31017
31018 @item -b @var{address}
31019 @cindex @option{-b} (@code{gnatdll})
31020 Set the relocatable DLL base address. By default the address is
31021 @code{0x11000000}.
31022
31023 @item -bargs @var{opts}
31024 @cindex @option{-bargs} (@code{gnatdll})
31025 Binder options. Pass @var{opts} to the binder.
31026
31027 @item -d @var{dllfile}
31028 @cindex @option{-d} (@code{gnatdll})
31029 @var{dllfile} is the name of the DLL. This switch must be present for
31030 @code{gnatdll} to do anything. The name of the generated import library is
31031 obtained algorithmically from @var{dllfile} as shown in the following
31032 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
31033 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
31034 by option @option{-e}) is obtained algorithmically from @var{dllfile}
31035 as shown in the following example:
31036 if @var{dllfile} is @code{xyz.dll}, the definition
31037 file used is @code{xyz.def}.
31038
31039 @item -e @var{deffile}
31040 @cindex @option{-e} (@code{gnatdll})
31041 @var{deffile} is the name of the definition file.
31042
31043 @item -g
31044 @cindex @option{-g} (@code{gnatdll})
31045 Generate debugging information. This information is stored in the object
31046 file and copied from there to the final DLL file by the linker,
31047 where it can be read by the debugger. You must use the
31048 @option{-g} switch if you plan on using the debugger or the symbolic
31049 stack traceback.
31050
31051 @item -h
31052 @cindex @option{-h} (@code{gnatdll})
31053 Help mode. Displays @code{gnatdll} switch usage information.
31054
31055 @item -Idir
31056 @cindex @option{-I} (@code{gnatdll})
31057 Direct @code{gnatdll} to search the @var{dir} directory for source and
31058 object files needed to build the DLL.
31059 (@pxref{Search Paths and the Run-Time Library (RTL)}).
31060
31061 @item -k
31062 @cindex @option{-k} (@code{gnatdll})
31063 Removes the @code{@@}@i{nn} suffix from the import library's exported
31064 names, but keeps them for the link names. You must specify this
31065 option if you want to use a @code{Stdcall} function in a DLL for which
31066 the @code{@@}@i{nn} suffix has been removed. This is the case for most
31067 of the Windows NT DLL for example. This option has no effect when
31068 @option{-n} option is specified.
31069
31070 @item -l @var{file}
31071 @cindex @option{-l} (@code{gnatdll})
31072 The list of ALI and object files used to build the DLL are listed in
31073 @var{file}, instead of being given in the command line. Each line in
31074 @var{file} contains the name of an ALI or object file.
31075
31076 @item -n
31077 @cindex @option{-n} (@code{gnatdll})
31078 No Import. Do not create the import library.
31079
31080 @item -q
31081 @cindex @option{-q} (@code{gnatdll})
31082 Quiet mode. Do not display unnecessary messages.
31083
31084 @item -v
31085 @cindex @option{-v} (@code{gnatdll})
31086 Verbose mode. Display extra information.
31087
31088 @item -largs @var{opts}
31089 @cindex @option{-largs} (@code{gnatdll})
31090 Linker options. Pass @var{opts} to the linker.
31091 @end table
31092
31093 @node gnatdll Example
31094 @subsubsection @code{gnatdll} Example
31095
31096 @noindent
31097 As an example the command to build a relocatable DLL from @file{api.adb}
31098 once @file{api.adb} has been compiled and @file{api.def} created is
31099
31100 @smallexample
31101 $ gnatdll -d api.dll api.ali
31102 @end smallexample
31103
31104 @noindent
31105 The above command creates two files: @file{libapi.dll.a} (the import
31106 library) and @file{api.dll} (the actual DLL). If you want to create
31107 only the DLL, just type:
31108
31109 @smallexample
31110 $ gnatdll -d api.dll -n api.ali
31111 @end smallexample
31112
31113 @noindent
31114 Alternatively if you want to create just the import library, type:
31115
31116 @smallexample
31117 $ gnatdll -d api.dll
31118 @end smallexample
31119
31120 @node gnatdll behind the Scenes
31121 @subsubsection @code{gnatdll} behind the Scenes
31122
31123 @noindent
31124 This section details the steps involved in creating a DLL. @code{gnatdll}
31125 does these steps for you. Unless you are interested in understanding what
31126 goes on behind the scenes, you should skip this section.
31127
31128 We use the previous example of a DLL containing the Ada package @code{API},
31129 to illustrate the steps necessary to build a DLL. The starting point is a
31130 set of objects that will make up the DLL and the corresponding ALI
31131 files. In the case of this example this means that @file{api.o} and
31132 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
31133 the following:
31134
31135 @enumerate
31136 @item
31137 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
31138 the information necessary to generate relocation information for the
31139 DLL.
31140
31141 @smallexample
31142 @group
31143 $ gnatbind -n api
31144 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
31145 @end group
31146 @end smallexample
31147
31148 @noindent
31149 In addition to the base file, the @command{gnatlink} command generates an
31150 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
31151 asks @command{gnatlink} to generate the routines @code{DllMain} and
31152 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
31153 is loaded into memory.
31154
31155 @item
31156 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
31157 export table (@file{api.exp}). The export table contains the relocation
31158 information in a form which can be used during the final link to ensure
31159 that the Windows loader is able to place the DLL anywhere in memory.
31160
31161 @smallexample
31162 @group
31163 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31164           --output-exp api.exp
31165 @end group
31166 @end smallexample
31167
31168 @item
31169 @code{gnatdll} builds the base file using the new export table. Note that
31170 @command{gnatbind} must be called once again since the binder generated file
31171 has been deleted during the previous call to @command{gnatlink}.
31172
31173 @smallexample
31174 @group
31175 $ gnatbind -n api
31176 $ gnatlink api -o api.jnk api.exp -mdll
31177       -Wl,--base-file,api.base
31178 @end group
31179 @end smallexample
31180
31181 @item
31182 @code{gnatdll} builds the new export table using the new base file and
31183 generates the DLL import library @file{libAPI.dll.a}.
31184
31185 @smallexample
31186 @group
31187 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31188           --output-exp api.exp --output-lib libAPI.a
31189 @end group
31190 @end smallexample
31191
31192 @item
31193 Finally @code{gnatdll} builds the relocatable DLL using the final export
31194 table.
31195
31196 @smallexample
31197 @group
31198 $ gnatbind -n api
31199 $ gnatlink api api.exp -o api.dll -mdll
31200 @end group
31201 @end smallexample
31202 @end enumerate
31203
31204 @node Using dlltool
31205 @subsubsection Using @code{dlltool}
31206
31207 @noindent
31208 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
31209 DLLs and static import libraries. This section summarizes the most
31210 common @code{dlltool} switches. The form of the @code{dlltool} command
31211 is
31212
31213 @smallexample
31214 $ dlltool [@var{switches}]
31215 @end smallexample
31216
31217 @noindent
31218 @code{dlltool} switches include:
31219
31220 @table @option
31221 @item --base-file @var{basefile}
31222 @cindex @option{--base-file} (@command{dlltool})
31223 Read the base file @var{basefile} generated by the linker. This switch
31224 is used to create a relocatable DLL.
31225
31226 @item --def @var{deffile}
31227 @cindex @option{--def} (@command{dlltool})
31228 Read the definition file.
31229
31230 @item --dllname @var{name}
31231 @cindex @option{--dllname} (@command{dlltool})
31232 Gives the name of the DLL. This switch is used to embed the name of the
31233 DLL in the static import library generated by @code{dlltool} with switch
31234 @option{--output-lib}.
31235
31236 @item -k
31237 @cindex @option{-k} (@command{dlltool})
31238 Kill @code{@@}@i{nn} from exported names
31239 (@pxref{Windows Calling Conventions}
31240 for a discussion about @code{Stdcall}-style symbols.
31241
31242 @item --help
31243 @cindex @option{--help} (@command{dlltool})
31244 Prints the @code{dlltool} switches with a concise description.
31245
31246 @item --output-exp @var{exportfile}
31247 @cindex @option{--output-exp} (@command{dlltool})
31248 Generate an export file @var{exportfile}. The export file contains the
31249 export table (list of symbols in the DLL) and is used to create the DLL.
31250
31251 @item --output-lib @i{libfile}
31252 @cindex @option{--output-lib} (@command{dlltool})
31253 Generate a static import library @var{libfile}.
31254
31255 @item -v
31256 @cindex @option{-v} (@command{dlltool})
31257 Verbose mode.
31258
31259 @item --as @i{assembler-name}
31260 @cindex @option{--as} (@command{dlltool})
31261 Use @i{assembler-name} as the assembler. The default is @code{as}.
31262 @end table
31263
31264 @node GNAT and Windows Resources
31265 @section GNAT and Windows Resources
31266 @cindex Resources, windows
31267
31268 @menu
31269 * Building Resources::
31270 * Compiling Resources::
31271 * Using Resources::
31272 @end menu
31273
31274 @noindent
31275 Resources are an easy way to add Windows specific objects to your
31276 application. The objects that can be added as resources include:
31277
31278 @itemize @bullet
31279 @item
31280 menus
31281
31282 @item
31283 accelerators
31284
31285 @item
31286 dialog boxes
31287
31288 @item
31289 string tables
31290
31291 @item
31292 bitmaps
31293
31294 @item
31295 cursors
31296
31297 @item
31298 icons
31299
31300 @item
31301 fonts
31302 @end itemize
31303
31304 @noindent
31305 This section explains how to build, compile and use resources.
31306
31307 @node Building Resources
31308 @subsection Building Resources
31309 @cindex Resources, building
31310
31311 @noindent
31312 A resource file is an ASCII file. By convention resource files have an
31313 @file{.rc} extension.
31314 The easiest way to build a resource file is to use Microsoft tools
31315 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
31316 @code{dlgedit.exe} to build dialogs.
31317 It is always possible to build an @file{.rc} file yourself by writing a
31318 resource script.
31319
31320 It is not our objective to explain how to write a resource file. A
31321 complete description of the resource script language can be found in the
31322 Microsoft documentation.
31323
31324 @node Compiling Resources
31325 @subsection Compiling Resources
31326 @findex rc
31327 @findex windres
31328 @cindex Resources, compiling
31329
31330 @noindent
31331 This section describes how to build a GNAT-compatible (COFF) object file
31332 containing the resources. This is done using the Resource Compiler
31333 @code{windres} as follows:
31334
31335 @smallexample
31336 $ windres -i myres.rc -o myres.o
31337 @end smallexample
31338
31339 @noindent
31340 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
31341 file. You can specify an alternate preprocessor (usually named
31342 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
31343 parameter. A list of all possible options may be obtained by entering
31344 the command @code{windres} @option{--help}.
31345
31346 It is also possible to use the Microsoft resource compiler @code{rc.exe}
31347 to produce a @file{.res} file (binary resource file). See the
31348 corresponding Microsoft documentation for further details. In this case
31349 you need to use @code{windres} to translate the @file{.res} file to a
31350 GNAT-compatible object file as follows:
31351
31352 @smallexample
31353 $ windres -i myres.res -o myres.o
31354 @end smallexample
31355
31356 @node Using Resources
31357 @subsection Using Resources
31358 @cindex Resources, using
31359
31360 @noindent
31361 To include the resource file in your program just add the
31362 GNAT-compatible object file for the resource(s) to the linker
31363 arguments. With @command{gnatmake} this is done by using the @option{-largs}
31364 option:
31365
31366 @smallexample
31367 $ gnatmake myprog -largs myres.o
31368 @end smallexample
31369
31370 @node Debugging a DLL
31371 @section Debugging a DLL
31372 @cindex DLL debugging
31373
31374 @menu
31375 * Program and DLL Both Built with GCC/GNAT::
31376 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
31377 @end menu
31378
31379 @noindent
31380 Debugging a DLL is similar to debugging a standard program. But
31381 we have to deal with two different executable parts: the DLL and the
31382 program that uses it. We have the following four possibilities:
31383
31384 @enumerate 1
31385 @item
31386 The program and the DLL are built with @code{GCC/GNAT}.
31387 @item
31388 The program is built with foreign tools and the DLL is built with
31389 @code{GCC/GNAT}.
31390 @item
31391 The program is built with @code{GCC/GNAT} and the DLL is built with
31392 foreign tools.
31393 @item
31394 @end enumerate
31395
31396 @noindent
31397 In this section we address only cases one and two above.
31398 There is no point in trying to debug
31399 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
31400 information in it. To do so you must use a debugger compatible with the
31401 tools suite used to build the DLL.
31402
31403 @node Program and DLL Both Built with GCC/GNAT
31404 @subsection Program and DLL Both Built with GCC/GNAT
31405
31406 @noindent
31407 This is the simplest case. Both the DLL and the program have @code{GDB}
31408 compatible debugging information. It is then possible to break anywhere in
31409 the process. Let's suppose here that the main procedure is named
31410 @code{ada_main} and that in the DLL there is an entry point named
31411 @code{ada_dll}.
31412
31413 @noindent
31414 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
31415 program must have been built with the debugging information (see GNAT -g
31416 switch). Here are the step-by-step instructions for debugging it:
31417
31418 @enumerate 1
31419 @item Launch @code{GDB} on the main program.
31420
31421 @smallexample
31422 $ gdb -nw ada_main
31423 @end smallexample
31424
31425 @item Start the program and stop at the beginning of the main procedure
31426
31427 @smallexample
31428 (gdb) start
31429 @end smallexample
31430
31431 @noindent
31432 This step is required to be able to set a breakpoint inside the DLL. As long
31433 as the program is not run, the DLL is not loaded. This has the
31434 consequence that the DLL debugging information is also not loaded, so it is not
31435 possible to set a breakpoint in the DLL.
31436
31437 @item Set a breakpoint inside the DLL
31438
31439 @smallexample
31440 (gdb) break ada_dll
31441 (gdb) cont
31442 @end smallexample
31443
31444 @end enumerate
31445
31446 @noindent
31447 At this stage a breakpoint is set inside the DLL. From there on
31448 you can use the standard approach to debug the whole program
31449 (@pxref{Running and Debugging Ada Programs}).
31450
31451 @ignore
31452 @c This used to work, probably because the DLLs were non-relocatable
31453 @c keep this section around until the problem is sorted out.
31454
31455 To break on the @code{DllMain} routine it is not possible to follow
31456 the procedure above. At the time the program stop on @code{ada_main}
31457 the @code{DllMain} routine as already been called. Either you can use
31458 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
31459
31460 @enumerate 1
31461 @item Launch @code{GDB} on the main program.
31462
31463 @smallexample
31464 $ gdb ada_main
31465 @end smallexample
31466
31467 @item Load DLL symbols
31468
31469 @smallexample
31470 (gdb) add-sym api.dll
31471 @end smallexample
31472
31473 @item Set a breakpoint inside the DLL
31474
31475 @smallexample
31476 (gdb) break ada_dll.adb:45
31477 @end smallexample
31478
31479 Note that at this point it is not possible to break using the routine symbol
31480 directly as the program is not yet running. The solution is to break
31481 on the proper line (break in @file{ada_dll.adb} line 45).
31482
31483 @item Start the program
31484
31485 @smallexample
31486 (gdb) run
31487 @end smallexample
31488
31489 @end enumerate
31490 @end ignore
31491
31492 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
31493 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
31494
31495 @menu
31496 * Debugging the DLL Directly::
31497 * Attaching to a Running Process::
31498 @end menu
31499
31500 @noindent
31501 In this case things are slightly more complex because it is not possible to
31502 start the main program and then break at the beginning to load the DLL and the
31503 associated DLL debugging information. It is not possible to break at the
31504 beginning of the program because there is no @code{GDB} debugging information,
31505 and therefore there is no direct way of getting initial control. This
31506 section addresses this issue by describing some methods that can be used
31507 to break somewhere in the DLL to debug it.
31508
31509 @noindent
31510 First suppose that the main procedure is named @code{main} (this is for
31511 example some C code built with Microsoft Visual C) and that there is a
31512 DLL named @code{test.dll} containing an Ada entry point named
31513 @code{ada_dll}.
31514
31515 @noindent
31516 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
31517 been built with debugging information (see GNAT -g option).
31518
31519 @node Debugging the DLL Directly
31520 @subsubsection Debugging the DLL Directly
31521
31522 @enumerate 1
31523 @item
31524 Find out the executable starting address
31525
31526 @smallexample
31527 $ objdump --file-header main.exe
31528 @end smallexample
31529
31530 The starting address is reported on the last line. For example:
31531
31532 @smallexample
31533 main.exe:     file format pei-i386
31534 architecture: i386, flags 0x0000010a:
31535 EXEC_P, HAS_DEBUG, D_PAGED
31536 start address 0x00401010
31537 @end smallexample
31538
31539 @item
31540 Launch the debugger on the executable.
31541
31542 @smallexample
31543 $ gdb main.exe
31544 @end smallexample
31545
31546 @item
31547 Set a breakpoint at the starting address, and launch the program.
31548
31549 @smallexample
31550 $ (gdb) break *0x00401010
31551 $ (gdb) run
31552 @end smallexample
31553
31554 The program will stop at the given address.
31555
31556 @item
31557 Set a breakpoint on a DLL subroutine.
31558
31559 @smallexample
31560 (gdb) break ada_dll.adb:45
31561 @end smallexample
31562
31563 Or if you want to break using a symbol on the DLL, you need first to
31564 select the Ada language (language used by the DLL).
31565
31566 @smallexample
31567 (gdb) set language ada
31568 (gdb) break ada_dll
31569 @end smallexample
31570
31571 @item
31572 Continue the program.
31573
31574 @smallexample
31575 (gdb) cont
31576 @end smallexample
31577
31578 @noindent
31579 This will run the program until it reaches the breakpoint that has been
31580 set. From that point you can use the standard way to debug a program
31581 as described in (@pxref{Running and Debugging Ada Programs}).
31582
31583 @end enumerate
31584
31585 @noindent
31586 It is also possible to debug the DLL by attaching to a running process.
31587
31588 @node Attaching to a Running Process
31589 @subsubsection Attaching to a Running Process
31590 @cindex DLL debugging, attach to process
31591
31592 @noindent
31593 With @code{GDB} it is always possible to debug a running process by
31594 attaching to it. It is possible to debug a DLL this way. The limitation
31595 of this approach is that the DLL must run long enough to perform the
31596 attach operation. It may be useful for instance to insert a time wasting
31597 loop in the code of the DLL to meet this criterion.
31598
31599 @enumerate 1
31600
31601 @item Launch the main program @file{main.exe}.
31602
31603 @smallexample
31604 $ main
31605 @end smallexample
31606
31607 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
31608 that the process PID for @file{main.exe} is 208.
31609
31610 @item Launch gdb.
31611
31612 @smallexample
31613 $ gdb
31614 @end smallexample
31615
31616 @item Attach to the running process to be debugged.
31617
31618 @smallexample
31619 (gdb) attach 208
31620 @end smallexample
31621
31622 @item Load the process debugging information.
31623
31624 @smallexample
31625 (gdb) symbol-file main.exe
31626 @end smallexample
31627
31628 @item Break somewhere in the DLL.
31629
31630 @smallexample
31631 (gdb) break ada_dll
31632 @end smallexample
31633
31634 @item Continue process execution.
31635
31636 @smallexample
31637 (gdb) cont
31638 @end smallexample
31639
31640 @end enumerate
31641
31642 @noindent
31643 This last step will resume the process execution, and stop at
31644 the breakpoint we have set. From there you can use the standard
31645 approach to debug a program as described in
31646 (@pxref{Running and Debugging Ada Programs}).
31647
31648 @node Setting Stack Size from gnatlink
31649 @section Setting Stack Size from @command{gnatlink}
31650
31651 @noindent
31652 It is possible to specify the program stack size at link time. On modern
31653 versions of Windows, starting with XP, this is mostly useful to set the size of
31654 the main stack (environment task). The other task stacks are set with pragma
31655 Storage_Size or with the @command{gnatbind -d} command.
31656
31657 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
31658 reserve size of individual tasks, the link-time stack size applies to all
31659 tasks, and pragma Storage_Size has no effect.
31660 In particular, Stack Overflow checks are made against this
31661 link-time specified size.
31662
31663 This setting can be done with
31664 @command{gnatlink} using either:
31665
31666 @itemize @bullet
31667
31668 @item using @option{-Xlinker} linker option
31669
31670 @smallexample
31671 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
31672 @end smallexample
31673
31674 This sets the stack reserve size to 0x10000 bytes and the stack commit
31675 size to 0x1000 bytes.
31676
31677 @item using @option{-Wl} linker option
31678
31679 @smallexample
31680 $ gnatlink hello -Wl,--stack=0x1000000
31681 @end smallexample
31682
31683 This sets the stack reserve size to 0x1000000 bytes. Note that with
31684 @option{-Wl} option it is not possible to set the stack commit size
31685 because the coma is a separator for this option.
31686
31687 @end itemize
31688
31689 @node Setting Heap Size from gnatlink
31690 @section Setting Heap Size from @command{gnatlink}
31691
31692 @noindent
31693 Under Windows systems, it is possible to specify the program heap size from
31694 @command{gnatlink} using either:
31695
31696 @itemize @bullet
31697
31698 @item using @option{-Xlinker} linker option
31699
31700 @smallexample
31701 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
31702 @end smallexample
31703
31704 This sets the heap reserve size to 0x10000 bytes and the heap commit
31705 size to 0x1000 bytes.
31706
31707 @item using @option{-Wl} linker option
31708
31709 @smallexample
31710 $ gnatlink hello -Wl,--heap=0x1000000
31711 @end smallexample
31712
31713 This sets the heap reserve size to 0x1000000 bytes. Note that with
31714 @option{-Wl} option it is not possible to set the heap commit size
31715 because the coma is a separator for this option.
31716
31717 @end itemize
31718
31719 @end ifset
31720
31721 @c **********************************
31722 @c * GNU Free Documentation License *
31723 @c **********************************
31724 @include fdl.texi
31725 @c GNU Free Documentation License
31726
31727 @node Index,,GNU Free Documentation License, Top
31728 @unnumbered Index
31729
31730 @printindex cp
31731
31732 @contents
31733 @c Put table of contents at end, otherwise it precedes the "title page" in
31734 @c the .txt version
31735 @c Edit the pdf file to move the contents to the beginning, after the title
31736 @c page
31737
31738 @bye