OSDN Git Service

* env.c [__alpha__ && __osf__] (AES_SOURCE): Define.
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.texi
1 f\input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c   GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com).   o
11 @c                                                                            o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
13
14 @setfilename gnat_ugn.info
15
16 @copying
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
18 Inc.
19
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.2 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts.  A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
26 @end copying
27
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
29 @c
30 @c                           GNAT_UGN Style Guide
31 @c
32 @c  1. Always put a @noindent on the line before the first paragraph
33 @c     after any of these commands:
34 @c
35 @c          @chapter
36 @c          @section
37 @c          @subsection
38 @c          @subsubsection
39 @c          @subsubsubsection
40 @c
41 @c          @end smallexample
42 @c          @end itemize
43 @c          @end enumerate
44 @c
45 @c  2. DO NOT use @example. Use @smallexample instead.
46 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c        context.  These can interfere with the readability of the texi
48 @c        source file.  Instead, use one of the following annotated
49 @c        @smallexample commands, and preprocess the texi file with the
50 @c        ada2texi tool (which generates appropriate highlighting):
51 @c        @smallexample @c ada
52 @c        @smallexample @c adanocomment
53 @c        @smallexample @c projectfile
54 @c     b) The "@c ada" markup will result in boldface for reserved words
55 @c        and italics for comments
56 @c     c) The "@c adanocomment" markup will result only in boldface for
57 @c        reserved words (comments are left alone)
58 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c        of reserved words include the new reserved words for project files
60 @c
61 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c     command must be preceded by two empty lines
63 @c
64 @c  4. The @item command should be on a line of its own if it is in an
65 @c     @itemize or @enumerate command.
66 @c
67 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
68 @c     or "ali".
69 @c
70 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
71 @c     cause the document build to fail.
72 @c
73 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c     This command inhibits page breaks, so long examples in a @cartouche can
75 @c     lead to large, ugly patches of empty space on a page.
76 @c
77 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c        or the unw flag set.  The unw flag covers topics for both Unix and
79 @c        Windows.
80 @c
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
82
83 @set NOW January 2007
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
89
90 @set FSFEDITION
91 @set EDITION GNAT
92 @set DEFAULTLANGUAGEVERSION Ada 2005
93 @set NONDEFAULTLANGUAGEVERSION Ada 95
94
95 @ifset unw
96 @set PLATFORM
97 @end ifset
98
99 @ifset vms
100 @set PLATFORM OpenVMS
101 @end ifset
102
103 @c @ovar(ARG)
104 @c ----------
105 @c The ARG is an optional argument.  To be used for macro arguments in
106 @c their documentation (@defmac).
107 @macro ovar{varname}
108 @r{[}@var{\varname\}@r{]}@c
109 @end macro
110
111 @settitle @value{EDITION} User's Guide @value{PLATFORM}
112 @dircategory GNU Ada tools
113 @direntry
114 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
115 @end direntry
116
117 @include gcc-common.texi
118
119 @setchapternewpage odd
120 @syncodeindex fn cp
121 @c %**end of header
122
123 @titlepage
124 @title @value{EDITION} User's Guide
125 @ifset vms
126 @sp 1
127 @flushright
128 @titlefont{@i{@value{PLATFORM}}}
129 @end flushright
130 @end ifset
131
132 @sp 2
133
134 @subtitle GNAT, The GNU Ada Compiler
135 @versionsubtitle
136 @author AdaCore
137
138 @page
139 @vskip 0pt plus 1filll
140
141 @insertcopying
142
143 @end titlepage
144
145 @ifnottex
146 @node Top, About This Guide, (dir), (dir)
147 @top @value{EDITION} User's Guide
148
149 @noindent
150 @value{EDITION} User's Guide @value{PLATFORM}
151
152 @noindent
153 GNAT, The GNU Ada Compiler@*
154 GCC version @value{version-GCC}@*
155
156 @noindent
157 AdaCore@*
158
159 @menu
160 * About This Guide::
161 * Getting Started with GNAT::
162 * The GNAT Compilation Model::
163 * Compiling Using gcc::
164 * Binding Using gnatbind::
165 * Linking Using gnatlink::
166 * The GNAT Make Program gnatmake::
167 * Improving Performance::
168 * Renaming Files Using gnatchop::
169 * Configuration Pragmas::
170 * Handling Arbitrary File Naming Conventions Using gnatname::
171 * GNAT Project Manager::
172 * The Cross-Referencing Tools gnatxref and gnatfind::
173 * The GNAT Pretty-Printer gnatpp::
174 * The GNAT Metric Tool gnatmetric::
175 * File Name Krunching Using gnatkr::
176 * Preprocessing Using gnatprep::
177 @ifset vms
178 * The GNAT Run-Time Library Builder gnatlbr::
179 @end ifset
180 * The GNAT Library Browser gnatls::
181 * Cleaning Up Using gnatclean::
182 @ifclear vms
183 * GNAT and Libraries::
184 * Using the GNU make Utility::
185 @end ifclear
186 * Memory Management Issues::
187 * Stack Related Facilities::
188 * Verifying Properties Using gnatcheck::
189 * Creating Sample Bodies Using gnatstub::
190 * Generating Ada Bindings for C and C++ headers::
191 * Other Utility Programs::
192 * Running and Debugging Ada Programs::
193 @ifclear vms
194 * Code Coverage and Profiling::
195 @end ifclear
196 @ifset vms
197 * Compatibility with HP Ada::
198 @end ifset
199 * Platform-Specific Information for the Run-Time Libraries::
200 * Example of Binder Output File::
201 * Elaboration Order Handling in GNAT::
202 * Conditional Compilation::
203 * Inline Assembler::
204 * Compatibility and Porting Guide::
205 @ifset unw
206 * Microsoft Windows Topics::
207 @end ifset
208 * GNU Free Documentation License::
209 * Index::
210
211  --- The Detailed Node Listing ---
212
213 About This Guide
214
215 * What This Guide Contains::
216 * What You Should Know before Reading This Guide::
217 * Related Information::
218 * Conventions::
219
220 Getting Started with GNAT
221
222 * Running GNAT::
223 * Running a Simple Ada Program::
224 * Running a Program with Multiple Units::
225 * Using the gnatmake Utility::
226 @ifset vms
227 * Editing with Emacs::
228 @end ifset
229 @ifclear vms
230 * Introduction to GPS::
231 @end ifclear
232
233 The GNAT Compilation Model
234
235 * Source Representation::
236 * Foreign Language Representation::
237 * File Naming Rules::
238 * Using Other File Names::
239 * Alternative File Naming Schemes::
240 * Generating Object Files::
241 * Source Dependencies::
242 * The Ada Library Information Files::
243 * Binding an Ada Program::
244 * Mixed Language Programming::
245 @ifclear vms
246 * Building Mixed Ada & C++ Programs::
247 * Comparison between GNAT and C/C++ Compilation Models::
248 @end ifclear
249 * Comparison between GNAT and Conventional Ada Library Models::
250 @ifset vms
251 * Placement of temporary files::
252 @end ifset
253
254 Foreign Language Representation
255
256 * Latin-1::
257 * Other 8-Bit Codes::
258 * Wide Character Encodings::
259
260 Compiling Ada Programs With gcc
261
262 * Compiling Programs::
263 * Switches for gcc::
264 * Search Paths and the Run-Time Library (RTL)::
265 * Order of Compilation Issues::
266 * Examples::
267
268 Switches for gcc
269
270 * Output and Error Message Control::
271 * Warning Message Control::
272 * Debugging and Assertion Control::
273 * Validity Checking::
274 * Style Checking::
275 * Run-Time Checks::
276 * Using gcc for Syntax Checking::
277 * Using gcc for Semantic Checking::
278 * Compiling Different Versions of Ada::
279 * Character Set Control::
280 * File Naming Control::
281 * Subprogram Inlining Control::
282 * Auxiliary Output Control::
283 * Debugging Control::
284 * Exception Handling Control::
285 * Units to Sources Mapping Files::
286 * Integrated Preprocessing::
287 @ifset vms
288 * Return Codes::
289 @end ifset
290
291 Binding Ada Programs With gnatbind
292
293 * Running gnatbind::
294 * Switches for gnatbind::
295 * Command-Line Access::
296 * Search Paths for gnatbind::
297 * Examples of gnatbind Usage::
298
299 Switches for gnatbind
300
301 * Consistency-Checking Modes::
302 * Binder Error Message Control::
303 * Elaboration Control::
304 * Output Control::
305 * Binding with Non-Ada Main Programs::
306 * Binding Programs with No Main Subprogram::
307
308 Linking Using gnatlink
309
310 * Running gnatlink::
311 * Switches for gnatlink::
312
313 The GNAT Make Program gnatmake
314
315 * Running gnatmake::
316 * Switches for gnatmake::
317 * Mode Switches for gnatmake::
318 * Notes on the Command Line::
319 * How gnatmake Works::
320 * Examples of gnatmake Usage::
321
322 Improving Performance
323 * Performance Considerations::
324 * Text_IO Suggestions::
325 * Reducing Size of Ada Executables with gnatelim::
326 * Reducing Size of Executables with unused subprogram/data elimination::
327
328 Performance Considerations
329 * Controlling Run-Time Checks::
330 * Use of Restrictions::
331 * Optimization Levels::
332 * Debugging Optimized Code::
333 * Inlining of Subprograms::
334 * Other Optimization Switches::
335 * Optimization and Strict Aliasing::
336 @ifset vms
337 * Coverage Analysis::
338 @end ifset
339
340 Reducing Size of Ada Executables with gnatelim
341 * About gnatelim::
342 * Running gnatelim::
343 * Correcting the List of Eliminate Pragmas::
344 * Making Your Executables Smaller::
345 * Summary of the gnatelim Usage Cycle::
346
347 Reducing Size of Executables with unused subprogram/data elimination
348 * About unused subprogram/data elimination::
349 * Compilation options::
350
351 Renaming Files Using gnatchop
352
353 * Handling Files with Multiple Units::
354 * Operating gnatchop in Compilation Mode::
355 * Command Line for gnatchop::
356 * Switches for gnatchop::
357 * Examples of gnatchop Usage::
358
359 Configuration Pragmas
360
361 * Handling of Configuration Pragmas::
362 * The Configuration Pragmas Files::
363
364 Handling Arbitrary File Naming Conventions Using gnatname
365
366 * Arbitrary File Naming Conventions::
367 * Running gnatname::
368 * Switches for gnatname::
369 * Examples of gnatname Usage::
370
371 GNAT Project Manager
372
373 * Introduction::
374 * Examples of Project Files::
375 * Project File Syntax::
376 * Objects and Sources in Project Files::
377 * Importing Projects::
378 * Project Extension::
379 * Project Hierarchy Extension::
380 * External References in Project Files::
381 * Packages in Project Files::
382 * Variables from Imported Projects::
383 * Naming Schemes::
384 * Library Projects::
385 * Stand-alone Library Projects::
386 * Switches Related to Project Files::
387 * Tools Supporting Project Files::
388 * An Extended Example::
389 * Project File Complete Syntax::
390
391 The Cross-Referencing Tools gnatxref and gnatfind
392
393 * gnatxref Switches::
394 * gnatfind Switches::
395 * Project Files for gnatxref and gnatfind::
396 * Regular Expressions in gnatfind and gnatxref::
397 * Examples of gnatxref Usage::
398 * Examples of gnatfind Usage::
399
400 The GNAT Pretty-Printer gnatpp
401
402 * Switches for gnatpp::
403 * Formatting Rules::
404
405 The GNAT Metrics Tool gnatmetric
406
407 * Switches for gnatmetric::
408
409 File Name Krunching Using gnatkr
410
411 * About gnatkr::
412 * Using gnatkr::
413 * Krunching Method::
414 * Examples of gnatkr Usage::
415
416 Preprocessing Using gnatprep
417 * Preprocessing Symbols::
418 * Using gnatprep::
419 * Switches for gnatprep::
420 * Form of Definitions File::
421 * Form of Input Text for gnatprep::
422
423 @ifset vms
424 The GNAT Run-Time Library Builder gnatlbr
425
426 * Running gnatlbr::
427 * Switches for gnatlbr::
428 * Examples of gnatlbr Usage::
429 @end ifset
430
431 The GNAT Library Browser gnatls
432
433 * Running gnatls::
434 * Switches for gnatls::
435 * Examples of gnatls Usage::
436
437 Cleaning Up Using gnatclean
438
439 * Running gnatclean::
440 * Switches for gnatclean::
441 @c * Examples of gnatclean Usage::
442
443 @ifclear vms
444
445 GNAT and Libraries
446
447 * Introduction to Libraries in GNAT::
448 * General Ada Libraries::
449 * Stand-alone Ada Libraries::
450 * Rebuilding the GNAT Run-Time Library::
451
452 Using the GNU make Utility
453
454 * Using gnatmake in a Makefile::
455 * Automatically Creating a List of Directories::
456 * Generating the Command Line Switches::
457 * Overcoming Command Line Length Limits::
458 @end ifclear
459
460 Memory Management Issues
461
462 * Some Useful Memory Pools::
463 * The GNAT Debug Pool Facility::
464 @ifclear vms
465 * The gnatmem Tool::
466 @end ifclear
467
468 Stack Related Facilities
469
470 * Stack Overflow Checking::
471 * Static Stack Usage Analysis::
472 * Dynamic Stack Usage Analysis::
473
474 Some Useful Memory Pools
475
476 The GNAT Debug Pool Facility
477
478 @ifclear vms
479 The gnatmem Tool
480
481 * Running gnatmem::
482 * Switches for gnatmem::
483 * Example of gnatmem Usage::
484 @end ifclear
485
486 Verifying Properties Using gnatcheck
487
488 * Format of the Report File::
489 * General gnatcheck Switches::
490 * gnatcheck Rule Options::
491 * Adding the Results of Compiler Checks to gnatcheck Output::
492 * Project-Wide Checks::
493 * Rule exemption::
494 * Predefined Rules::
495
496 Sample Bodies Using gnatstub
497
498 * Running gnatstub::
499 * Switches for gnatstub::
500
501 Other Utility Programs
502
503 * Using Other Utility Programs with GNAT::
504 * The External Symbol Naming Scheme of GNAT::
505 * Converting Ada Files to html with gnathtml::
506
507 @ifclear vms
508 Code Coverage and Profiling
509
510 * Code Coverage of Ada Programs using gcov::
511 * Profiling an Ada Program using gprof::
512 @end ifclear
513
514 Running and Debugging Ada Programs
515
516 * The GNAT Debugger GDB::
517 * Running GDB::
518 * Introduction to GDB Commands::
519 * Using Ada Expressions::
520 * Calling User-Defined Subprograms::
521 * Using the Next Command in a Function::
522 * Ada Exceptions::
523 * Ada Tasks::
524 * Debugging Generic Units::
525 * GNAT Abnormal Termination or Failure to Terminate::
526 * Naming Conventions for GNAT Source Files::
527 * Getting Internal Debugging Information::
528 * Stack Traceback::
529
530 @ifset vms
531 * LSE::
532 @end ifset
533
534 @ifset vms
535 Compatibility with HP Ada
536
537 * Ada Language Compatibility::
538 * Differences in the Definition of Package System::
539 * Language-Related Features::
540 * The Package STANDARD::
541 * The Package SYSTEM::
542 * Tasking and Task-Related Features::
543 * Pragmas and Pragma-Related Features::
544 * Library of Predefined Units::
545 * Bindings::
546 * Main Program Definition::
547 * Implementation-Defined Attributes::
548 * Compiler and Run-Time Interfacing::
549 * Program Compilation and Library Management::
550 * Input-Output::
551 * Implementation Limits::
552 * Tools and Utilities::
553
554 Language-Related Features
555
556 * Integer Types and Representations::
557 * Floating-Point Types and Representations::
558 * Pragmas Float_Representation and Long_Float::
559 * Fixed-Point Types and Representations::
560 * Record and Array Component Alignment::
561 * Address Clauses::
562 * Other Representation Clauses::
563
564 Tasking and Task-Related Features
565
566 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
567 * Assigning Task IDs::
568 * Task IDs and Delays::
569 * Task-Related Pragmas::
570 * Scheduling and Task Priority::
571 * The Task Stack::
572 * External Interrupts::
573
574 Pragmas and Pragma-Related Features
575
576 * Restrictions on the Pragma INLINE::
577 * Restrictions on the Pragma INTERFACE::
578 * Restrictions on the Pragma SYSTEM_NAME::
579
580 Library of Predefined Units
581
582 * Changes to DECLIB::
583
584 Bindings
585
586 * Shared Libraries and Options Files::
587 * Interfaces to C::
588 @end ifset
589
590 Platform-Specific Information for the Run-Time Libraries
591
592 * Summary of Run-Time Configurations::
593 * Specifying a Run-Time Library::
594 * Choosing the Scheduling Policy::
595 * Solaris-Specific Considerations::
596 * Linux-Specific Considerations::
597 * AIX-Specific Considerations::
598 * Irix-Specific Considerations::
599
600 Example of Binder Output File
601
602 Elaboration Order Handling in GNAT
603
604 * Elaboration Code::
605 * Checking the Elaboration Order::
606 * Controlling the Elaboration Order::
607 * Controlling Elaboration in GNAT - Internal Calls::
608 * Controlling Elaboration in GNAT - External Calls::
609 * Default Behavior in GNAT - Ensuring Safety::
610 * Treatment of Pragma Elaborate::
611 * Elaboration Issues for Library Tasks::
612 * Mixing Elaboration Models::
613 * What to Do If the Default Elaboration Behavior Fails::
614 * Elaboration for Access-to-Subprogram Values::
615 * Summary of Procedures for Elaboration Control::
616 * Other Elaboration Order Considerations::
617
618 Conditional Compilation
619 * Use of Boolean Constants::
620 * Debugging - A Special Case::
621 * Conditionalizing Declarations::
622 * Use of Alternative Implementations::
623 * Preprocessing::
624
625 Inline Assembler
626
627 * Basic Assembler Syntax::
628 * A Simple Example of Inline Assembler::
629 * Output Variables in Inline Assembler::
630 * Input Variables in Inline Assembler::
631 * Inlining Inline Assembler Code::
632 * Other Asm Functionality::
633
634 Compatibility and Porting Guide
635
636 * Compatibility with Ada 83::
637 * Compatibility between Ada 95 and Ada 2005::
638 * Implementation-dependent characteristics::
639 @ifclear vms
640 @c This brief section is only in the non-VMS version
641 @c The complete chapter on HP Ada issues is in the VMS version
642 * Compatibility with HP Ada 83::
643 @end ifclear
644 * Compatibility with Other Ada Systems::
645 * Representation Clauses::
646 @ifset vms
647 * Transitioning to 64-Bit GNAT for OpenVMS::
648 @end ifset
649
650 @ifset unw
651 Microsoft Windows Topics
652
653 * Using GNAT on Windows::
654 * CONSOLE and WINDOWS subsystems::
655 * Temporary Files::
656 * Mixed-Language Programming on Windows::
657 * Windows Calling Conventions::
658 * Introduction to Dynamic Link Libraries (DLLs)::
659 * Using DLLs with GNAT::
660 * Building DLLs with GNAT::
661 * GNAT and Windows Resources::
662 * Debugging a DLL::
663 * Setting Stack Size from gnatlink::
664 * Setting Heap Size from gnatlink::
665 @end ifset
666
667 * Index::
668 @end menu
669 @end ifnottex
670
671 @node About This Guide
672 @unnumbered About This Guide
673
674 @noindent
675 @ifset vms
676 This guide describes the use of @value{EDITION},
677 a compiler and software development toolset for the full Ada
678 programming language, implemented on OpenVMS for HP's Alpha and
679 Integrity server (I64) platforms.
680 @end ifset
681 @ifclear vms
682 This guide describes the use of @value{EDITION},
683 a compiler and software development
684 toolset for the full Ada programming language.
685 @end ifclear
686 It documents the features of the compiler and tools, and explains
687 how to use them to build Ada applications.
688
689 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
690 Ada 83 compatibility mode.
691 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
692 but you can override with a compiler switch
693 (@pxref{Compiling Different Versions of Ada})
694 to explicitly specify the language version.
695 Throughout this manual, references to ``Ada'' without a year suffix
696 apply to both the Ada 95 and Ada 2005 versions of the language.
697
698
699 @ifclear FSFEDITION
700 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
701 ``GNAT'' in the remainder of this document.
702 @end ifclear
703
704
705
706
707 @menu
708 * What This Guide Contains::
709 * What You Should Know before Reading This Guide::
710 * Related Information::
711 * Conventions::
712 @end menu
713
714 @node What This Guide Contains
715 @unnumberedsec What This Guide Contains
716
717 @noindent
718 This guide contains the following chapters:
719 @itemize @bullet
720
721 @item
722 @ref{Getting Started with GNAT}, describes how to get started compiling
723 and running Ada programs with the GNAT Ada programming environment.
724 @item
725 @ref{The GNAT Compilation Model}, describes the compilation model used
726 by GNAT.
727
728 @item
729 @ref{Compiling Using gcc}, describes how to compile
730 Ada programs with @command{gcc}, the Ada compiler.
731
732 @item
733 @ref{Binding Using gnatbind}, describes how to
734 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
735 utility.
736
737 @item
738 @ref{Linking Using gnatlink},
739 describes @command{gnatlink}, a
740 program that provides for linking using the GNAT run-time library to
741 construct a program. @command{gnatlink} can also incorporate foreign language
742 object units into the executable.
743
744 @item
745 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
746 utility that automatically determines the set of sources
747 needed by an Ada compilation unit, and executes the necessary compilations
748 binding and link.
749
750 @item
751 @ref{Improving Performance}, shows various techniques for making your
752 Ada program run faster or take less space.
753 It discusses the effect of the compiler's optimization switch and
754 also describes the @command{gnatelim} tool and unused subprogram/data
755 elimination.
756
757 @item
758 @ref{Renaming Files Using gnatchop}, describes
759 @code{gnatchop}, a utility that allows you to preprocess a file that
760 contains Ada source code, and split it into one or more new files, one
761 for each compilation unit.
762
763 @item
764 @ref{Configuration Pragmas}, describes the configuration pragmas
765 handled by GNAT.
766
767 @item
768 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
769 shows how to override the default GNAT file naming conventions,
770 either for an individual unit or globally.
771
772 @item
773 @ref{GNAT Project Manager}, describes how to use project files
774 to organize large projects.
775
776 @item
777 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
778 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
779 way to navigate through sources.
780
781 @item
782 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
783 version of an Ada source file with control over casing, indentation,
784 comment placement, and other elements of program presentation style.
785
786 @item
787 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
788 metrics for an Ada source file, such as the number of types and subprograms,
789 and assorted complexity measures.
790
791 @item
792 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
793 file name krunching utility, used to handle shortened
794 file names on operating systems with a limit on the length of names.
795
796 @item
797 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
798 preprocessor utility that allows a single source file to be used to
799 generate multiple or parameterized source files by means of macro
800 substitution.
801
802 @ifset vms
803 @item
804 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
805 a tool for rebuilding the GNAT run time with user-supplied
806 configuration pragmas.
807 @end ifset
808
809 @item
810 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
811 utility that displays information about compiled units, including dependences
812 on the corresponding sources files, and consistency of compilations.
813
814 @item
815 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
816 to delete files that are produced by the compiler, binder and linker.
817
818 @ifclear vms
819 @item
820 @ref{GNAT and Libraries}, describes the process of creating and using
821 Libraries with GNAT. It also describes how to recompile the GNAT run-time
822 library.
823
824 @item
825 @ref{Using the GNU make Utility}, describes some techniques for using
826 the GNAT toolset in Makefiles.
827 @end ifclear
828
829 @item
830 @ref{Memory Management Issues}, describes some useful predefined storage pools
831 and in particular the GNAT Debug Pool facility, which helps detect incorrect
832 memory references.
833 @ifclear vms
834 It also describes @command{gnatmem}, a utility that monitors dynamic
835 allocation and deallocation and helps detect ``memory leaks''.
836 @end ifclear
837
838 @item
839 @ref{Stack Related Facilities}, describes some useful tools associated with
840 stack checking and analysis.
841
842 @item
843 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
844 a utility that checks Ada code against a set of rules.
845
846 @item
847 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
848 a utility that generates empty but compilable bodies for library units.
849
850 @item
851 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
852 generate automatically Ada bindings from C and C++ headers.
853
854 @item
855 @ref{Other Utility Programs}, discusses several other GNAT utilities,
856 including @code{gnathtml}.
857
858 @ifclear vms
859 @item
860 @ref{Code Coverage and Profiling}, describes how to perform a structural
861 coverage and profile the execution of Ada programs.
862 @end ifclear
863
864 @item
865 @ref{Running and Debugging Ada Programs}, describes how to run and debug
866 Ada programs.
867
868 @ifset vms
869 @item
870 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
871 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
872 developed by Digital Equipment Corporation and currently supported by HP.}
873 for OpenVMS Alpha. This product was formerly known as DEC Ada,
874 @cindex DEC Ada
875 and for
876 historical compatibility reasons, the relevant libraries still use the
877 DEC prefix.
878 @end ifset
879
880 @item
881 @ref{Platform-Specific Information for the Run-Time Libraries},
882 describes the various run-time
883 libraries supported by GNAT on various platforms and explains how to
884 choose a particular library.
885
886 @item
887 @ref{Example of Binder Output File}, shows the source code for the binder
888 output file for a sample program.
889
890 @item
891 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
892 you deal with elaboration order issues.
893
894 @item
895 @ref{Conditional Compilation}, describes how to model conditional compilation,
896 both with Ada in general and with GNAT facilities in particular.
897
898 @item
899 @ref{Inline Assembler}, shows how to use the inline assembly facility
900 in an Ada program.
901
902 @item
903 @ref{Compatibility and Porting Guide}, contains sections on compatibility
904 of GNAT with other Ada development environments (including Ada 83 systems),
905 to assist in porting code from those environments.
906
907 @ifset unw
908 @item
909 @ref{Microsoft Windows Topics}, presents information relevant to the
910 Microsoft Windows platform.
911 @end ifset
912 @end itemize
913
914 @c *************************************************
915 @node What You Should Know before Reading This Guide
916 @c *************************************************
917 @unnumberedsec What You Should Know before Reading This Guide
918
919 @cindex Ada 95 Language Reference Manual
920 @cindex Ada 2005 Language Reference Manual
921 @noindent
922 This guide assumes a basic familiarity with the Ada 95 language, as
923 described in the International Standard ANSI/ISO/IEC-8652:1995, January
924 1995.
925 It does not require knowledge of the new features introduced by Ada 2005,
926 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
927 and Amendment 1).
928 Both reference manuals are included in the GNAT documentation
929 package.
930
931 @node Related Information
932 @unnumberedsec Related Information
933
934 @noindent
935 For further information about related tools, refer to the following
936 documents:
937
938 @itemize @bullet
939 @item
940 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
941 Reference Manual}, which contains all reference material for the GNAT
942 implementation of Ada.
943
944 @ifset unw
945 @item
946 @cite{Using the GNAT Programming Studio}, which describes the GPS
947 Integrated Development Environment.
948
949 @item
950 @cite{GNAT Programming Studio Tutorial}, which introduces the
951 main GPS features through examples.
952 @end ifset
953
954 @item
955 @cite{Ada 95 Reference Manual}, which contains reference
956 material for the Ada 95 programming language.
957
958 @item
959 @cite{Ada 2005 Reference Manual}, which contains reference
960 material for the Ada 2005 programming language.
961
962 @item
963 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
964 @ifset vms
965 in the GNU:[DOCS] directory,
966 @end ifset
967 for all details on the use of the GNU source-level debugger.
968
969 @item
970 @xref{Top,, The extensible self-documenting text editor, emacs,
971 GNU Emacs Manual},
972 @ifset vms
973 located in the GNU:[DOCS] directory if the EMACS kit is installed,
974 @end ifset
975 for full information on the extensible editor and programming
976 environment Emacs.
977
978 @end itemize
979
980 @c **************
981 @node Conventions
982 @unnumberedsec Conventions
983 @cindex Conventions
984 @cindex Typographical conventions
985
986 @noindent
987 Following are examples of the typographical and graphic conventions used
988 in this guide:
989
990 @itemize @bullet
991 @item
992 @code{Functions}, @command{utility program names}, @code{standard names},
993 and @code{classes}.
994
995 @item
996 @option{Option flags}
997
998 @item
999 @file{File names}, @samp{button names}, and @samp{field names}.
1000
1001 @item
1002 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1003 variables}.
1004
1005 @item
1006 @emph{Emphasis}.
1007
1008 @item
1009 @r{[}optional information or parameters@r{]}
1010
1011 @item
1012 Examples are described by text
1013 @smallexample
1014 and then shown this way.
1015 @end smallexample
1016 @end itemize
1017
1018 @noindent
1019 Commands that are entered by the user are preceded in this manual by the
1020 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1021 uses this sequence as a prompt, then the commands will appear exactly as
1022 you see them in the manual. If your system uses some other prompt, then
1023 the command will appear with the @code{$} replaced by whatever prompt
1024 character you are using.
1025
1026 @ifset unw
1027 Full file names are shown with the ``@code{/}'' character
1028 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1029 If you are using GNAT on a Windows platform, please note that
1030 the ``@code{\}'' character should be used instead.
1031 @end ifset
1032
1033 @c ****************************
1034 @node Getting Started with GNAT
1035 @chapter Getting Started with GNAT
1036
1037 @noindent
1038 This chapter describes some simple ways of using GNAT to build
1039 executable Ada programs.
1040 @ifset unw
1041 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1042 show how to use the command line environment.
1043 @ref{Introduction to GPS}, provides a brief
1044 introduction to the GNAT Programming Studio, a visually-oriented
1045 Integrated Development Environment for GNAT.
1046 GPS offers a graphical ``look and feel'', support for development in
1047 other programming languages, comprehensive browsing features, and
1048 many other capabilities.
1049 For information on GPS please refer to
1050 @cite{Using the GNAT Programming Studio}.
1051 @end ifset
1052
1053 @menu
1054 * Running GNAT::
1055 * Running a Simple Ada Program::
1056 * Running a Program with Multiple Units::
1057 * Using the gnatmake Utility::
1058 @ifset vms
1059 * Editing with Emacs::
1060 @end ifset
1061 @ifclear vms
1062 * Introduction to GPS::
1063 @end ifclear
1064 @end menu
1065
1066 @node Running GNAT
1067 @section Running GNAT
1068
1069 @noindent
1070 Three steps are needed to create an executable file from an Ada source
1071 file:
1072
1073 @enumerate
1074 @item
1075 The source file(s) must be compiled.
1076 @item
1077 The file(s) must be bound using the GNAT binder.
1078 @item
1079 All appropriate object files must be linked to produce an executable.
1080 @end enumerate
1081
1082 @noindent
1083 All three steps are most commonly handled by using the @command{gnatmake}
1084 utility program that, given the name of the main program, automatically
1085 performs the necessary compilation, binding and linking steps.
1086
1087 @node Running a Simple Ada Program
1088 @section Running a Simple Ada Program
1089
1090 @noindent
1091 Any text editor may be used to prepare an Ada program.
1092 (If @code{Emacs} is
1093 used, the optional Ada mode may be helpful in laying out the program.)
1094 The
1095 program text is a normal text file. We will assume in our initial
1096 example that you have used your editor to prepare the following
1097 standard format text file:
1098
1099 @smallexample @c ada
1100 @cartouche
1101 with Ada.Text_IO; use Ada.Text_IO;
1102 procedure Hello is
1103 begin
1104    Put_Line ("Hello WORLD!");
1105 end Hello;
1106 @end cartouche
1107 @end smallexample
1108
1109 @noindent
1110 This file should be named @file{hello.adb}.
1111 With the normal default file naming conventions, GNAT requires
1112 that each file
1113 contain a single compilation unit whose file name is the
1114 unit name,
1115 with periods replaced by hyphens; the
1116 extension is @file{ads} for a
1117 spec and @file{adb} for a body.
1118 You can override this default file naming convention by use of the
1119 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1120 Alternatively, if you want to rename your files according to this default
1121 convention, which is probably more convenient if you will be using GNAT
1122 for all your compilations, then the @code{gnatchop} utility
1123 can be used to generate correctly-named source files
1124 (@pxref{Renaming Files Using gnatchop}).
1125
1126 You can compile the program using the following command (@code{$} is used
1127 as the command prompt in the examples in this document):
1128
1129 @smallexample
1130 $ gcc -c hello.adb
1131 @end smallexample
1132
1133 @noindent
1134 @command{gcc} is the command used to run the compiler. This compiler is
1135 capable of compiling programs in several languages, including Ada and
1136 C. It assumes that you have given it an Ada program if the file extension is
1137 either @file{.ads} or @file{.adb}, and it will then call
1138 the GNAT compiler to compile the specified file.
1139
1140 @ifclear vms
1141 The @option{-c} switch is required. It tells @command{gcc} to only do a
1142 compilation. (For C programs, @command{gcc} can also do linking, but this
1143 capability is not used directly for Ada programs, so the @option{-c}
1144 switch must always be present.)
1145 @end ifclear
1146
1147 This compile command generates a file
1148 @file{hello.o}, which is the object
1149 file corresponding to your Ada program. It also generates
1150 an ``Ada Library Information'' file @file{hello.ali},
1151 which contains additional information used to check
1152 that an Ada program is consistent.
1153 To build an executable file,
1154 use @code{gnatbind} to bind the program
1155 and @command{gnatlink} to link it. The
1156 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1157 @file{ALI} file, but the default extension of @file{.ali} can
1158 be omitted. This means that in the most common case, the argument
1159 is simply the name of the main program:
1160
1161 @smallexample
1162 $ gnatbind hello
1163 $ gnatlink hello
1164 @end smallexample
1165
1166 @noindent
1167 A simpler method of carrying out these steps is to use
1168 @command{gnatmake},
1169 a master program that invokes all the required
1170 compilation, binding and linking tools in the correct order. In particular,
1171 @command{gnatmake} automatically recompiles any sources that have been
1172 modified since they were last compiled, or sources that depend
1173 on such modified sources, so that ``version skew'' is avoided.
1174 @cindex Version skew (avoided by @command{gnatmake})
1175
1176 @smallexample
1177 $ gnatmake hello.adb
1178 @end smallexample
1179
1180 @noindent
1181 The result is an executable program called @file{hello}, which can be
1182 run by entering:
1183
1184 @smallexample
1185 $ ^hello^RUN HELLO^
1186 @end smallexample
1187
1188 @noindent
1189 assuming that the current directory is on the search path
1190 for executable programs.
1191
1192 @noindent
1193 and, if all has gone well, you will see
1194
1195 @smallexample
1196 Hello WORLD!
1197 @end smallexample
1198
1199 @noindent
1200 appear in response to this command.
1201
1202 @c ****************************************
1203 @node Running a Program with Multiple Units
1204 @section Running a Program with Multiple Units
1205
1206 @noindent
1207 Consider a slightly more complicated example that has three files: a
1208 main program, and the spec and body of a package:
1209
1210 @smallexample @c ada
1211 @cartouche
1212 @group
1213 package Greetings is
1214    procedure Hello;
1215    procedure Goodbye;
1216 end Greetings;
1217
1218 with Ada.Text_IO; use Ada.Text_IO;
1219 package body Greetings is
1220    procedure Hello is
1221    begin
1222       Put_Line ("Hello WORLD!");
1223    end Hello;
1224
1225    procedure Goodbye is
1226    begin
1227       Put_Line ("Goodbye WORLD!");
1228    end Goodbye;
1229 end Greetings;
1230 @end group
1231
1232 @group
1233 with Greetings;
1234 procedure Gmain is
1235 begin
1236    Greetings.Hello;
1237    Greetings.Goodbye;
1238 end Gmain;
1239 @end group
1240 @end cartouche
1241 @end smallexample
1242
1243 @noindent
1244 Following the one-unit-per-file rule, place this program in the
1245 following three separate files:
1246
1247 @table @file
1248 @item greetings.ads
1249 spec of package @code{Greetings}
1250
1251 @item greetings.adb
1252 body of package @code{Greetings}
1253
1254 @item gmain.adb
1255 body of main program
1256 @end table
1257
1258 @noindent
1259 To build an executable version of
1260 this program, we could use four separate steps to compile, bind, and link
1261 the program, as follows:
1262
1263 @smallexample
1264 $ gcc -c gmain.adb
1265 $ gcc -c greetings.adb
1266 $ gnatbind gmain
1267 $ gnatlink gmain
1268 @end smallexample
1269
1270 @noindent
1271 Note that there is no required order of compilation when using GNAT.
1272 In particular it is perfectly fine to compile the main program first.
1273 Also, it is not necessary to compile package specs in the case where
1274 there is an accompanying body; you only need to compile the body. If you want
1275 to submit these files to the compiler for semantic checking and not code
1276 generation, then use the
1277 @option{-gnatc} switch:
1278
1279 @smallexample
1280 $ gcc -c greetings.ads -gnatc
1281 @end smallexample
1282
1283 @noindent
1284 Although the compilation can be done in separate steps as in the
1285 above example, in practice it is almost always more convenient
1286 to use the @command{gnatmake} tool. All you need to know in this case
1287 is the name of the main program's source file. The effect of the above four
1288 commands can be achieved with a single one:
1289
1290 @smallexample
1291 $ gnatmake gmain.adb
1292 @end smallexample
1293
1294 @noindent
1295 In the next section we discuss the advantages of using @command{gnatmake} in
1296 more detail.
1297
1298 @c *****************************
1299 @node Using the gnatmake Utility
1300 @section Using the @command{gnatmake} Utility
1301
1302 @noindent
1303 If you work on a program by compiling single components at a time using
1304 @command{gcc}, you typically keep track of the units you modify. In order to
1305 build a consistent system, you compile not only these units, but also any
1306 units that depend on the units you have modified.
1307 For example, in the preceding case,
1308 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1309 you edit @file{greetings.ads}, you must recompile both
1310 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1311 units that depend on @file{greetings.ads}.
1312
1313 @code{gnatbind} will warn you if you forget one of these compilation
1314 steps, so that it is impossible to generate an inconsistent program as a
1315 result of forgetting to do a compilation. Nevertheless it is tedious and
1316 error-prone to keep track of dependencies among units.
1317 One approach to handle the dependency-bookkeeping is to use a
1318 makefile. However, makefiles present maintenance problems of their own:
1319 if the dependencies change as you change the program, you must make
1320 sure that the makefile is kept up-to-date manually, which is also an
1321 error-prone process.
1322
1323 The @command{gnatmake} utility takes care of these details automatically.
1324 Invoke it using either one of the following forms:
1325
1326 @smallexample
1327 $ gnatmake gmain.adb
1328 $ gnatmake ^gmain^GMAIN^
1329 @end smallexample
1330
1331 @noindent
1332 The argument is the name of the file containing the main program;
1333 you may omit the extension. @command{gnatmake}
1334 examines the environment, automatically recompiles any files that need
1335 recompiling, and binds and links the resulting set of object files,
1336 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1337 In a large program, it
1338 can be extremely helpful to use @command{gnatmake}, because working out by hand
1339 what needs to be recompiled can be difficult.
1340
1341 Note that @command{gnatmake}
1342 takes into account all the Ada rules that
1343 establish dependencies among units. These include dependencies that result
1344 from inlining subprogram bodies, and from
1345 generic instantiation. Unlike some other
1346 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1347 found by the compiler on a previous compilation, which may possibly
1348 be wrong when sources change. @command{gnatmake} determines the exact set of
1349 dependencies from scratch each time it is run.
1350
1351 @ifset vms
1352 @node Editing with Emacs
1353 @section Editing with Emacs
1354 @cindex Emacs
1355
1356 @noindent
1357 Emacs is an extensible self-documenting text editor that is available in a
1358 separate VMSINSTAL kit.
1359
1360 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1361 click on the Emacs Help menu and run the Emacs Tutorial.
1362 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1363 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1364
1365 Documentation on Emacs and other tools is available in Emacs under the
1366 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1367 use the middle mouse button to select a topic (e.g.@: Emacs).
1368
1369 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1370 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1371 get to the Emacs manual.
1372 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1373 prompt.
1374
1375 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1376 which is sufficiently extensible to provide for a complete programming
1377 environment and shell for the sophisticated user.
1378 @end ifset
1379
1380 @ifclear vms
1381 @node Introduction to GPS
1382 @section Introduction to GPS
1383 @cindex GPS (GNAT Programming Studio)
1384 @cindex GNAT Programming Studio (GPS)
1385 @noindent
1386 Although the command line interface (@command{gnatmake}, etc.) alone
1387 is sufficient, a graphical Interactive Development
1388 Environment can make it easier for you to compose, navigate, and debug
1389 programs.  This section describes the main features of GPS
1390 (``GNAT Programming Studio''), the GNAT graphical IDE.
1391 You will see how to use GPS to build and debug an executable, and
1392 you will also learn some of the basics of the GNAT ``project'' facility.
1393
1394 GPS enables you to do much more than is presented here;
1395 e.g., you can produce a call graph, interface to a third-party
1396 Version Control System, and inspect the generated assembly language
1397 for a program.
1398 Indeed, GPS also supports languages other than Ada.
1399 Such additional information, and an explanation of all of the GPS menu
1400 items. may be found in the on-line help, which includes
1401 a user's guide and a tutorial (these are also accessible from the GNAT
1402 startup menu).
1403
1404 @menu
1405 * Building a New Program with GPS::
1406 * Simple Debugging with GPS::
1407 @end menu
1408
1409 @node Building a New Program with GPS
1410 @subsection Building a New Program with GPS
1411 @noindent
1412 GPS invokes the GNAT compilation tools using information
1413 contained in a @emph{project} (also known as a @emph{project file}):
1414 a collection of properties such
1415 as source directories, identities of main subprograms, tool switches, etc.,
1416 and their associated values.
1417 See @ref{GNAT Project Manager} for details.
1418 In order to run GPS, you will need to either create a new project
1419 or else open an existing one.
1420
1421 This section will explain how you can use GPS to create a project,
1422 to associate Ada source files with a project, and to build and run
1423 programs.
1424
1425 @enumerate
1426 @item @emph{Creating a project}
1427
1428 Invoke GPS, either from the command line or the platform's IDE.
1429 After it starts, GPS will display a ``Welcome'' screen with three
1430 radio buttons:
1431
1432 @itemize @bullet
1433 @item
1434 @code{Start with default project in directory}
1435
1436 @item
1437 @code{Create new project with wizard}
1438
1439 @item
1440 @code{Open existing project}
1441 @end itemize
1442
1443 @noindent
1444 Select @code{Create new project with wizard} and press @code{OK}.
1445 A new window will appear.  In the text box labeled with
1446 @code{Enter the name of the project to create}, type @file{sample}
1447 as the project name.
1448 In the next box, browse to choose the directory in which you
1449 would like to create the project file.
1450 After selecting an appropriate directory, press @code{Forward}.
1451
1452 A window will appear with the title
1453 @code{Version Control System Configuration}.
1454 Simply press @code{Forward}.
1455
1456 A window will appear with the title
1457 @code{Please select the source directories for this project}.
1458 The directory that you specified for the project file will be selected
1459 by default as the one to use for sources; simply press @code{Forward}.
1460
1461 A window will appear with the title
1462 @code{Please select the build directory for this project}.
1463 The directory that you specified for the project file will be selected
1464 by default for object files and executables;
1465 simply press @code{Forward}.
1466
1467 A window will appear with the title
1468 @code{Please select the main units for this project}.
1469 You will supply this information later, after creating the source file.
1470 Simply press @code{Forward} for now.
1471
1472 A window will appear with the title
1473 @code{Please select the switches to build the project}.
1474 Press @code{Apply}.  This will create a project file named
1475 @file{sample.prj} in the directory that you had specified.
1476
1477 @item @emph{Creating and saving the source file}
1478
1479 After you create the new project, a GPS window will appear, which is
1480 partitioned into two main sections:
1481
1482 @itemize @bullet
1483 @item
1484 A @emph{Workspace area}, initially greyed out, which you will use for
1485 creating and editing source files
1486
1487 @item
1488 Directly below, a @emph{Messages area}, which initially displays a
1489 ``Welcome'' message.
1490 (If the Messages area is not visible, drag its border upward to expand it.)
1491 @end itemize
1492
1493 @noindent
1494 Select @code{File} on the menu bar, and then the @code{New} command.
1495 The Workspace area will become white, and you can now
1496 enter the source program explicitly.
1497 Type the following text
1498
1499 @smallexample @c ada
1500 @group
1501 with Ada.Text_IO; use Ada.Text_IO;
1502 procedure Hello is
1503 begin
1504   Put_Line("Hello from GPS!");
1505 end Hello;
1506 @end group
1507 @end smallexample
1508
1509 @noindent
1510 Select @code{File}, then @code{Save As}, and enter the source file name
1511 @file{hello.adb}.
1512 The file will be saved in the same directory you specified as the
1513 location of the default project file.
1514
1515 @item @emph{Updating the project file}
1516
1517 You need to add the new source file to the project.
1518 To do this, select
1519 the @code{Project} menu and then @code{Edit project properties}.
1520 Click the @code{Main files} tab on the left, and then the
1521 @code{Add} button.
1522 Choose @file{hello.adb} from the list, and press @code{Open}.
1523 The project settings window will reflect this action.
1524 Click @code{OK}.
1525
1526 @item @emph{Building and running the program}
1527
1528 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1529 and select @file{hello.adb}.
1530 The Messages window will display the resulting invocations of @command{gcc},
1531 @command{gnatbind}, and @command{gnatlink}
1532 (reflecting the default switch settings from the
1533 project file that you created) and then a ``successful compilation/build''
1534 message.
1535
1536 To run the program, choose the @code{Build} menu, then @code{Run}, and
1537 select @command{hello}.
1538 An @emph{Arguments Selection} window will appear.
1539 There are no command line arguments, so just click @code{OK}.
1540
1541 The Messages window will now display the program's output (the string
1542 @code{Hello from GPS}), and at the bottom of the GPS window a status
1543 update is displayed (@code{Run: hello}).
1544 Close the GPS window (or select @code{File}, then @code{Exit}) to
1545 terminate this GPS session.
1546 @end enumerate
1547
1548 @node Simple Debugging with GPS
1549 @subsection Simple Debugging with GPS
1550 @noindent
1551 This section illustrates basic debugging techniques (setting breakpoints,
1552 examining/modifying variables, single stepping).
1553
1554 @enumerate
1555 @item @emph{Opening a project}
1556
1557 Start GPS and select @code{Open existing project}; browse to
1558 specify the project file @file{sample.prj} that you had created in the
1559 earlier example.
1560
1561 @item @emph{Creating a source file}
1562
1563 Select @code{File}, then @code{New}, and type in the following program:
1564
1565 @smallexample @c ada
1566 @group
1567 with Ada.Text_IO; use Ada.Text_IO;
1568 procedure Example is
1569    Line : String (1..80);
1570    N    : Natural;
1571 begin
1572    Put_Line("Type a line of text at each prompt; an empty line to exit");
1573    loop
1574       Put(": ");
1575       Get_Line (Line, N);
1576       Put_Line (Line (1..N) );
1577       exit when N=0;
1578    end loop;
1579 end Example;
1580 @end group
1581 @end smallexample
1582
1583 @noindent
1584 Select @code{File}, then @code{Save as}, and enter the file name
1585 @file{example.adb}.
1586
1587 @item @emph{Updating the project file}
1588
1589 Add @code{Example} as a new main unit for the project:
1590 @enumerate a
1591 @item
1592 Select @code{Project}, then @code{Edit Project Properties}.
1593
1594 @item
1595 Select the @code{Main files} tab, click @code{Add}, then
1596 select the file @file{example.adb} from the list, and
1597 click @code{Open}.
1598 You will see the file name appear in the list of main units
1599
1600 @item
1601 Click @code{OK}
1602 @end enumerate
1603
1604 @item @emph{Building/running the executable}
1605
1606 To build the executable
1607 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1608
1609 Run the program to see its effect (in the Messages area).
1610 Each line that you enter is displayed; an empty line will
1611 cause the loop to exit and the program to terminate.
1612
1613 @item @emph{Debugging the program}
1614
1615 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1616 which are required for debugging, are on by default when you create
1617 a new project.
1618 Thus unless you intentionally remove these settings, you will be able
1619 to debug any program that you develop using GPS.
1620
1621 @enumerate a
1622 @item @emph{Initializing}
1623
1624 Select @code{Debug}, then @code{Initialize}, then @file{example}
1625
1626 @item @emph{Setting a breakpoint}
1627
1628 After performing the initialization step, you will observe a small
1629 icon to the right of each line number.
1630 This serves as a toggle for breakpoints; clicking the icon will
1631 set a breakpoint at the corresponding line (the icon will change to
1632 a red circle with an ``x''), and clicking it again
1633 will remove the breakpoint / reset the icon.
1634
1635 For purposes of this example, set a breakpoint at line 10 (the
1636 statement @code{Put_Line@ (Line@ (1..N));}
1637
1638 @item @emph{Starting program execution}
1639
1640 Select @code{Debug}, then @code{Run}.  When the
1641 @code{Program Arguments} window appears, click @code{OK}.
1642 A console window will appear; enter some line of text,
1643 e.g.@: @code{abcde}, at the prompt.
1644 The program will pause execution when it gets to the
1645 breakpoint, and the corresponding line is highlighted.
1646
1647 @item @emph{Examining a variable}
1648
1649 Move the mouse over one of the occurrences of the variable @code{N}.
1650 You will see the value (5) displayed, in ``tool tip'' fashion.
1651 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1652 You will see information about @code{N} appear in the @code{Debugger Data}
1653 pane, showing the value as 5.
1654
1655 @item @emph{Assigning a new value to a variable}
1656
1657 Right click on the @code{N} in the @code{Debugger Data} pane, and
1658 select @code{Set value of N}.
1659 When the input window appears, enter the value @code{4} and click
1660 @code{OK}.
1661 This value does not automatically appear in the @code{Debugger Data}
1662 pane; to see it, right click again on the @code{N} in the
1663 @code{Debugger Data} pane and select @code{Update value}.
1664 The new value, 4, will appear in red.
1665
1666 @item @emph{Single stepping}
1667
1668 Select @code{Debug}, then @code{Next}.
1669 This will cause the next statement to be executed, in this case the
1670 call of @code{Put_Line} with the string slice.
1671 Notice in the console window that the displayed string is simply
1672 @code{abcd} and not @code{abcde} which you had entered.
1673 This is because the upper bound of the slice is now 4 rather than 5.
1674
1675 @item @emph{Removing a breakpoint}
1676
1677 Toggle the breakpoint icon at line 10.
1678
1679 @item @emph{Resuming execution from a breakpoint}
1680
1681 Select @code{Debug}, then @code{Continue}.
1682 The program will reach the next iteration of the loop, and
1683 wait for input after displaying the prompt.
1684 This time, just hit the @kbd{Enter} key.
1685 The value of @code{N} will be 0, and the program will terminate.
1686 The console window will disappear.
1687 @end enumerate
1688 @end enumerate
1689 @end ifclear
1690
1691 @node The GNAT Compilation Model
1692 @chapter The GNAT Compilation Model
1693 @cindex GNAT compilation model
1694 @cindex Compilation model
1695
1696 @menu
1697 * Source Representation::
1698 * Foreign Language Representation::
1699 * File Naming Rules::
1700 * Using Other File Names::
1701 * Alternative File Naming Schemes::
1702 * Generating Object Files::
1703 * Source Dependencies::
1704 * The Ada Library Information Files::
1705 * Binding an Ada Program::
1706 * Mixed Language Programming::
1707 @ifclear vms
1708 * Building Mixed Ada & C++ Programs::
1709 * Comparison between GNAT and C/C++ Compilation Models::
1710 @end ifclear
1711 * Comparison between GNAT and Conventional Ada Library Models::
1712 @ifset vms
1713 * Placement of temporary files::
1714 @end ifset
1715 @end menu
1716
1717 @noindent
1718 This chapter describes the compilation model used by GNAT. Although
1719 similar to that used by other languages, such as C and C++, this model
1720 is substantially different from the traditional Ada compilation models,
1721 which are based on a library. The model is initially described without
1722 reference to the library-based model. If you have not previously used an
1723 Ada compiler, you need only read the first part of this chapter. The
1724 last section describes and discusses the differences between the GNAT
1725 model and the traditional Ada compiler models. If you have used other
1726 Ada compilers, this section will help you to understand those
1727 differences, and the advantages of the GNAT model.
1728
1729 @node Source Representation
1730 @section Source Representation
1731 @cindex Latin-1
1732
1733 @noindent
1734 Ada source programs are represented in standard text files, using
1735 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1736 7-bit ASCII set, plus additional characters used for
1737 representing foreign languages (@pxref{Foreign Language Representation}
1738 for support of non-USA character sets). The format effector characters
1739 are represented using their standard ASCII encodings, as follows:
1740
1741 @table @code
1742 @item VT
1743 @findex VT
1744 Vertical tab, @code{16#0B#}
1745
1746 @item HT
1747 @findex HT
1748 Horizontal tab, @code{16#09#}
1749
1750 @item CR
1751 @findex CR
1752 Carriage return, @code{16#0D#}
1753
1754 @item LF
1755 @findex LF
1756 Line feed, @code{16#0A#}
1757
1758 @item FF
1759 @findex FF
1760 Form feed, @code{16#0C#}
1761 @end table
1762
1763 @noindent
1764 Source files are in standard text file format. In addition, GNAT will
1765 recognize a wide variety of stream formats, in which the end of
1766 physical lines is marked by any of the following sequences:
1767 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1768 in accommodating files that are imported from other operating systems.
1769
1770 @cindex End of source file
1771 @cindex Source file, end
1772 @findex SUB
1773 The end of a source file is normally represented by the physical end of
1774 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1775 recognized as signalling the end of the source file. Again, this is
1776 provided for compatibility with other operating systems where this
1777 code is used to represent the end of file.
1778
1779 Each file contains a single Ada compilation unit, including any pragmas
1780 associated with the unit. For example, this means you must place a
1781 package declaration (a package @dfn{spec}) and the corresponding body in
1782 separate files. An Ada @dfn{compilation} (which is a sequence of
1783 compilation units) is represented using a sequence of files. Similarly,
1784 you will place each subunit or child unit in a separate file.
1785
1786 @node Foreign Language Representation
1787 @section Foreign Language Representation
1788
1789 @noindent
1790 GNAT supports the standard character sets defined in Ada as well as
1791 several other non-standard character sets for use in localized versions
1792 of the compiler (@pxref{Character Set Control}).
1793 @menu
1794 * Latin-1::
1795 * Other 8-Bit Codes::
1796 * Wide Character Encodings::
1797 @end menu
1798
1799 @node Latin-1
1800 @subsection Latin-1
1801 @cindex Latin-1
1802
1803 @noindent
1804 The basic character set is Latin-1. This character set is defined by ISO
1805 standard 8859, part 1. The lower half (character codes @code{16#00#}
1806 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1807 is used to represent additional characters. These include extended letters
1808 used by European languages, such as French accents, the vowels with umlauts
1809 used in German, and the extra letter A-ring used in Swedish.
1810
1811 @findex Ada.Characters.Latin_1
1812 For a complete list of Latin-1 codes and their encodings, see the source
1813 file of library unit @code{Ada.Characters.Latin_1} in file
1814 @file{a-chlat1.ads}.
1815 You may use any of these extended characters freely in character or
1816 string literals. In addition, the extended characters that represent
1817 letters can be used in identifiers.
1818
1819 @node Other 8-Bit Codes
1820 @subsection Other 8-Bit Codes
1821
1822 @noindent
1823 GNAT also supports several other 8-bit coding schemes:
1824
1825 @table @asis
1826 @item ISO 8859-2 (Latin-2)
1827 @cindex Latin-2
1828 @cindex ISO 8859-2
1829 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1830 equivalence.
1831
1832 @item ISO 8859-3 (Latin-3)
1833 @cindex Latin-3
1834 @cindex ISO 8859-3
1835 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1836 equivalence.
1837
1838 @item ISO 8859-4 (Latin-4)
1839 @cindex Latin-4
1840 @cindex ISO 8859-4
1841 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1842 equivalence.
1843
1844 @item ISO 8859-5 (Cyrillic)
1845 @cindex ISO 8859-5
1846 @cindex Cyrillic
1847 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1848 lowercase equivalence.
1849
1850 @item ISO 8859-15 (Latin-9)
1851 @cindex ISO 8859-15
1852 @cindex Latin-9
1853 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1854 lowercase equivalence
1855
1856 @item IBM PC (code page 437)
1857 @cindex code page 437
1858 This code page is the normal default for PCs in the U.S. It corresponds
1859 to the original IBM PC character set. This set has some, but not all, of
1860 the extended Latin-1 letters, but these letters do not have the same
1861 encoding as Latin-1. In this mode, these letters are allowed in
1862 identifiers with uppercase and lowercase equivalence.
1863
1864 @item IBM PC (code page 850)
1865 @cindex code page 850
1866 This code page is a modification of 437 extended to include all the
1867 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1868 mode, all these letters are allowed in identifiers with uppercase and
1869 lowercase equivalence.
1870
1871 @item Full Upper 8-bit
1872 Any character in the range 80-FF allowed in identifiers, and all are
1873 considered distinct. In other words, there are no uppercase and lowercase
1874 equivalences in this range. This is useful in conjunction with
1875 certain encoding schemes used for some foreign character sets (e.g.,
1876 the typical method of representing Chinese characters on the PC).
1877
1878 @item No Upper-Half
1879 No upper-half characters in the range 80-FF are allowed in identifiers.
1880 This gives Ada 83 compatibility for identifier names.
1881 @end table
1882
1883 @noindent
1884 For precise data on the encodings permitted, and the uppercase and lowercase
1885 equivalences that are recognized, see the file @file{csets.adb} in
1886 the GNAT compiler sources. You will need to obtain a full source release
1887 of GNAT to obtain this file.
1888
1889 @node Wide Character Encodings
1890 @subsection Wide Character Encodings
1891
1892 @noindent
1893 GNAT allows wide character codes to appear in character and string
1894 literals, and also optionally in identifiers, by means of the following
1895 possible encoding schemes:
1896
1897 @table @asis
1898
1899 @item Hex Coding
1900 In this encoding, a wide character is represented by the following five
1901 character sequence:
1902
1903 @smallexample
1904 ESC a b c d
1905 @end smallexample
1906
1907 @noindent
1908 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1909 characters (using uppercase letters) of the wide character code. For
1910 example, ESC A345 is used to represent the wide character with code
1911 @code{16#A345#}.
1912 This scheme is compatible with use of the full Wide_Character set.
1913
1914 @item Upper-Half Coding
1915 @cindex Upper-Half Coding
1916 The wide character with encoding @code{16#abcd#} where the upper bit is on
1917 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1918 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1919 character, but is not required to be in the upper half. This method can
1920 be also used for shift-JIS or EUC, where the internal coding matches the
1921 external coding.
1922
1923 @item Shift JIS Coding
1924 @cindex Shift JIS Coding
1925 A wide character is represented by a two-character sequence,
1926 @code{16#ab#} and
1927 @code{16#cd#}, with the restrictions described for upper-half encoding as
1928 described above. The internal character code is the corresponding JIS
1929 character according to the standard algorithm for Shift-JIS
1930 conversion. Only characters defined in the JIS code set table can be
1931 used with this encoding method.
1932
1933 @item EUC Coding
1934 @cindex EUC Coding
1935 A wide character is represented by a two-character sequence
1936 @code{16#ab#} and
1937 @code{16#cd#}, with both characters being in the upper half. The internal
1938 character code is the corresponding JIS character according to the EUC
1939 encoding algorithm. Only characters defined in the JIS code set table
1940 can be used with this encoding method.
1941
1942 @item UTF-8 Coding
1943 A wide character is represented using
1944 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1945 10646-1/Am.2. Depending on the character value, the representation
1946 is a one, two, or three byte sequence:
1947 @smallexample
1948 @iftex
1949 @leftskip=.7cm
1950 @end iftex
1951 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1952 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1953 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1954
1955 @end smallexample
1956
1957 @noindent
1958 where the @var{xxx} bits correspond to the left-padded bits of the
1959 16-bit character value. Note that all lower half ASCII characters
1960 are represented as ASCII bytes and all upper half characters and
1961 other wide characters are represented as sequences of upper-half
1962 (The full UTF-8 scheme allows for encoding 31-bit characters as
1963 6-byte sequences, but in this implementation, all UTF-8 sequences
1964 of four or more bytes length will be treated as illegal).
1965 @item Brackets Coding
1966 In this encoding, a wide character is represented by the following eight
1967 character sequence:
1968
1969 @smallexample
1970 [ " a b c d " ]
1971 @end smallexample
1972
1973 @noindent
1974 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1975 characters (using uppercase letters) of the wide character code. For
1976 example, [``A345''] is used to represent the wide character with code
1977 @code{16#A345#}. It is also possible (though not required) to use the
1978 Brackets coding for upper half characters. For example, the code
1979 @code{16#A3#} can be represented as @code{[``A3'']}.
1980
1981 This scheme is compatible with use of the full Wide_Character set,
1982 and is also the method used for wide character encoding in the standard
1983 ACVC (Ada Compiler Validation Capability) test suite distributions.
1984
1985 @end table
1986
1987 @noindent
1988 Note: Some of these coding schemes do not permit the full use of the
1989 Ada character set. For example, neither Shift JIS, nor EUC allow the
1990 use of the upper half of the Latin-1 set.
1991
1992 @node File Naming Rules
1993 @section File Naming Rules
1994
1995 @noindent
1996 The default file name is determined by the name of the unit that the
1997 file contains. The name is formed by taking the full expanded name of
1998 the unit and replacing the separating dots with hyphens and using
1999 ^lowercase^uppercase^ for all letters.
2000
2001 An exception arises if the file name generated by the above rules starts
2002 with one of the characters
2003 @ifset vms
2004 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2005 @end ifset
2006 @ifclear vms
2007 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2008 @end ifclear
2009 and the second character is a
2010 minus. In this case, the character ^tilde^dollar sign^ is used in place
2011 of the minus. The reason for this special rule is to avoid clashes with
2012 the standard names for child units of the packages System, Ada,
2013 Interfaces, and GNAT, which use the prefixes
2014 @ifset vms
2015 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2016 @end ifset
2017 @ifclear vms
2018 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2019 @end ifclear
2020 respectively.
2021
2022 The file extension is @file{.ads} for a spec and
2023 @file{.adb} for a body. The following list shows some
2024 examples of these rules.
2025
2026 @table @file
2027 @item main.ads
2028 Main (spec)
2029 @item main.adb
2030 Main (body)
2031 @item arith_functions.ads
2032 Arith_Functions (package spec)
2033 @item arith_functions.adb
2034 Arith_Functions (package body)
2035 @item func-spec.ads
2036 Func.Spec (child package spec)
2037 @item func-spec.adb
2038 Func.Spec (child package body)
2039 @item main-sub.adb
2040 Sub (subunit of Main)
2041 @item ^a~bad.adb^A$BAD.ADB^
2042 A.Bad (child package body)
2043 @end table
2044
2045 @noindent
2046 Following these rules can result in excessively long
2047 file names if corresponding
2048 unit names are long (for example, if child units or subunits are
2049 heavily nested). An option is available to shorten such long file names
2050 (called file name ``krunching''). This may be particularly useful when
2051 programs being developed with GNAT are to be used on operating systems
2052 with limited file name lengths. @xref{Using gnatkr}.
2053
2054 Of course, no file shortening algorithm can guarantee uniqueness over
2055 all possible unit names; if file name krunching is used, it is your
2056 responsibility to ensure no name clashes occur. Alternatively you
2057 can specify the exact file names that you want used, as described
2058 in the next section. Finally, if your Ada programs are migrating from a
2059 compiler with a different naming convention, you can use the gnatchop
2060 utility to produce source files that follow the GNAT naming conventions.
2061 (For details @pxref{Renaming Files Using gnatchop}.)
2062
2063 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2064 systems, case is not significant. So for example on @code{Windows XP}
2065 if the canonical name is @code{main-sub.adb}, you can use the file name
2066 @code{Main-Sub.adb} instead. However, case is significant for other
2067 operating systems, so for example, if you want to use other than
2068 canonically cased file names on a Unix system, you need to follow
2069 the procedures described in the next section.
2070
2071 @node Using Other File Names
2072 @section Using Other File Names
2073 @cindex File names
2074
2075 @noindent
2076 In the previous section, we have described the default rules used by
2077 GNAT to determine the file name in which a given unit resides. It is
2078 often convenient to follow these default rules, and if you follow them,
2079 the compiler knows without being explicitly told where to find all
2080 the files it needs.
2081
2082 However, in some cases, particularly when a program is imported from
2083 another Ada compiler environment, it may be more convenient for the
2084 programmer to specify which file names contain which units. GNAT allows
2085 arbitrary file names to be used by means of the Source_File_Name pragma.
2086 The form of this pragma is as shown in the following examples:
2087 @cindex Source_File_Name pragma
2088
2089 @smallexample @c ada
2090 @cartouche
2091 pragma Source_File_Name (My_Utilities.Stacks,
2092   Spec_File_Name => "myutilst_a.ada");
2093 pragma Source_File_name (My_Utilities.Stacks,
2094   Body_File_Name => "myutilst.ada");
2095 @end cartouche
2096 @end smallexample
2097
2098 @noindent
2099 As shown in this example, the first argument for the pragma is the unit
2100 name (in this example a child unit). The second argument has the form
2101 of a named association. The identifier
2102 indicates whether the file name is for a spec or a body;
2103 the file name itself is given by a string literal.
2104
2105 The source file name pragma is a configuration pragma, which means that
2106 normally it will be placed in the @file{gnat.adc}
2107 file used to hold configuration
2108 pragmas that apply to a complete compilation environment.
2109 For more details on how the @file{gnat.adc} file is created and used
2110 see @ref{Handling of Configuration Pragmas}.
2111 @cindex @file{gnat.adc}
2112
2113 @ifclear vms
2114 GNAT allows completely arbitrary file names to be specified using the
2115 source file name pragma. However, if the file name specified has an
2116 extension other than @file{.ads} or @file{.adb} it is necessary to use
2117 a special syntax when compiling the file. The name in this case must be
2118 preceded by the special sequence @option{-x} followed by a space and the name
2119 of the language, here @code{ada}, as in:
2120
2121 @smallexample
2122 $ gcc -c -x ada peculiar_file_name.sim
2123 @end smallexample
2124 @end ifclear
2125
2126 @noindent
2127 @command{gnatmake} handles non-standard file names in the usual manner (the
2128 non-standard file name for the main program is simply used as the
2129 argument to gnatmake). Note that if the extension is also non-standard,
2130 then it must be included in the @command{gnatmake} command, it may not
2131 be omitted.
2132
2133 @node Alternative File Naming Schemes
2134 @section Alternative File Naming Schemes
2135 @cindex File naming schemes, alternative
2136 @cindex File names
2137
2138 In the previous section, we described the use of the @code{Source_File_Name}
2139 pragma to allow arbitrary names to be assigned to individual source files.
2140 However, this approach requires one pragma for each file, and especially in
2141 large systems can result in very long @file{gnat.adc} files, and also create
2142 a maintenance problem.
2143
2144 GNAT also provides a facility for specifying systematic file naming schemes
2145 other than the standard default naming scheme previously described. An
2146 alternative scheme for naming is specified by the use of
2147 @code{Source_File_Name} pragmas having the following format:
2148 @cindex Source_File_Name pragma
2149
2150 @smallexample @c ada
2151 pragma Source_File_Name (
2152    Spec_File_Name  => FILE_NAME_PATTERN
2153  @r{[},Casing          => CASING_SPEC@r{]}
2154  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2155
2156 pragma Source_File_Name (
2157    Body_File_Name  => FILE_NAME_PATTERN
2158  @r{[},Casing          => CASING_SPEC@r{]}
2159  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2160
2161 pragma Source_File_Name (
2162    Subunit_File_Name  => FILE_NAME_PATTERN
2163  @r{[},Casing             => CASING_SPEC@r{]}
2164  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2165
2166 FILE_NAME_PATTERN ::= STRING_LITERAL
2167 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2168 @end smallexample
2169
2170 @noindent
2171 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2172 It contains a single asterisk character, and the unit name is substituted
2173 systematically for this asterisk. The optional parameter
2174 @code{Casing} indicates
2175 whether the unit name is to be all upper-case letters, all lower-case letters,
2176 or mixed-case. If no
2177 @code{Casing} parameter is used, then the default is all
2178 ^lower-case^upper-case^.
2179
2180 The optional @code{Dot_Replacement} string is used to replace any periods
2181 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2182 argument is used then separating dots appear unchanged in the resulting
2183 file name.
2184 Although the above syntax indicates that the
2185 @code{Casing} argument must appear
2186 before the @code{Dot_Replacement} argument, but it
2187 is also permissible to write these arguments in the opposite order.
2188
2189 As indicated, it is possible to specify different naming schemes for
2190 bodies, specs, and subunits. Quite often the rule for subunits is the
2191 same as the rule for bodies, in which case, there is no need to give
2192 a separate @code{Subunit_File_Name} rule, and in this case the
2193 @code{Body_File_name} rule is used for subunits as well.
2194
2195 The separate rule for subunits can also be used to implement the rather
2196 unusual case of a compilation environment (e.g.@: a single directory) which
2197 contains a subunit and a child unit with the same unit name. Although
2198 both units cannot appear in the same partition, the Ada Reference Manual
2199 allows (but does not require) the possibility of the two units coexisting
2200 in the same environment.
2201
2202 The file name translation works in the following steps:
2203
2204 @itemize @bullet
2205
2206 @item
2207 If there is a specific @code{Source_File_Name} pragma for the given unit,
2208 then this is always used, and any general pattern rules are ignored.
2209
2210 @item
2211 If there is a pattern type @code{Source_File_Name} pragma that applies to
2212 the unit, then the resulting file name will be used if the file exists. If
2213 more than one pattern matches, the latest one will be tried first, and the
2214 first attempt resulting in a reference to a file that exists will be used.
2215
2216 @item
2217 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2218 for which the corresponding file exists, then the standard GNAT default
2219 naming rules are used.
2220
2221 @end itemize
2222
2223 @noindent
2224 As an example of the use of this mechanism, consider a commonly used scheme
2225 in which file names are all lower case, with separating periods copied
2226 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2227 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2228 two pragmas appear:
2229
2230 @smallexample @c ada
2231 pragma Source_File_Name
2232   (Spec_File_Name => "*.1.ada");
2233 pragma Source_File_Name
2234   (Body_File_Name => "*.2.ada");
2235 @end smallexample
2236
2237 @noindent
2238 The default GNAT scheme is actually implemented by providing the following
2239 default pragmas internally:
2240
2241 @smallexample @c ada
2242 pragma Source_File_Name
2243   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2244 pragma Source_File_Name
2245   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2246 @end smallexample
2247
2248 @noindent
2249 Our final example implements a scheme typically used with one of the
2250 Ada 83 compilers, where the separator character for subunits was ``__''
2251 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2252 by adding @file{.ADA}, and subunits by
2253 adding @file{.SEP}. All file names were
2254 upper case. Child units were not present of course since this was an
2255 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2256 the same double underscore separator for child units.
2257
2258 @smallexample @c ada
2259 pragma Source_File_Name
2260   (Spec_File_Name => "*_.ADA",
2261    Dot_Replacement => "__",
2262    Casing = Uppercase);
2263 pragma Source_File_Name
2264   (Body_File_Name => "*.ADA",
2265    Dot_Replacement => "__",
2266    Casing = Uppercase);
2267 pragma Source_File_Name
2268   (Subunit_File_Name => "*.SEP",
2269    Dot_Replacement => "__",
2270    Casing = Uppercase);
2271 @end smallexample
2272
2273 @node Generating Object Files
2274 @section Generating Object Files
2275
2276 @noindent
2277 An Ada program consists of a set of source files, and the first step in
2278 compiling the program is to generate the corresponding object files.
2279 These are generated by compiling a subset of these source files.
2280 The files you need to compile are the following:
2281
2282 @itemize @bullet
2283 @item
2284 If a package spec has no body, compile the package spec to produce the
2285 object file for the package.
2286
2287 @item
2288 If a package has both a spec and a body, compile the body to produce the
2289 object file for the package. The source file for the package spec need
2290 not be compiled in this case because there is only one object file, which
2291 contains the code for both the spec and body of the package.
2292
2293 @item
2294 For a subprogram, compile the subprogram body to produce the object file
2295 for the subprogram. The spec, if one is present, is as usual in a
2296 separate file, and need not be compiled.
2297
2298 @item
2299 @cindex Subunits
2300 In the case of subunits, only compile the parent unit. A single object
2301 file is generated for the entire subunit tree, which includes all the
2302 subunits.
2303
2304 @item
2305 Compile child units independently of their parent units
2306 (though, of course, the spec of all the ancestor unit must be present in order
2307 to compile a child unit).
2308
2309 @item
2310 @cindex Generics
2311 Compile generic units in the same manner as any other units. The object
2312 files in this case are small dummy files that contain at most the
2313 flag used for elaboration checking. This is because GNAT always handles generic
2314 instantiation by means of macro expansion. However, it is still necessary to
2315 compile generic units, for dependency checking and elaboration purposes.
2316 @end itemize
2317
2318 @noindent
2319 The preceding rules describe the set of files that must be compiled to
2320 generate the object files for a program. Each object file has the same
2321 name as the corresponding source file, except that the extension is
2322 @file{.o} as usual.
2323
2324 You may wish to compile other files for the purpose of checking their
2325 syntactic and semantic correctness. For example, in the case where a
2326 package has a separate spec and body, you would not normally compile the
2327 spec. However, it is convenient in practice to compile the spec to make
2328 sure it is error-free before compiling clients of this spec, because such
2329 compilations will fail if there is an error in the spec.
2330
2331 GNAT provides an option for compiling such files purely for the
2332 purposes of checking correctness; such compilations are not required as
2333 part of the process of building a program. To compile a file in this
2334 checking mode, use the @option{-gnatc} switch.
2335
2336 @node Source Dependencies
2337 @section Source Dependencies
2338
2339 @noindent
2340 A given object file clearly depends on the source file which is compiled
2341 to produce it. Here we are using @dfn{depends} in the sense of a typical
2342 @code{make} utility; in other words, an object file depends on a source
2343 file if changes to the source file require the object file to be
2344 recompiled.
2345 In addition to this basic dependency, a given object may depend on
2346 additional source files as follows:
2347
2348 @itemize @bullet
2349 @item
2350 If a file being compiled @code{with}'s a unit @var{X}, the object file
2351 depends on the file containing the spec of unit @var{X}. This includes
2352 files that are @code{with}'ed implicitly either because they are parents
2353 of @code{with}'ed child units or they are run-time units required by the
2354 language constructs used in a particular unit.
2355
2356 @item
2357 If a file being compiled instantiates a library level generic unit, the
2358 object file depends on both the spec and body files for this generic
2359 unit.
2360
2361 @item
2362 If a file being compiled instantiates a generic unit defined within a
2363 package, the object file depends on the body file for the package as
2364 well as the spec file.
2365
2366 @item
2367 @findex Inline
2368 @cindex @option{-gnatn} switch
2369 If a file being compiled contains a call to a subprogram for which
2370 pragma @code{Inline} applies and inlining is activated with the
2371 @option{-gnatn} switch, the object file depends on the file containing the
2372 body of this subprogram as well as on the file containing the spec. Note
2373 that for inlining to actually occur as a result of the use of this switch,
2374 it is necessary to compile in optimizing mode.
2375
2376 @cindex @option{-gnatN} switch
2377 The use of @option{-gnatN} activates  inlining optimization
2378 that is performed by the front end of the compiler. This inlining does
2379 not require that the code generation be optimized. Like @option{-gnatn},
2380 the use of this switch generates additional dependencies.
2381
2382 When using a gcc-based back end (in practice this means using any version
2383 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2384 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2385 Historically front end inlining was more extensive than the gcc back end
2386 inlining, but that is no longer the case.
2387
2388 @item
2389 If an object file @file{O} depends on the proper body of a subunit through
2390 inlining or instantiation, it depends on the parent unit of the subunit.
2391 This means that any modification of the parent unit or one of its subunits
2392 affects the compilation of @file{O}.
2393
2394 @item
2395 The object file for a parent unit depends on all its subunit body files.
2396
2397 @item
2398 The previous two rules meant that for purposes of computing dependencies and
2399 recompilation, a body and all its subunits are treated as an indivisible whole.
2400
2401 @noindent
2402 These rules are applied transitively: if unit @code{A} @code{with}'s
2403 unit @code{B}, whose elaboration calls an inlined procedure in package
2404 @code{C}, the object file for unit @code{A} will depend on the body of
2405 @code{C}, in file @file{c.adb}.
2406
2407 The set of dependent files described by these rules includes all the
2408 files on which the unit is semantically dependent, as dictated by the
2409 Ada language standard. However, it is a superset of what the
2410 standard describes, because it includes generic, inline, and subunit
2411 dependencies.
2412
2413 An object file must be recreated by recompiling the corresponding source
2414 file if any of the source files on which it depends are modified. For
2415 example, if the @code{make} utility is used to control compilation,
2416 the rule for an Ada object file must mention all the source files on
2417 which the object file depends, according to the above definition.
2418 The determination of the necessary
2419 recompilations is done automatically when one uses @command{gnatmake}.
2420 @end itemize
2421
2422 @node The Ada Library Information Files
2423 @section The Ada Library Information Files
2424 @cindex Ada Library Information files
2425 @cindex @file{ALI} files
2426
2427 @noindent
2428 Each compilation actually generates two output files. The first of these
2429 is the normal object file that has a @file{.o} extension. The second is a
2430 text file containing full dependency information. It has the same
2431 name as the source file, but an @file{.ali} extension.
2432 This file is known as the Ada Library Information (@file{ALI}) file.
2433 The following information is contained in the @file{ALI} file.
2434
2435 @itemize @bullet
2436 @item
2437 Version information (indicates which version of GNAT was used to compile
2438 the unit(s) in question)
2439
2440 @item
2441 Main program information (including priority and time slice settings,
2442 as well as the wide character encoding used during compilation).
2443
2444 @item
2445 List of arguments used in the @command{gcc} command for the compilation
2446
2447 @item
2448 Attributes of the unit, including configuration pragmas used, an indication
2449 of whether the compilation was successful, exception model used etc.
2450
2451 @item
2452 A list of relevant restrictions applying to the unit (used for consistency)
2453 checking.
2454
2455 @item
2456 Categorization information (e.g.@: use of pragma @code{Pure}).
2457
2458 @item
2459 Information on all @code{with}'ed units, including presence of
2460 @code{Elaborate} or @code{Elaborate_All} pragmas.
2461
2462 @item
2463 Information from any @code{Linker_Options} pragmas used in the unit
2464
2465 @item
2466 Information on the use of @code{Body_Version} or @code{Version}
2467 attributes in the unit.
2468
2469 @item
2470 Dependency information. This is a list of files, together with
2471 time stamp and checksum information. These are files on which
2472 the unit depends in the sense that recompilation is required
2473 if any of these units are modified.
2474
2475 @item
2476 Cross-reference data. Contains information on all entities referenced
2477 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2478 provide cross-reference information.
2479
2480 @end itemize
2481
2482 @noindent
2483 For a full detailed description of the format of the @file{ALI} file,
2484 see the source of the body of unit @code{Lib.Writ}, contained in file
2485 @file{lib-writ.adb} in the GNAT compiler sources.
2486
2487 @node Binding an Ada Program
2488 @section Binding an Ada Program
2489
2490 @noindent
2491 When using languages such as C and C++, once the source files have been
2492 compiled the only remaining step in building an executable program
2493 is linking the object modules together. This means that it is possible to
2494 link an inconsistent version of a program, in which two units have
2495 included different versions of the same header.
2496
2497 The rules of Ada do not permit such an inconsistent program to be built.
2498 For example, if two clients have different versions of the same package,
2499 it is illegal to build a program containing these two clients.
2500 These rules are enforced by the GNAT binder, which also determines an
2501 elaboration order consistent with the Ada rules.
2502
2503 The GNAT binder is run after all the object files for a program have
2504 been created. It is given the name of the main program unit, and from
2505 this it determines the set of units required by the program, by reading the
2506 corresponding ALI files. It generates error messages if the program is
2507 inconsistent or if no valid order of elaboration exists.
2508
2509 If no errors are detected, the binder produces a main program, in Ada by
2510 default, that contains calls to the elaboration procedures of those
2511 compilation unit that require them, followed by
2512 a call to the main program. This Ada program is compiled to generate the
2513 object file for the main program. The name of
2514 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2515 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2516 main program unit.
2517
2518 Finally, the linker is used to build the resulting executable program,
2519 using the object from the main program from the bind step as well as the
2520 object files for the Ada units of the program.
2521
2522 @node Mixed Language Programming
2523 @section Mixed Language Programming
2524 @cindex Mixed Language Programming
2525
2526 @noindent
2527 This section describes how to develop a mixed-language program,
2528 specifically one that comprises units in both Ada and C.
2529
2530 @menu
2531 * Interfacing to C::
2532 * Calling Conventions::
2533 @end menu
2534
2535 @node Interfacing to C
2536 @subsection Interfacing to C
2537 @noindent
2538 Interfacing Ada with a foreign language such as C involves using
2539 compiler directives to import and/or export entity definitions in each
2540 language---using @code{extern} statements in C, for instance, and the
2541 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2542 A full treatment of these topics is provided in Appendix B, section 1
2543 of the Ada Reference Manual.
2544
2545 There are two ways to build a program using GNAT that contains some Ada
2546 sources and some foreign language sources, depending on whether or not
2547 the main subprogram is written in Ada.  Here is a source example with
2548 the main subprogram in Ada:
2549
2550 @smallexample
2551 /* file1.c */
2552 #include <stdio.h>
2553
2554 void print_num (int num)
2555 @{
2556   printf ("num is %d.\n", num);
2557   return;
2558 @}
2559
2560 /* file2.c */
2561
2562 /* num_from_Ada is declared in my_main.adb */
2563 extern int num_from_Ada;
2564
2565 int get_num (void)
2566 @{
2567   return num_from_Ada;
2568 @}
2569 @end smallexample
2570
2571 @smallexample @c ada
2572 --  my_main.adb
2573 procedure My_Main is
2574
2575    --  Declare then export an Integer entity called num_from_Ada
2576    My_Num : Integer := 10;
2577    pragma Export (C, My_Num, "num_from_Ada");
2578
2579    --  Declare an Ada function spec for Get_Num, then use
2580    --  C function get_num for the implementation.
2581    function Get_Num return Integer;
2582    pragma Import (C, Get_Num, "get_num");
2583
2584    --  Declare an Ada procedure spec for Print_Num, then use
2585    --  C function print_num for the implementation.
2586    procedure Print_Num (Num : Integer);
2587    pragma Import (C, Print_Num, "print_num");
2588
2589 begin
2590    Print_Num (Get_Num);
2591 end My_Main;
2592 @end smallexample
2593
2594 @enumerate
2595 @item
2596 To build this example, first compile the foreign language files to
2597 generate object files:
2598 @smallexample
2599 ^gcc -c file1.c^gcc -c FILE1.C^
2600 ^gcc -c file2.c^gcc -c FILE2.C^
2601 @end smallexample
2602
2603 @item
2604 Then, compile the Ada units to produce a set of object files and ALI
2605 files:
2606 @smallexample
2607 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2608 @end smallexample
2609
2610 @item
2611 Run the Ada binder on the Ada main program:
2612 @smallexample
2613 gnatbind my_main.ali
2614 @end smallexample
2615
2616 @item
2617 Link the Ada main program, the Ada objects and the other language
2618 objects:
2619 @smallexample
2620 gnatlink my_main.ali file1.o file2.o
2621 @end smallexample
2622 @end enumerate
2623
2624 The last three steps can be grouped in a single command:
2625 @smallexample
2626 gnatmake my_main.adb -largs file1.o file2.o
2627 @end smallexample
2628
2629 @cindex Binder output file
2630 @noindent
2631 If the main program is in a language other than Ada, then you may have
2632 more than one entry point into the Ada subsystem. You must use a special
2633 binder option to generate callable routines that initialize and
2634 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2635 Calls to the initialization and finalization routines must be inserted
2636 in the main program, or some other appropriate point in the code. The
2637 call to initialize the Ada units must occur before the first Ada
2638 subprogram is called, and the call to finalize the Ada units must occur
2639 after the last Ada subprogram returns. The binder will place the
2640 initialization and finalization subprograms into the
2641 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2642 sources.  To illustrate, we have the following example:
2643
2644 @smallexample
2645 /* main.c */
2646 extern void adainit (void);
2647 extern void adafinal (void);
2648 extern int add (int, int);
2649 extern int sub (int, int);
2650
2651 int main (int argc, char *argv[])
2652 @{
2653   int a = 21, b = 7;
2654
2655   adainit();
2656
2657   /* Should print "21 + 7 = 28" */
2658   printf ("%d + %d = %d\n", a, b, add (a, b));
2659   /* Should print "21 - 7 = 14" */
2660   printf ("%d - %d = %d\n", a, b, sub (a, b));
2661
2662   adafinal();
2663 @}
2664 @end smallexample
2665
2666 @smallexample @c ada
2667 --  unit1.ads
2668 package Unit1 is
2669    function Add (A, B : Integer) return Integer;
2670    pragma Export (C, Add, "add");
2671 end Unit1;
2672
2673 --  unit1.adb
2674 package body Unit1 is
2675    function Add (A, B : Integer) return Integer is
2676    begin
2677       return A + B;
2678    end Add;
2679 end Unit1;
2680
2681 --  unit2.ads
2682 package Unit2 is
2683    function Sub (A, B : Integer) return Integer;
2684    pragma Export (C, Sub, "sub");
2685 end Unit2;
2686
2687 --  unit2.adb
2688 package body Unit2 is
2689    function Sub (A, B : Integer) return Integer is
2690    begin
2691       return A - B;
2692    end Sub;
2693 end Unit2;
2694 @end smallexample
2695
2696 @enumerate
2697 @item
2698 The build procedure for this application is similar to the last
2699 example's.  First, compile the foreign language files to generate object
2700 files:
2701 @smallexample
2702 ^gcc -c main.c^gcc -c main.c^
2703 @end smallexample
2704
2705 @item
2706 Next, compile the Ada units to produce a set of object files and ALI
2707 files:
2708 @smallexample
2709 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2710 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2711 @end smallexample
2712
2713 @item
2714 Run the Ada binder on every generated ALI file.  Make sure to use the
2715 @option{-n} option to specify a foreign main program:
2716 @smallexample
2717 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2718 @end smallexample
2719
2720 @item
2721 Link the Ada main program, the Ada objects and the foreign language
2722 objects. You need only list the last ALI file here:
2723 @smallexample
2724 gnatlink unit2.ali main.o -o exec_file
2725 @end smallexample
2726
2727 This procedure yields a binary executable called @file{exec_file}.
2728 @end enumerate
2729
2730 @noindent
2731 Depending on the circumstances (for example when your non-Ada main object
2732 does not provide symbol @code{main}), you may also need to instruct the
2733 GNAT linker not to include the standard startup objects by passing the
2734 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2735
2736 @node Calling Conventions
2737 @subsection Calling Conventions
2738 @cindex Foreign Languages
2739 @cindex Calling Conventions
2740 GNAT follows standard calling sequence conventions and will thus interface
2741 to any other language that also follows these conventions. The following
2742 Convention identifiers are recognized by GNAT:
2743
2744 @table @code
2745 @cindex Interfacing to Ada
2746 @cindex Other Ada compilers
2747 @cindex Convention Ada
2748 @item Ada
2749 This indicates that the standard Ada calling sequence will be
2750 used and all Ada data items may be passed without any limitations in the
2751 case where GNAT is used to generate both the caller and callee. It is also
2752 possible to mix GNAT generated code and code generated by another Ada
2753 compiler. In this case, the data types should be restricted to simple
2754 cases, including primitive types. Whether complex data types can be passed
2755 depends on the situation. Probably it is safe to pass simple arrays, such
2756 as arrays of integers or floats. Records may or may not work, depending
2757 on whether both compilers lay them out identically. Complex structures
2758 involving variant records, access parameters, tasks, or protected types,
2759 are unlikely to be able to be passed.
2760
2761 Note that in the case of GNAT running
2762 on a platform that supports HP Ada 83, a higher degree of compatibility
2763 can be guaranteed, and in particular records are layed out in an identical
2764 manner in the two compilers. Note also that if output from two different
2765 compilers is mixed, the program is responsible for dealing with elaboration
2766 issues. Probably the safest approach is to write the main program in the
2767 version of Ada other than GNAT, so that it takes care of its own elaboration
2768 requirements, and then call the GNAT-generated adainit procedure to ensure
2769 elaboration of the GNAT components. Consult the documentation of the other
2770 Ada compiler for further details on elaboration.
2771
2772 However, it is not possible to mix the tasking run time of GNAT and
2773 HP Ada 83, All the tasking operations must either be entirely within
2774 GNAT compiled sections of the program, or entirely within HP Ada 83
2775 compiled sections of the program.
2776
2777 @cindex Interfacing to Assembly
2778 @cindex Convention Assembler
2779 @item Assembler
2780 Specifies assembler as the convention. In practice this has the
2781 same effect as convention Ada (but is not equivalent in the sense of being
2782 considered the same convention).
2783
2784 @cindex Convention Asm
2785 @findex Asm
2786 @item Asm
2787 Equivalent to Assembler.
2788
2789 @cindex Interfacing to COBOL
2790 @cindex Convention COBOL
2791 @findex COBOL
2792 @item COBOL
2793 Data will be passed according to the conventions described
2794 in section B.4 of the Ada Reference Manual.
2795
2796 @findex C
2797 @cindex Interfacing to C
2798 @cindex Convention C
2799 @item C
2800 Data will be passed according to the conventions described
2801 in section B.3 of the Ada Reference Manual.
2802
2803 A note on interfacing to a C ``varargs'' function:
2804 @findex C varargs function
2805 @cindex Interfacing to C varargs function
2806 @cindex varargs function interfaces
2807
2808 @itemize @bullet
2809 @item
2810 In C, @code{varargs} allows a function to take a variable number of
2811 arguments. There is no direct equivalent in this to Ada. One
2812 approach that can be used is to create a C wrapper for each
2813 different profile and then interface to this C wrapper. For
2814 example, to print an @code{int} value using @code{printf},
2815 create a C function @code{printfi} that takes two arguments, a
2816 pointer to a string and an int, and calls @code{printf}.
2817 Then in the Ada program, use pragma @code{Import} to
2818 interface to @code{printfi}.
2819
2820 @item
2821 It may work on some platforms to directly interface to
2822 a @code{varargs} function by providing a specific Ada profile
2823 for a particular call. However, this does not work on
2824 all platforms, since there is no guarantee that the
2825 calling sequence for a two argument normal C function
2826 is the same as for calling a @code{varargs} C function with
2827 the same two arguments.
2828 @end itemize
2829
2830 @cindex Convention Default
2831 @findex Default
2832 @item Default
2833 Equivalent to C.
2834
2835 @cindex Convention External
2836 @findex External
2837 @item External
2838 Equivalent to C.
2839
2840 @ifclear vms
2841 @findex C++
2842 @cindex Interfacing to C++
2843 @cindex Convention C++
2844 @item C_Plus_Plus (or CPP)
2845 This stands for C++. For most purposes this is identical to C.
2846 See the separate description of the specialized GNAT pragmas relating to
2847 C++ interfacing for further details.
2848 @end ifclear
2849
2850 @findex Fortran
2851 @cindex Interfacing to Fortran
2852 @cindex Convention Fortran
2853 @item Fortran
2854 Data will be passed according to the conventions described
2855 in section B.5 of the Ada Reference Manual.
2856
2857 @item Intrinsic
2858 This applies to an intrinsic operation, as defined in the Ada
2859 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2860 this means that the body of the subprogram is provided by the compiler itself,
2861 usually by means of an efficient code sequence, and that the user does not
2862 supply an explicit body for it. In an application program, the pragma may
2863 be applied to the following sets of names:
2864
2865 @itemize @bullet
2866 @item
2867 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2868 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2869 two formal parameters. The
2870 first one must be a signed integer type or a modular type with a binary
2871 modulus, and the second parameter must be of type Natural.
2872 The return type must be the same as the type of the first argument. The size
2873 of this type can only be 8, 16, 32, or 64.
2874
2875 @item
2876 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2877 The corresponding operator declaration must have parameters and result type
2878 that have the same root numeric type (for example, all three are long_float
2879 types). This simplifies the definition of operations that use type checking
2880 to perform dimensional checks:
2881
2882 @smallexample @c ada
2883 type Distance is new Long_Float;
2884 type Time     is new Long_Float;
2885 type Velocity is new Long_Float;
2886 function "/" (D : Distance; T : Time)
2887   return Velocity;
2888 pragma Import (Intrinsic, "/");
2889 @end smallexample
2890
2891 @noindent
2892 This common idiom is often programmed with a generic definition and an
2893 explicit body. The pragma makes it simpler to introduce such declarations.
2894 It incurs no overhead in compilation time or code size, because it is
2895 implemented as a single machine instruction.
2896
2897 @item
2898 General subprogram entities, to bind an Ada subprogram declaration to
2899 a compiler builtin by name with back-ends where such interfaces are
2900 available. A typical example is the set of ``__builtin'' functions
2901 exposed by the GCC back-end, as in the following example:
2902
2903 @smallexample @c ada
2904    function builtin_sqrt (F : Float) return Float;
2905    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2906 @end smallexample
2907
2908 Most of the GCC builtins are accessible this way, and as for other
2909 import conventions (e.g. C), it is the user's responsibility to ensure
2910 that the Ada subprogram profile matches the underlying builtin
2911 expectations.
2912 @end itemize
2913
2914 @noindent
2915
2916 @ifset unw
2917 @findex Stdcall
2918 @cindex Convention Stdcall
2919 @item Stdcall
2920 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2921 and specifies that the @code{Stdcall} calling sequence will be used,
2922 as defined by the NT API. Nevertheless, to ease building
2923 cross-platform bindings this convention will be handled as a @code{C} calling
2924 convention on non-Windows platforms.
2925
2926 @findex DLL
2927 @cindex Convention DLL
2928 @item DLL
2929 This is equivalent to @code{Stdcall}.
2930
2931 @findex Win32
2932 @cindex Convention Win32
2933 @item Win32
2934 This is equivalent to @code{Stdcall}.
2935 @end ifset
2936
2937 @findex Stubbed
2938 @cindex Convention Stubbed
2939 @item Stubbed
2940 This is a special convention that indicates that the compiler
2941 should provide a stub body that raises @code{Program_Error}.
2942 @end table
2943
2944 @noindent
2945 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2946 that can be used to parametrize conventions and allow additional synonyms
2947 to be specified. For example if you have legacy code in which the convention
2948 identifier Fortran77 was used for Fortran, you can use the configuration
2949 pragma:
2950
2951 @smallexample @c ada
2952 pragma Convention_Identifier (Fortran77, Fortran);
2953 @end smallexample
2954
2955 @noindent
2956 And from now on the identifier Fortran77 may be used as a convention
2957 identifier (for example in an @code{Import} pragma) with the same
2958 meaning as Fortran.
2959
2960 @ifclear vms
2961 @node Building Mixed Ada & C++ Programs
2962 @section Building Mixed Ada and C++ Programs
2963
2964 @noindent
2965 A programmer inexperienced with mixed-language development may find that
2966 building an application containing both Ada and C++ code can be a
2967 challenge.  This section gives a few
2968 hints that should make this task easier. The first section addresses
2969 the differences between interfacing with C and interfacing with C++.
2970 The second section
2971 looks into the delicate problem of linking the complete application from
2972 its Ada and C++ parts. The last section gives some hints on how the GNAT
2973 run-time library can be adapted in order to allow inter-language dispatching
2974 with a new C++ compiler.
2975
2976 @menu
2977 * Interfacing to C++::
2978 * Linking a Mixed C++ & Ada Program::
2979 * A Simple Example::
2980 * Interfacing with C++ constructors::
2981 * Interfacing with C++ at the Class Level::
2982 @end menu
2983
2984 @node Interfacing to C++
2985 @subsection Interfacing to C++
2986
2987 @noindent
2988 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2989 generating code that is compatible with the G++ Application Binary
2990 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2991
2992 @noindent
2993 Interfacing can be done at 3 levels: simple data, subprograms, and
2994 classes. In the first two cases, GNAT offers a specific @code{Convention
2995 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2996 Usually, C++ mangles the names of subprograms. To generate proper mangled
2997 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2998 This problem can also be addressed manually in two ways:
2999
3000 @itemize @bullet
3001 @item
3002 by modifying the C++ code in order to force a C convention using
3003 the @code{extern "C"} syntax.
3004
3005 @item
3006 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
3007 Link_Name argument of the pragma import.
3008 @end itemize
3009
3010 @noindent
3011 Interfacing at the class level can be achieved by using the GNAT specific
3012 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3013 gnat_rm, GNAT Reference Manual}, for additional information.
3014
3015 @node Linking a Mixed C++ & Ada Program
3016 @subsection Linking a Mixed C++ & Ada Program
3017
3018 @noindent
3019 Usually the linker of the C++ development system must be used to link
3020 mixed applications because most C++ systems will resolve elaboration
3021 issues (such as calling constructors on global class instances)
3022 transparently during the link phase. GNAT has been adapted to ease the
3023 use of a foreign linker for the last phase. Three cases can be
3024 considered:
3025 @enumerate
3026
3027 @item
3028 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3029 The C++ linker can simply be called by using the C++ specific driver
3030 called @code{g++}.
3031
3032 Note that if the C++ code uses inline functions, you will need to
3033 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3034 order to provide an existing function implementation that the Ada code can
3035 link with.
3036
3037 @smallexample
3038 $ g++ -c -fkeep-inline-functions file1.C
3039 $ g++ -c -fkeep-inline-functions file2.C
3040 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3041 @end smallexample
3042
3043 @item
3044 Using GNAT and G++ from two different GCC installations: If both
3045 compilers are on the @env{PATH}, the previous method may be used. It is
3046 important to note that environment variables such as
3047 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3048 @env{GCC_ROOT} will affect both compilers
3049 at the same time and may make one of the two compilers operate
3050 improperly if set during invocation of the wrong compiler.  It is also
3051 very important that the linker uses the proper @file{libgcc.a} GCC
3052 library -- that is, the one from the C++ compiler installation. The
3053 implicit link command as suggested in the @command{gnatmake} command
3054 from the former example can be replaced by an explicit link command with
3055 the full-verbosity option in order to verify which library is used:
3056 @smallexample
3057 $ gnatbind ada_unit
3058 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3059 @end smallexample
3060 If there is a problem due to interfering environment variables, it can
3061 be worked around by using an intermediate script. The following example
3062 shows the proper script to use when GNAT has not been installed at its
3063 default location and g++ has been installed at its default location:
3064
3065 @smallexample
3066 $ cat ./my_script
3067 #!/bin/sh
3068 unset BINUTILS_ROOT
3069 unset GCC_ROOT
3070 c++ $*
3071 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3072 @end smallexample
3073
3074 @item
3075 Using a non-GNU C++ compiler: The commands previously described can be
3076 used to insure that the C++ linker is used. Nonetheless, you need to add
3077 a few more parameters to the link command line, depending on the exception
3078 mechanism used.
3079
3080 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3081 to the libgcc libraries are required:
3082
3083 @smallexample
3084 $ cat ./my_script
3085 #!/bin/sh
3086 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3087 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3088 @end smallexample
3089
3090 Where CC is the name of the non-GNU C++ compiler.
3091
3092 If the @code{zero cost} exception mechanism is used, and the platform
3093 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3094 paths to more objects are required:
3095
3096 @smallexample
3097 $ cat ./my_script
3098 #!/bin/sh
3099 CC `gcc -print-file-name=crtbegin.o` $* \
3100 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3101 `gcc -print-file-name=crtend.o`
3102 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3103 @end smallexample
3104
3105 If the @code{zero cost} exception mechanism is used, and the platform
3106 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3107 Tru64 or AIX), the simple approach described above will not work and
3108 a pre-linking phase using GNAT will be necessary.
3109
3110 @end enumerate
3111
3112 Another alternative is to use the @command{gprbuild} multi-language builder
3113 which has a large knowledge base and knows how to link Ada and C++ code
3114 together automatically in most cases.
3115
3116 @node A Simple Example
3117 @subsection  A Simple Example
3118 @noindent
3119 The following example, provided as part of the GNAT examples, shows how
3120 to achieve procedural interfacing between Ada and C++ in both
3121 directions. The C++ class A has two methods. The first method is exported
3122 to Ada by the means of an extern C wrapper function. The second method
3123 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3124 a limited record with a layout comparable to the C++ class. The Ada
3125 subprogram, in turn, calls the C++ method. So, starting from the C++
3126 main program, the process passes back and forth between the two
3127 languages.
3128
3129 @noindent
3130 Here are the compilation commands:
3131 @smallexample
3132 $ gnatmake -c simple_cpp_interface
3133 $ g++ -c cpp_main.C
3134 $ g++ -c ex7.C
3135 $ gnatbind -n simple_cpp_interface
3136 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3137       -lstdc++ ex7.o cpp_main.o
3138 @end smallexample
3139
3140 @noindent
3141 Here are the corresponding sources:
3142 @smallexample
3143
3144 //cpp_main.C
3145
3146 #include "ex7.h"
3147
3148 extern "C" @{
3149   void adainit (void);
3150   void adafinal (void);
3151   void method1 (A *t);
3152 @}
3153
3154 void method1 (A *t)
3155 @{
3156   t->method1 ();
3157 @}
3158
3159 int main ()
3160 @{
3161   A obj;
3162   adainit ();
3163   obj.method2 (3030);
3164   adafinal ();
3165 @}
3166
3167 //ex7.h
3168
3169 class Origin @{
3170  public:
3171   int o_value;
3172 @};
3173 class A : public Origin @{
3174  public:
3175   void method1 (void);
3176   void method2 (int v);
3177   A();
3178   int   a_value;
3179 @};
3180
3181 //ex7.C
3182
3183 #include "ex7.h"
3184 #include <stdio.h>
3185
3186 extern "C" @{ void ada_method2 (A *t, int v);@}
3187
3188 void A::method1 (void)
3189 @{
3190   a_value = 2020;
3191   printf ("in A::method1, a_value = %d \n",a_value);
3192
3193 @}
3194
3195 void A::method2 (int v)
3196 @{
3197    ada_method2 (this, v);
3198    printf ("in A::method2, a_value = %d \n",a_value);
3199
3200 @}
3201
3202 A::A(void)
3203 @{
3204    a_value = 1010;
3205   printf ("in A::A, a_value = %d \n",a_value);
3206 @}
3207 @end smallexample
3208
3209 @smallexample @c ada
3210 -- Ada sources
3211 package body Simple_Cpp_Interface is
3212
3213    procedure Ada_Method2 (This : in out A; V : Integer) is
3214    begin
3215       Method1 (This);
3216       This.A_Value := V;
3217    end Ada_Method2;
3218
3219 end Simple_Cpp_Interface;
3220
3221 with System;
3222 package Simple_Cpp_Interface is
3223    type A is limited
3224       record
3225          Vptr    : System.Address;
3226          O_Value : Integer;
3227          A_Value : Integer;
3228       end record;
3229    pragma Convention (C, A);
3230
3231    procedure Method1 (This : in out A);
3232    pragma Import (C, Method1);
3233
3234    procedure Ada_Method2 (This : in out A; V : Integer);
3235    pragma Export (C, Ada_Method2);
3236
3237 end Simple_Cpp_Interface;
3238 @end smallexample
3239
3240 @node Interfacing with C++ constructors
3241 @subsection Interfacing with C++ constructors
3242 @noindent
3243
3244 In order to interface with C++ constructors GNAT provides the
3245 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3246 gnat_rm, GNAT Reference Manual}, for additional information).
3247 In this section we present some common uses of C++ constructors
3248 in mixed-languages programs in GNAT.
3249
3250 Let us assume that we need to interface with the following
3251 C++ class:
3252
3253 @smallexample
3254 @b{class} Root @{
3255 @b{public}:
3256   int  a_value;
3257   int  b_value;
3258   @b{virtual} int Get_Value ();
3259   Root();              // Default constructor
3260   Root(int v);         // 1st non-default constructor
3261   Root(int v, int w);  // 2nd non-default constructor
3262 @};
3263 @end smallexample
3264
3265 For this purpose we can write the following package spec (further
3266 information on how to build this spec is available in
3267 @ref{Interfacing with C++ at the Class Level} and
3268 @ref{Generating Ada Bindings for C and C++ headers}).
3269
3270 @smallexample @c ada
3271 with Interfaces.C; use Interfaces.C;
3272 package Pkg_Root is
3273   type Root is tagged limited record
3274      A_Value : int;
3275      B_Value : int;
3276   end record;
3277   pragma Import (CPP, Root);
3278
3279   function Get_Value (Obj : Root) return int;
3280   pragma Import (CPP, Get_Value);
3281
3282   function Constructor return Root;
3283   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3284
3285   function Constructor (v : Integer) return Root;
3286   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3287
3288   function Constructor (v, w : Integer) return Root;
3289   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3290 end Pkg_Root;
3291 @end smallexample
3292
3293 On the Ada side the constructor is represented by a function (whose
3294 name is arbitrary) that returns the classwide type corresponding to
3295 the imported C++ class. Although the constructor is described as a
3296 function, it is typically a procedure with an extra implicit argument
3297 (the object being initialized) at the implementation level. GNAT
3298 issues the appropriate call, whatever it is, to get the object
3299 properly initialized.
3300
3301 Constructors can only appear in the following contexts:
3302
3303 @itemize @bullet
3304 @item
3305 On the right side of an initialization of an object of type @var{T}.
3306 @item
3307 On the right side of an initialization of a record component of type @var{T}.
3308 @item
3309 In an Ada 2005 limited aggregate.
3310 @item
3311 In an Ada 2005 nested limited aggregate.
3312 @item
3313 In an Ada 2005 limited aggregate that initializes an object built in
3314 place by an extended return statement.
3315 @end itemize
3316
3317 @noindent
3318 In a declaration of an object whose type is a class imported from C++,
3319 either the default C++ constructor is implicitly called by GNAT, or
3320 else the required C++ constructor must be explicitly called in the
3321 expression that initializes the object. For example:
3322
3323 @smallexample @c ada
3324   Obj1 : Root;
3325   Obj2 : Root := Constructor;
3326   Obj3 : Root := Constructor (v => 10);
3327   Obj4 : Root := Constructor (30, 40);
3328 @end smallexample
3329
3330 The first two declarations are equivalent: in both cases the default C++
3331 constructor is invoked (in the former case the call to the constructor is
3332 implicit, and in the latter case the call is explicit in the object
3333 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3334 that takes an integer argument, and @code{Obj4} is initialized by the
3335 non-default C++ constructor that takes two integers.
3336
3337 Let us derive the imported C++ class in the Ada side. For example:
3338
3339 @smallexample @c ada
3340   type DT is new Root with record
3341      C_Value : Natural := 2009;
3342   end record;
3343 @end smallexample
3344
3345 In this case the components DT inherited from the C++ side must be
3346 initialized by a C++ constructor, and the additional Ada components
3347 of type DT are initialized by GNAT. The initialization of such an
3348 object is done either by default, or by means of a function returning
3349 an aggregate of type DT, or by means of an extension aggregate.
3350
3351 @smallexample @c ada
3352   Obj5 : DT;
3353   Obj6 : DT := Function_Returning_DT (50);
3354   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3355 @end smallexample
3356
3357 The declaration of @code{Obj5} invokes the default constructors: the
3358 C++ default constructor of the parent type takes care of the initialization
3359 of the components inherited from Root, and GNAT takes care of the default
3360 initialization of the additional Ada components of type DT (that is,
3361 @code{C_Value} is initialized to value 2009). The order of invocation of
3362 the constructors is consistent with the order of elaboration required by
3363 Ada and C++. That is, the constructor of the parent type is always called
3364 before the constructor of the derived type.
3365
3366 Let us now consider a record that has components whose type is imported
3367 from C++. For example:
3368
3369 @smallexample @c ada
3370   type Rec1 is limited record
3371      Data1 : Root := Constructor (10);
3372      Value : Natural := 1000;
3373   end record;
3374
3375   type Rec2 (D : Integer := 20) is limited record
3376      Rec   : Rec1;
3377      Data2 : Root := Constructor (D, 30);
3378   end record;
3379 @end smallexample
3380
3381 The initialization of an object of type @code{Rec2} will call the
3382 non-default C++ constructors specified for the imported components.
3383 For example:
3384
3385 @smallexample @c ada
3386   Obj8 : Rec2 (40);
3387 @end smallexample
3388
3389 Using Ada 2005 we can use limited aggregates to initialize an object
3390 invoking C++ constructors that differ from those specified in the type
3391 declarations. For example:
3392
3393 @smallexample @c ada
3394   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3395                           others => <>),
3396                   others => <>);
3397 @end smallexample
3398
3399 The above declaration uses an Ada 2005 limited aggregate to
3400 initialize @code{Obj9}, and the C++ constructor that has two integer
3401 arguments is invoked to initialize the @code{Data1} component instead
3402 of the constructor specified in the declaration of type @code{Rec1}. In
3403 Ada 2005 the box in the aggregate indicates that unspecified components
3404 are initialized using the expression (if any) available in the component
3405 declaration. That is, in this case discriminant @code{D} is initialized
3406 to value @code{20}, @code{Value} is initialized to value 1000, and the
3407 non-default C++ constructor that handles two integers takes care of
3408 initializing component @code{Data2} with values @code{20,30}.
3409
3410 In Ada 2005 we can use the extended return statement to build the Ada
3411 equivalent to C++ non-default constructors. For example:
3412
3413 @smallexample @c ada
3414   function Constructor (V : Integer) return Rec2 is
3415   begin
3416      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3417                                    others => <>),
3418                            others => <>) do
3419         --  Further actions required for construction of
3420         --  objects of type Rec2
3421         ...
3422      end record;
3423   end Constructor;
3424 @end smallexample
3425
3426 In this example the extended return statement construct is used to
3427 build in place the returned object whose components are initialized
3428 by means of a limited aggregate. Any further action associated with
3429 the constructor can be placed inside the construct.
3430
3431 @node Interfacing with C++ at the Class Level
3432 @subsection Interfacing with C++ at the Class Level
3433 @noindent
3434 In this section we demonstrate the GNAT features for interfacing with
3435 C++ by means of an example making use of Ada 2005 abstract interface
3436 types. This example consists of a classification of animals; classes
3437 have been used to model our main classification of animals, and
3438 interfaces provide support for the management of secondary
3439 classifications. We first demonstrate a case in which the types and
3440 constructors are defined on the C++ side and imported from the Ada
3441 side, and latter the reverse case.
3442
3443 The root of our derivation will be the @code{Animal} class, with a
3444 single private attribute (the @code{Age} of the animal) and two public
3445 primitives to set and get the value of this attribute.
3446
3447 @smallexample
3448 @b{class} Animal @{
3449  @b{public}:
3450    @b{virtual} void Set_Age (int New_Age);
3451    @b{virtual} int Age ();
3452  @b{private}:
3453    int Age_Count;
3454 @};
3455 @end smallexample
3456
3457 Abstract interface types are defined in C++ by means of classes with pure
3458 virtual functions and no data members. In our example we will use two
3459 interfaces that provide support for the common management of @code{Carnivore}
3460 and @code{Domestic} animals:
3461
3462 @smallexample
3463 @b{class} Carnivore @{
3464 @b{public}:
3465    @b{virtual} int Number_Of_Teeth () = 0;
3466 @};
3467
3468 @b{class} Domestic @{
3469 @b{public}:
3470    @b{virtual void} Set_Owner (char* Name) = 0;
3471 @};
3472 @end smallexample
3473
3474 Using these declarations, we can now say that a @code{Dog} is an animal that is
3475 both Carnivore and Domestic, that is:
3476
3477 @smallexample
3478 @b{class} Dog : Animal, Carnivore, Domestic @{
3479  @b{public}:
3480    @b{virtual} int  Number_Of_Teeth ();
3481    @b{virtual} void Set_Owner (char* Name);
3482
3483    Dog(); // Constructor
3484  @b{private}:
3485    int  Tooth_Count;
3486    char *Owner;
3487 @};
3488 @end smallexample
3489
3490 In the following examples we will assume that the previous declarations are
3491 located in a file named @code{animals.h}. The following package demonstrates
3492 how to import these C++ declarations from the Ada side:
3493
3494 @smallexample @c ada
3495 with Interfaces.C.Strings; use Interfaces.C.Strings;
3496 package Animals is
3497   type Carnivore is interface;
3498   pragma Convention (C_Plus_Plus, Carnivore);
3499   function Number_Of_Teeth (X : Carnivore)
3500      return Natural is abstract;
3501
3502   type Domestic is interface;
3503   pragma Convention (C_Plus_Plus, Set_Owner);
3504   procedure Set_Owner
3505     (X    : in out Domestic;
3506      Name : Chars_Ptr) is abstract;
3507
3508   type Animal is tagged record
3509     Age : Natural := 0;
3510   end record;
3511   pragma Import (C_Plus_Plus, Animal);
3512
3513   procedure Set_Age (X : in out Animal; Age : Integer);
3514   pragma Import (C_Plus_Plus, Set_Age);
3515
3516   function Age (X : Animal) return Integer;
3517   pragma Import (C_Plus_Plus, Age);
3518
3519   type Dog is new Animal and Carnivore and Domestic with record
3520     Tooth_Count : Natural;
3521     Owner       : String (1 .. 30);
3522   end record;
3523   pragma Import (C_Plus_Plus, Dog);
3524
3525   function Number_Of_Teeth (A : Dog) return Integer;
3526   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3527
3528   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3529   pragma Import (C_Plus_Plus, Set_Owner);
3530
3531   function New_Dog return Dog;
3532   pragma CPP_Constructor (New_Dog);
3533   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3534 end Animals;
3535 @end smallexample
3536
3537 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3538 interfacing with these C++ classes is easy. The only requirement is that all
3539 the primitives and components must be declared exactly in the same order in
3540 the two languages.
3541
3542 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3543 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3544 the arguments to the called primitives will be the same as for C++. For the
3545 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3546 to indicate that they have been defined on the C++ side; this is required
3547 because the dispatch table associated with these tagged types will be built
3548 in the C++ side and therefore will not contain the predefined Ada primitives
3549 which Ada would otherwise expect.
3550
3551 As the reader can see there is no need to indicate the C++ mangled names
3552 associated with each subprogram because it is assumed that all the calls to
3553 these primitives will be dispatching calls. The only exception is the
3554 constructor, which must be registered with the compiler by means of
3555 @code{pragma CPP_Constructor} and needs to provide its associated C++
3556 mangled name because the Ada compiler generates direct calls to it.
3557
3558 With the above packages we can now declare objects of type Dog on the Ada side
3559 and dispatch calls to the corresponding subprograms on the C++ side. We can
3560 also extend the tagged type Dog with further fields and primitives, and
3561 override some of its C++ primitives on the Ada side. For example, here we have
3562 a type derivation defined on the Ada side that inherits all the dispatching
3563 primitives of the ancestor from the C++ side.
3564
3565 @smallexample
3566 @b{with} Animals; @b{use} Animals;
3567 @b{package} Vaccinated_Animals @b{is}
3568   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3569   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3570 @b{end} Vaccinated_Animals;
3571 @end smallexample
3572
3573 It is important to note that, because of the ABI compatibility, the programmer
3574 does not need to add any further information to indicate either the object
3575 layout or the dispatch table entry associated with each dispatching operation.
3576
3577 Now let us define all the types and constructors on the Ada side and export
3578 them to C++, using the same hierarchy of our previous example:
3579
3580 @smallexample @c ada
3581 with Interfaces.C.Strings;
3582 use Interfaces.C.Strings;
3583 package Animals is
3584   type Carnivore is interface;
3585   pragma Convention (C_Plus_Plus, Carnivore);
3586   function Number_Of_Teeth (X : Carnivore)
3587      return Natural is abstract;
3588
3589   type Domestic is interface;
3590   pragma Convention (C_Plus_Plus, Set_Owner);
3591   procedure Set_Owner
3592     (X    : in out Domestic;
3593      Name : Chars_Ptr) is abstract;
3594
3595   type Animal is tagged record
3596     Age : Natural := 0;
3597   end record;
3598   pragma Convention (C_Plus_Plus, Animal);
3599
3600   procedure Set_Age (X : in out Animal; Age : Integer);
3601   pragma Export (C_Plus_Plus, Set_Age);
3602
3603   function Age (X : Animal) return Integer;
3604   pragma Export (C_Plus_Plus, Age);
3605
3606   type Dog is new Animal and Carnivore and Domestic with record
3607     Tooth_Count : Natural;
3608     Owner       : String (1 .. 30);
3609   end record;
3610   pragma Convention (C_Plus_Plus, Dog);
3611
3612   function Number_Of_Teeth (A : Dog) return Integer;
3613   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3614
3615   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3616   pragma Export (C_Plus_Plus, Set_Owner);
3617
3618   function New_Dog return Dog'Class;
3619   pragma Export (C_Plus_Plus, New_Dog);
3620 end Animals;
3621 @end smallexample
3622
3623 Compared with our previous example the only difference is the use of
3624 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3625 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3626 nothing else to be done; as explained above, the only requirement is that all
3627 the primitives and components are declared in exactly the same order.
3628
3629 For completeness, let us see a brief C++ main program that uses the
3630 declarations available in @code{animals.h} (presented in our first example) to
3631 import and use the declarations from the Ada side, properly initializing and
3632 finalizing the Ada run-time system along the way:
3633
3634 @smallexample
3635 @b{#include} "animals.h"
3636 @b{#include} <iostream>
3637 @b{using namespace} std;
3638
3639 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3640 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3641 void Check_Animal (Animal *obj)       @{@dots{}@}
3642 void Check_Dog (Dog *obj)             @{@dots{}@}
3643
3644 @b{extern} "C" @{
3645   void adainit (void);
3646   void adafinal (void);
3647   Dog* new_dog ();
3648 @}
3649
3650 void test ()
3651 @{
3652   Dog *obj = new_dog();  // Ada constructor
3653   Check_Carnivore (obj); // Check secondary DT
3654   Check_Domestic (obj);  // Check secondary DT
3655   Check_Animal (obj);    // Check primary DT
3656   Check_Dog (obj);       // Check primary DT
3657 @}
3658
3659 int main ()
3660 @{
3661   adainit ();  test();  adafinal ();
3662   return 0;
3663 @}
3664 @end smallexample
3665
3666 @node Comparison between GNAT and C/C++ Compilation Models
3667 @section Comparison between GNAT and C/C++ Compilation Models
3668
3669 @noindent
3670 The GNAT model of compilation is close to the C and C++ models. You can
3671 think of Ada specs as corresponding to header files in C. As in C, you
3672 don't need to compile specs; they are compiled when they are used. The
3673 Ada @code{with} is similar in effect to the @code{#include} of a C
3674 header.
3675
3676 One notable difference is that, in Ada, you may compile specs separately
3677 to check them for semantic and syntactic accuracy. This is not always
3678 possible with C headers because they are fragments of programs that have
3679 less specific syntactic or semantic rules.
3680
3681 The other major difference is the requirement for running the binder,
3682 which performs two important functions. First, it checks for
3683 consistency. In C or C++, the only defense against assembling
3684 inconsistent programs lies outside the compiler, in a makefile, for
3685 example. The binder satisfies the Ada requirement that it be impossible
3686 to construct an inconsistent program when the compiler is used in normal
3687 mode.
3688
3689 @cindex Elaboration order control
3690 The other important function of the binder is to deal with elaboration
3691 issues. There are also elaboration issues in C++ that are handled
3692 automatically. This automatic handling has the advantage of being
3693 simpler to use, but the C++ programmer has no control over elaboration.
3694 Where @code{gnatbind} might complain there was no valid order of
3695 elaboration, a C++ compiler would simply construct a program that
3696 malfunctioned at run time.
3697 @end ifclear
3698
3699 @node Comparison between GNAT and Conventional Ada Library Models
3700 @section Comparison between GNAT and Conventional Ada Library Models
3701
3702 @noindent
3703 This section is intended for Ada programmers who have
3704 used an Ada compiler implementing the traditional Ada library
3705 model, as described in the Ada Reference Manual.
3706
3707 @cindex GNAT library
3708 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3709 source files themselves acts as the library. Compiling Ada programs does
3710 not generate any centralized information, but rather an object file and
3711 a ALI file, which are of interest only to the binder and linker.
3712 In a traditional system, the compiler reads information not only from
3713 the source file being compiled, but also from the centralized library.
3714 This means that the effect of a compilation depends on what has been
3715 previously compiled. In particular:
3716
3717 @itemize @bullet
3718 @item
3719 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3720 to the version of the unit most recently compiled into the library.
3721
3722 @item
3723 Inlining is effective only if the necessary body has already been
3724 compiled into the library.
3725
3726 @item
3727 Compiling a unit may obsolete other units in the library.
3728 @end itemize
3729
3730 @noindent
3731 In GNAT, compiling one unit never affects the compilation of any other
3732 units because the compiler reads only source files. Only changes to source
3733 files can affect the results of a compilation. In particular:
3734
3735 @itemize @bullet
3736 @item
3737 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3738 to the source version of the unit that is currently accessible to the
3739 compiler.
3740
3741 @item
3742 @cindex Inlining
3743 Inlining requires the appropriate source files for the package or
3744 subprogram bodies to be available to the compiler. Inlining is always
3745 effective, independent of the order in which units are complied.
3746
3747 @item
3748 Compiling a unit never affects any other compilations. The editing of
3749 sources may cause previous compilations to be out of date if they
3750 depended on the source file being modified.
3751 @end itemize
3752
3753 @noindent
3754 The most important result of these differences is that order of compilation
3755 is never significant in GNAT. There is no situation in which one is
3756 required to do one compilation before another. What shows up as order of
3757 compilation requirements in the traditional Ada library becomes, in
3758 GNAT, simple source dependencies; in other words, there is only a set
3759 of rules saying what source files must be present when a file is
3760 compiled.
3761
3762 @ifset vms
3763 @node Placement of temporary files
3764 @section Placement of temporary files
3765 @cindex Temporary files (user control over placement)
3766
3767 @noindent
3768 GNAT creates temporary files in the directory designated by the environment
3769 variable @env{TMPDIR}.
3770 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3771 for detailed information on how environment variables are resolved.
3772 For most users the easiest way to make use of this feature is to simply
3773 define @env{TMPDIR} as a job level logical name).
3774 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3775 for compiler temporary files, then you can include something like the
3776 following command in your @file{LOGIN.COM} file:
3777
3778 @smallexample
3779 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3780 @end smallexample
3781
3782 @noindent
3783 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3784 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3785 designated by @env{TEMP}.
3786 If none of these environment variables are defined then GNAT uses the
3787 directory designated by the logical name @code{SYS$SCRATCH:}
3788 (by default the user's home directory). If all else fails
3789 GNAT uses the current directory for temporary files.
3790 @end ifset
3791
3792 @c *************************
3793 @node Compiling Using gcc
3794 @chapter Compiling Using @command{gcc}
3795
3796 @noindent
3797 This chapter discusses how to compile Ada programs using the @command{gcc}
3798 command. It also describes the set of switches
3799 that can be used to control the behavior of the compiler.
3800 @menu
3801 * Compiling Programs::
3802 * Switches for gcc::
3803 * Search Paths and the Run-Time Library (RTL)::
3804 * Order of Compilation Issues::
3805 * Examples::
3806 @end menu
3807
3808 @node Compiling Programs
3809 @section Compiling Programs
3810
3811 @noindent
3812 The first step in creating an executable program is to compile the units
3813 of the program using the @command{gcc} command. You must compile the
3814 following files:
3815
3816 @itemize @bullet
3817 @item
3818 the body file (@file{.adb}) for a library level subprogram or generic
3819 subprogram
3820
3821 @item
3822 the spec file (@file{.ads}) for a library level package or generic
3823 package that has no body
3824
3825 @item
3826 the body file (@file{.adb}) for a library level package
3827 or generic package that has a body
3828
3829 @end itemize
3830
3831 @noindent
3832 You need @emph{not} compile the following files
3833
3834 @itemize @bullet
3835
3836 @item
3837 the spec of a library unit which has a body
3838
3839 @item
3840 subunits
3841 @end itemize
3842
3843 @noindent
3844 because they are compiled as part of compiling related units. GNAT
3845 package specs
3846 when the corresponding body is compiled, and subunits when the parent is
3847 compiled.
3848
3849 @cindex cannot generate code
3850 If you attempt to compile any of these files, you will get one of the
3851 following error messages (where @var{fff} is the name of the file you compiled):
3852
3853 @smallexample
3854 cannot generate code for file @var{fff} (package spec)
3855 to check package spec, use -gnatc
3856
3857 cannot generate code for file @var{fff} (missing subunits)
3858 to check parent unit, use -gnatc
3859
3860 cannot generate code for file @var{fff} (subprogram spec)
3861 to check subprogram spec, use -gnatc
3862
3863 cannot generate code for file @var{fff} (subunit)
3864 to check subunit, use -gnatc
3865 @end smallexample
3866
3867 @noindent
3868 As indicated by the above error messages, if you want to submit
3869 one of these files to the compiler to check for correct semantics
3870 without generating code, then use the @option{-gnatc} switch.
3871
3872 The basic command for compiling a file containing an Ada unit is
3873
3874 @smallexample
3875 $ gcc -c @ovar{switches} @file{file name}
3876 @end smallexample
3877
3878 @noindent
3879 where @var{file name} is the name of the Ada file (usually
3880 having an extension
3881 @file{.ads} for a spec or @file{.adb} for a body).
3882 @ifclear vms
3883 You specify the
3884 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3885 @end ifclear
3886 The result of a successful compilation is an object file, which has the
3887 same name as the source file but an extension of @file{.o} and an Ada
3888 Library Information (ALI) file, which also has the same name as the
3889 source file, but with @file{.ali} as the extension. GNAT creates these
3890 two output files in the current directory, but you may specify a source
3891 file in any directory using an absolute or relative path specification
3892 containing the directory information.
3893
3894 @findex gnat1
3895 @command{gcc} is actually a driver program that looks at the extensions of
3896 the file arguments and loads the appropriate compiler. For example, the
3897 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3898 These programs are in directories known to the driver program (in some
3899 configurations via environment variables you set), but need not be in
3900 your path. The @command{gcc} driver also calls the assembler and any other
3901 utilities needed to complete the generation of the required object
3902 files.
3903
3904 It is possible to supply several file names on the same @command{gcc}
3905 command. This causes @command{gcc} to call the appropriate compiler for
3906 each file. For example, the following command lists three separate
3907 files to be compiled:
3908
3909 @smallexample
3910 $ gcc -c x.adb y.adb z.c
3911 @end smallexample
3912
3913 @noindent
3914 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3915 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3916 The compiler generates three object files @file{x.o}, @file{y.o} and
3917 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3918 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3919 @ifclear vms
3920 except for
3921 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3922 @end ifclear
3923
3924 @node Switches for gcc
3925 @section Switches for @command{gcc}
3926
3927 @noindent
3928 The @command{gcc} command accepts switches that control the
3929 compilation process. These switches are fully described in this section.
3930 First we briefly list all the switches, in alphabetical order, then we
3931 describe the switches in more detail in functionally grouped sections.
3932
3933 More switches exist for GCC than those documented here, especially
3934 for specific targets. However, their use is not recommended as
3935 they may change code generation in ways that are incompatible with
3936 the Ada run-time library, or can cause inconsistencies between
3937 compilation units.
3938
3939 @menu
3940 * Output and Error Message Control::
3941 * Warning Message Control::
3942 * Debugging and Assertion Control::
3943 * Validity Checking::
3944 * Style Checking::
3945 * Run-Time Checks::
3946 * Using gcc for Syntax Checking::
3947 * Using gcc for Semantic Checking::
3948 * Compiling Different Versions of Ada::
3949 * Character Set Control::
3950 * File Naming Control::
3951 * Subprogram Inlining Control::
3952 * Auxiliary Output Control::
3953 * Debugging Control::
3954 * Exception Handling Control::
3955 * Units to Sources Mapping Files::
3956 * Integrated Preprocessing::
3957 * Code Generation Control::
3958 @ifset vms
3959 * Return Codes::
3960 @end ifset
3961 @end menu
3962
3963 @table @option
3964 @c !sort!
3965 @ifclear vms
3966 @cindex @option{-b} (@command{gcc})
3967 @item -b @var{target}
3968 Compile your program to run on @var{target}, which is the name of a
3969 system configuration. You must have a GNAT cross-compiler built if
3970 @var{target} is not the same as your host system.
3971
3972 @item -B@var{dir}
3973 @cindex @option{-B} (@command{gcc})
3974 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3975 from @var{dir} instead of the default location. Only use this switch
3976 when multiple versions of the GNAT compiler are available.
3977 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3978 GNU Compiler Collection (GCC)}, for further details. You would normally
3979 use the @option{-b} or @option{-V} switch instead.
3980
3981 @item -c
3982 @cindex @option{-c} (@command{gcc})
3983 Compile. Always use this switch when compiling Ada programs.
3984
3985 Note: for some other languages when using @command{gcc}, notably in
3986 the case of C and C++, it is possible to use
3987 use @command{gcc} without a @option{-c} switch to
3988 compile and link in one step. In the case of GNAT, you
3989 cannot use this approach, because the binder must be run
3990 and @command{gcc} cannot be used to run the GNAT binder.
3991 @end ifclear
3992
3993 @item -fno-inline
3994 @cindex @option{-fno-inline} (@command{gcc})
3995 Suppresses all back-end inlining, even if other optimization or inlining
3996 switches are set.
3997 This includes suppression of inlining that results
3998 from the use of the pragma @code{Inline_Always}.
3999 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
4000 are ignored, and @option{-gnatn} and @option{-gnatN} have no
4001 effect if this switch is present.
4002
4003 @item -fno-inline-functions
4004 @cindex @option{-fno-inline-functions} (@command{gcc})
4005 Suppresses automatic inlining of simple subprograms, which is enabled
4006 if @option{-O3} is used.
4007
4008 @item -fno-inline-small-functions
4009 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4010 Suppresses automatic inlining of small subprograms, which is enabled
4011 if @option{-O2} is used.
4012
4013 @item -fno-inline-functions-called-once
4014 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4015 Suppresses inlining of subprograms local to the unit and called once
4016 from within it, which is enabled if @option{-O1} is used.
4017
4018 @item -fno-ivopts
4019 @cindex @option{-fno-ivopts} (@command{gcc})
4020 Suppresses high-level loop induction variable optimizations, which are
4021 enabled if @option{-O1} is used. These optimizations are generally
4022 profitable but, for some specific cases of loops with numerous uses
4023 of the iteration variable that follow a common pattern, they may end
4024 up destroying the regularity that could be exploited at a lower level
4025 and thus producing inferior code.
4026
4027 @item -fno-strict-aliasing
4028 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4029 Causes the compiler to avoid assumptions regarding non-aliasing
4030 of objects of different types. See
4031 @ref{Optimization and Strict Aliasing} for details.
4032
4033 @item -fstack-check
4034 @cindex @option{-fstack-check} (@command{gcc})
4035 Activates stack checking.
4036 See @ref{Stack Overflow Checking} for details.
4037
4038 @item -fstack-usage
4039 @cindex @option{-fstack-usage} (@command{gcc})
4040 Makes the compiler output stack usage information for the program, on a
4041 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4042
4043 @item -fcallgraph-info@r{[}=su@r{]}
4044 @cindex @option{-fcallgraph-info} (@command{gcc})
4045 Makes the compiler output callgraph information for the program, on a
4046 per-file basis.  The information is generated in the VCG format.  It can
4047 be decorated with stack-usage per-node information.
4048
4049 @item ^-g^/DEBUG^
4050 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4051 Generate debugging information. This information is stored in the object
4052 file and copied from there to the final executable file by the linker,
4053 where it can be read by the debugger. You must use the
4054 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4055
4056 @item -gnat83
4057 @cindex @option{-gnat83} (@command{gcc})
4058 Enforce Ada 83 restrictions.
4059
4060 @item -gnat95
4061 @cindex @option{-gnat95} (@command{gcc})
4062 Enforce Ada 95 restrictions.
4063
4064 @item -gnat05
4065 @cindex @option{-gnat05} (@command{gcc})
4066 Allow full Ada 2005 features.
4067
4068 @item -gnata
4069 @cindex @option{-gnata} (@command{gcc})
4070 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4071 activated. Note that these pragmas can also be controlled using the
4072 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4073 It also activates pragmas @code{Check}, @code{Precondition}, and
4074 @code{Postcondition}. Note that these pragmas can also be controlled
4075 using the configuration pragma @code{Check_Policy}.
4076
4077 @item -gnatA
4078 @cindex @option{-gnatA} (@command{gcc})
4079 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4080 it will be ignored.
4081
4082 @item -gnatb
4083 @cindex @option{-gnatb} (@command{gcc})
4084 Generate brief messages to @file{stderr} even if verbose mode set.
4085
4086 @item -gnatB
4087 @cindex @option{-gnatB} (@command{gcc})
4088 Assume no invalid (bad) values except for 'Valid attribute use
4089 (@pxref{Validity Checking}).
4090
4091 @item -gnatc
4092 @cindex @option{-gnatc} (@command{gcc})
4093 Check syntax and semantics only (no code generation attempted).
4094
4095 @item -gnatC
4096 @cindex @option{-gnatC} (@command{gcc})
4097 Generate CodePeer information (no code generation attempted).
4098 This switch will generate an intermediate representation suitable for
4099 use by CodePeer (@file{.scil} files). This switch is not compatible with
4100 code generation (it will, among other things, disable some switches such
4101 as -gnatn, and enable others such as -gnata).
4102
4103 @item -gnatd
4104 @cindex @option{-gnatd} (@command{gcc})
4105 Specify debug options for the compiler. The string of characters after
4106 the @option{-gnatd} specify the specific debug options. The possible
4107 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4108 compiler source file @file{debug.adb} for details of the implemented
4109 debug options. Certain debug options are relevant to applications
4110 programmers, and these are documented at appropriate points in this
4111 users guide.
4112
4113 @ifclear vms
4114 @item -gnatD
4115 @cindex @option{-gnatD[nn]} (@command{gcc})
4116 @end ifclear
4117 @ifset vms
4118 @item /XDEBUG /LXDEBUG=nnn
4119 @end ifset
4120 Create expanded source files for source level debugging. This switch
4121 also suppress generation of cross-reference information
4122 (see @option{-gnatx}).
4123
4124 @item -gnatec=@var{path}
4125 @cindex @option{-gnatec} (@command{gcc})
4126 Specify a configuration pragma file
4127 @ifclear vms
4128 (the equal sign is optional)
4129 @end ifclear
4130 (@pxref{The Configuration Pragmas Files}).
4131
4132 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4133 @cindex @option{-gnateD} (@command{gcc})
4134 Defines a symbol, associated with @var{value}, for preprocessing.
4135 (@pxref{Integrated Preprocessing}).
4136
4137 @item -gnatef
4138 @cindex @option{-gnatef} (@command{gcc})
4139 Display full source path name in brief error messages.
4140
4141 @item -gnateG
4142 @cindex @option{-gnateG} (@command{gcc})
4143 Save result of preprocessing in a text file.
4144
4145 @item -gnatem=@var{path}
4146 @cindex @option{-gnatem} (@command{gcc})
4147 Specify a mapping file
4148 @ifclear vms
4149 (the equal sign is optional)
4150 @end ifclear
4151 (@pxref{Units to Sources Mapping Files}).
4152
4153 @item -gnatep=@var{file}
4154 @cindex @option{-gnatep} (@command{gcc})
4155 Specify a preprocessing data file
4156 @ifclear vms
4157 (the equal sign is optional)
4158 @end ifclear
4159 (@pxref{Integrated Preprocessing}).
4160
4161 @item -gnateS
4162 @cindex @option{-gnateS} (@command{gcc})
4163 Generate SCO (Source Coverage Obligation) information in the ALI
4164 file. This information is used by advanced coverage tools. See
4165 unit @file{SCOs} in the compiler sources for details in files
4166 @file{scos.ads} and @file{scos.adb}.
4167
4168 @item -gnatE
4169 @cindex @option{-gnatE} (@command{gcc})
4170 Full dynamic elaboration checks.
4171
4172 @item -gnatf
4173 @cindex @option{-gnatf} (@command{gcc})
4174 Full errors. Multiple errors per line, all undefined references, do not
4175 attempt to suppress cascaded errors.
4176
4177 @item -gnatF
4178 @cindex @option{-gnatF} (@command{gcc})
4179 Externals names are folded to all uppercase.
4180
4181 @item ^-gnatg^/GNAT_INTERNAL^
4182 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4183 Internal GNAT implementation mode. This should not be used for
4184 applications programs, it is intended only for use by the compiler
4185 and its run-time library. For documentation, see the GNAT sources.
4186 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4187 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4188 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4189 so that all standard warnings and all standard style options are turned on.
4190 All warnings and style error messages are treated as errors.
4191
4192 @ifclear vms
4193 @item -gnatG=nn
4194 @cindex @option{-gnatG[nn]} (@command{gcc})
4195 @end ifclear
4196 @ifset vms
4197 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4198 @end ifset
4199 List generated expanded code in source form.
4200
4201 @item ^-gnath^/HELP^
4202 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4203 Output usage information. The output is written to @file{stdout}.
4204
4205 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4206 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4207 Identifier character set
4208 @ifclear vms
4209 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4210 @end ifclear
4211 For details of the possible selections for @var{c},
4212 see @ref{Character Set Control}.
4213
4214 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4215 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4216 Ignore representation clauses. When this switch is used,
4217 representation clauses are treated as comments. This is useful
4218 when initially porting code where you want to ignore rep clause
4219 problems, and also for compiling foreign code (particularly
4220 for use with ASIS). The representation clauses that are ignored
4221 are: enumeration_representation_clause, record_representation_clause,
4222 and attribute_definition_clause for the following attributes:
4223 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4224 Object_Size, Size, Small, Stream_Size, and Value_Size.
4225 Note that this option should be used only for compiling -- the
4226 code is likely to malfunction at run time.
4227
4228 @item -gnatjnn
4229 @cindex @option{-gnatjnn} (@command{gcc})
4230 Reformat error messages to fit on nn character lines
4231
4232 @item -gnatk=@var{n}
4233 @cindex @option{-gnatk} (@command{gcc})
4234 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4235
4236 @item -gnatl
4237 @cindex @option{-gnatl} (@command{gcc})
4238 Output full source listing with embedded error messages.
4239
4240 @item -gnatL
4241 @cindex @option{-gnatL} (@command{gcc})
4242 Used in conjunction with -gnatG or -gnatD to intersperse original
4243 source lines (as comment lines with line numbers) in the expanded
4244 source output.
4245
4246 @item -gnatm=@var{n}
4247 @cindex @option{-gnatm} (@command{gcc})
4248 Limit number of detected error or warning messages to @var{n}
4249 where @var{n} is in the range 1..999999. The default setting if
4250 no switch is given is 9999. If the number of warnings reaches this
4251 limit, then a message is output and further warnings are suppressed,
4252 but the compilation is continued. If the number of error messages
4253 reaches this limit, then a message is output and the compilation
4254 is abandoned. The equal sign here is optional. A value of zero
4255 means that no limit applies.
4256
4257 @item -gnatn
4258 @cindex @option{-gnatn} (@command{gcc})
4259 Activate inlining for subprograms for which
4260 pragma @code{inline} is specified. This inlining is performed
4261 by the GCC back-end.
4262
4263 @item -gnatN
4264 @cindex @option{-gnatN} (@command{gcc})
4265 Activate front end inlining for subprograms for which
4266 pragma @code{Inline} is specified. This inlining is performed
4267 by the front end and will be visible in the
4268 @option{-gnatG} output.
4269
4270 When using a gcc-based back end (in practice this means using any version
4271 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4272 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4273 Historically front end inlining was more extensive than the gcc back end
4274 inlining, but that is no longer the case.
4275
4276 @item -gnato
4277 @cindex @option{-gnato} (@command{gcc})
4278 Enable numeric overflow checking (which is not normally enabled by
4279 default). Note that division by zero is a separate check that is not
4280 controlled by this switch (division by zero checking is on by default).
4281
4282 @item -gnatp
4283 @cindex @option{-gnatp} (@command{gcc})
4284 Suppress all checks. See @ref{Run-Time Checks} for details.
4285
4286 @item -gnatP
4287 @cindex @option{-gnatP} (@command{gcc})
4288 Enable polling. This is required on some systems (notably Windows NT) to
4289 obtain asynchronous abort and asynchronous transfer of control capability.
4290 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4291 details.
4292
4293 @item -gnatq
4294 @cindex @option{-gnatq} (@command{gcc})
4295 Don't quit. Try semantics, even if parse errors.
4296
4297 @item -gnatQ
4298 @cindex @option{-gnatQ} (@command{gcc})
4299 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4300
4301 @item -gnatr
4302 @cindex @option{-gnatr} (@command{gcc})
4303 Treat pragma Restrictions as Restriction_Warnings.
4304
4305 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4306 @cindex @option{-gnatR} (@command{gcc})
4307 Output representation information for declared types and objects.
4308
4309 @item -gnats
4310 @cindex @option{-gnats} (@command{gcc})
4311 Syntax check only.
4312
4313 @item -gnatS
4314 @cindex @option{-gnatS} (@command{gcc})
4315 Print package Standard.
4316
4317 @item -gnatt
4318 @cindex @option{-gnatt} (@command{gcc})
4319 Generate tree output file.
4320
4321 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4322 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4323 All compiler tables start at @var{nnn} times usual starting size.
4324
4325 @item -gnatu
4326 @cindex @option{-gnatu} (@command{gcc})
4327 List units for this compilation.
4328
4329 @item -gnatU
4330 @cindex @option{-gnatU} (@command{gcc})
4331 Tag all error messages with the unique string ``error:''
4332
4333 @item -gnatv
4334 @cindex @option{-gnatv} (@command{gcc})
4335 Verbose mode. Full error output with source lines to @file{stdout}.
4336
4337 @item -gnatV
4338 @cindex @option{-gnatV} (@command{gcc})
4339 Control level of validity checking (@pxref{Validity Checking}).
4340
4341 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4342 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4343 Warning mode where
4344 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4345 the exact warnings that
4346 are enabled or disabled (@pxref{Warning Message Control}).
4347
4348 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4349 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4350 Wide character encoding method
4351 @ifclear vms
4352 (@var{e}=n/h/u/s/e/8).
4353 @end ifclear
4354 @ifset vms
4355 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4356 @end ifset
4357
4358 @item -gnatx
4359 @cindex @option{-gnatx} (@command{gcc})
4360 Suppress generation of cross-reference information.
4361
4362 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4363 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4364 Enable built-in style checks (@pxref{Style Checking}).
4365
4366 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4367 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4368 Distribution stub generation and compilation
4369 @ifclear vms
4370 (@var{m}=r/c for receiver/caller stubs).
4371 @end ifclear
4372 @ifset vms
4373 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4374 to be generated and compiled).
4375 @end ifset
4376
4377 @item ^-I^/SEARCH=^@var{dir}
4378 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4379 @cindex RTL
4380 Direct GNAT to search the @var{dir} directory for source files needed by
4381 the current compilation
4382 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4383
4384 @item ^-I-^/NOCURRENT_DIRECTORY^
4385 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4386 @cindex RTL
4387 Except for the source file named in the command line, do not look for source
4388 files in the directory containing the source file named in the command line
4389 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4390
4391 @ifclear vms
4392 @item -mbig-switch
4393 @cindex @option{-mbig-switch} (@command{gcc})
4394 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4395 This standard gcc switch causes the compiler to use larger offsets in its
4396 jump table representation for @code{case} statements.
4397 This may result in less efficient code, but is sometimes necessary
4398 (for example on HP-UX targets)
4399 @cindex HP-UX and @option{-mbig-switch} option
4400 in order to compile large and/or nested @code{case} statements.
4401
4402 @item -o @var{file}
4403 @cindex @option{-o} (@command{gcc})
4404 This switch is used in @command{gcc} to redirect the generated object file
4405 and its associated ALI file. Beware of this switch with GNAT, because it may
4406 cause the object file and ALI file to have different names which in turn
4407 may confuse the binder and the linker.
4408 @end ifclear
4409
4410 @item -nostdinc
4411 @cindex @option{-nostdinc} (@command{gcc})
4412 Inhibit the search of the default location for the GNAT Run Time
4413 Library (RTL) source files.
4414
4415 @item -nostdlib
4416 @cindex @option{-nostdlib} (@command{gcc})
4417 Inhibit the search of the default location for the GNAT Run Time
4418 Library (RTL) ALI files.
4419
4420 @ifclear vms
4421 @item -O@ovar{n}
4422 @cindex @option{-O} (@command{gcc})
4423 @var{n} controls the optimization level.
4424
4425 @table @asis
4426 @item n = 0
4427 No optimization, the default setting if no @option{-O} appears
4428
4429 @item n = 1
4430 Normal optimization, the default if you specify @option{-O} without
4431 an operand. A good compromise between code quality and compilation
4432 time.
4433
4434 @item n = 2
4435 Extensive optimization, may improve execution time, possibly at the cost of
4436 substantially increased compilation time.
4437
4438 @item n = 3
4439 Same as @option{-O2}, and also includes inline expansion for small subprograms
4440 in the same unit.
4441
4442 @item n = s
4443 Optimize space usage
4444 @end table
4445
4446 @noindent
4447 See also @ref{Optimization Levels}.
4448 @end ifclear
4449
4450 @ifset vms
4451 @item  /NOOPTIMIZE
4452 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4453 Equivalent to @option{/OPTIMIZE=NONE}.
4454 This is the default behavior in the absence of an @option{/OPTIMIZE}
4455 qualifier.
4456
4457 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4458 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4459 Selects the level of optimization for your program. The supported
4460 keywords are as follows:
4461 @table @code
4462 @item   ALL
4463 Perform most optimizations, including those that
4464 are expensive.
4465 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4466 without keyword options.
4467
4468 @item   NONE
4469 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4470
4471 @item SOME
4472 Perform some optimizations, but omit ones that are costly.
4473
4474 @item   DEVELOPMENT
4475 Same as @code{SOME}.
4476
4477 @item INLINING
4478 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4479 automatic inlining of small subprograms within a unit
4480
4481 @item   UNROLL_LOOPS
4482 Try to unroll loops. This keyword may be specified together with
4483 any keyword above other than @code{NONE}. Loop unrolling
4484 usually, but not always, improves the performance of programs.
4485
4486 @item SPACE
4487 Optimize space usage
4488 @end table
4489
4490 @noindent
4491 See also @ref{Optimization Levels}.
4492 @end ifset
4493
4494 @ifclear vms
4495 @item -pass-exit-codes
4496 @cindex @option{-pass-exit-codes} (@command{gcc})
4497 Catch exit codes from the compiler and use the most meaningful as
4498 exit status.
4499 @end ifclear
4500
4501 @item --RTS=@var{rts-path}
4502 @cindex @option{--RTS} (@command{gcc})
4503 Specifies the default location of the runtime library. Same meaning as the
4504 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4505
4506 @item ^-S^/ASM^
4507 @cindex @option{^-S^/ASM^} (@command{gcc})
4508 ^Used in place of @option{-c} to^Used to^
4509 cause the assembler source file to be
4510 generated, using @file{^.s^.S^} as the extension,
4511 instead of the object file.
4512 This may be useful if you need to examine the generated assembly code.
4513
4514 @item ^-fverbose-asm^/VERBOSE_ASM^
4515 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4516 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4517 to cause the generated assembly code file to be annotated with variable
4518 names, making it significantly easier to follow.
4519
4520 @item ^-v^/VERBOSE^
4521 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4522 Show commands generated by the @command{gcc} driver. Normally used only for
4523 debugging purposes or if you need to be sure what version of the
4524 compiler you are executing.
4525
4526 @ifclear vms
4527 @item -V @var{ver}
4528 @cindex @option{-V} (@command{gcc})
4529 Execute @var{ver} version of the compiler. This is the @command{gcc}
4530 version, not the GNAT version.
4531 @end ifclear
4532
4533 @item ^-w^/NO_BACK_END_WARNINGS^
4534 @cindex @option{-w} (@command{gcc})
4535 Turn off warnings generated by the back end of the compiler. Use of
4536 this switch also causes the default for front end warnings to be set
4537 to suppress (as though @option{-gnatws} had appeared at the start of
4538 the options).
4539
4540 @end table
4541
4542 @ifclear vms
4543 @c Combining qualifiers does not work on VMS
4544 You may combine a sequence of GNAT switches into a single switch. For
4545 example, the combined switch
4546
4547 @cindex Combining GNAT switches
4548 @smallexample
4549 -gnatofi3
4550 @end smallexample
4551
4552 @noindent
4553 is equivalent to specifying the following sequence of switches:
4554
4555 @smallexample
4556 -gnato -gnatf -gnati3
4557 @end smallexample
4558 @end ifclear
4559
4560 @noindent
4561 The following restrictions apply to the combination of switches
4562 in this manner:
4563
4564 @itemize @bullet
4565 @item
4566 The switch @option{-gnatc} if combined with other switches must come
4567 first in the string.
4568
4569 @item
4570 The switch @option{-gnats} if combined with other switches must come
4571 first in the string.
4572
4573 @item
4574 The switches
4575 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4576 may not be combined with any other switches.
4577
4578 @ifclear vms
4579 @item
4580 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4581 switch), then all further characters in the switch are interpreted
4582 as style modifiers (see description of @option{-gnaty}).
4583
4584 @item
4585 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4586 switch), then all further characters in the switch are interpreted
4587 as debug flags (see description of @option{-gnatd}).
4588
4589 @item
4590 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4591 switch), then all further characters in the switch are interpreted
4592 as warning mode modifiers (see description of @option{-gnatw}).
4593
4594 @item
4595 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4596 switch), then all further characters in the switch are interpreted
4597 as validity checking options (@pxref{Validity Checking}).
4598 @end ifclear
4599 @end itemize
4600
4601 @node Output and Error Message Control
4602 @subsection Output and Error Message Control
4603 @findex stderr
4604
4605 @noindent
4606 The standard default format for error messages is called ``brief format''.
4607 Brief format messages are written to @file{stderr} (the standard error
4608 file) and have the following form:
4609
4610 @smallexample
4611 e.adb:3:04: Incorrect spelling of keyword "function"
4612 e.adb:4:20: ";" should be "is"
4613 @end smallexample
4614
4615 @noindent
4616 The first integer after the file name is the line number in the file,
4617 and the second integer is the column number within the line.
4618 @ifclear vms
4619 @code{GPS} can parse the error messages
4620 and point to the referenced character.
4621 @end ifclear
4622 The following switches provide control over the error message
4623 format:
4624
4625 @table @option
4626 @c !sort!
4627 @item -gnatv
4628 @cindex @option{-gnatv} (@command{gcc})
4629 @findex stdout
4630 @ifclear vms
4631 The v stands for verbose.
4632 @end ifclear
4633 The effect of this setting is to write long-format error
4634 messages to @file{stdout} (the standard output file.
4635 The same program compiled with the
4636 @option{-gnatv} switch would generate:
4637
4638 @smallexample
4639 @cartouche
4640 3. funcion X (Q : Integer)
4641    |
4642 >>> Incorrect spelling of keyword "function"
4643 4. return Integer;
4644                  |
4645 >>> ";" should be "is"
4646 @end cartouche
4647 @end smallexample
4648
4649 @noindent
4650 The vertical bar indicates the location of the error, and the @samp{>>>}
4651 prefix can be used to search for error messages. When this switch is
4652 used the only source lines output are those with errors.
4653
4654 @item -gnatl
4655 @cindex @option{-gnatl} (@command{gcc})
4656 @ifclear vms
4657 The @code{l} stands for list.
4658 @end ifclear
4659 This switch causes a full listing of
4660 the file to be generated. In the case where a body is
4661 compiled, the corresponding spec is also listed, along
4662 with any subunits. Typical output from compiling a package
4663 body @file{p.adb} might look like:
4664
4665 @smallexample @c ada
4666 @cartouche
4667  Compiling: p.adb
4668
4669      1. package body p is
4670      2.    procedure a;
4671      3.    procedure a is separate;
4672      4. begin
4673      5.    null
4674                |
4675         >>> missing ";"
4676
4677      6. end;
4678
4679 Compiling: p.ads
4680
4681      1. package p is
4682      2.    pragma Elaborate_Body
4683                                 |
4684         >>> missing ";"
4685
4686      3. end p;
4687
4688 Compiling: p-a.adb
4689
4690      1. separate p
4691                 |
4692         >>> missing "("
4693
4694      2. procedure a is
4695      3. begin
4696      4.    null
4697                |
4698         >>> missing ";"
4699
4700      5. end;
4701 @end cartouche
4702 @end smallexample
4703
4704 @noindent
4705 @findex stderr
4706 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4707 standard output is redirected, a brief summary is written to
4708 @file{stderr} (standard error) giving the number of error messages and
4709 warning messages generated.
4710
4711 @item -^gnatl^OUTPUT_FILE^=file
4712 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4713 This has the same effect as @option{-gnatl} except that the output is
4714 written to a file instead of to standard output. If the given name
4715 @file{fname} does not start with a period, then it is the full name
4716 of the file to be written. If @file{fname} is an extension, it is
4717 appended to the name of the file being compiled. For example, if
4718 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4719 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4720
4721 @item -gnatU
4722 @cindex @option{-gnatU} (@command{gcc})
4723 This switch forces all error messages to be preceded by the unique
4724 string ``error:''. This means that error messages take a few more
4725 characters in space, but allows easy searching for and identification
4726 of error messages.
4727
4728 @item -gnatb
4729 @cindex @option{-gnatb} (@command{gcc})
4730 @ifclear vms
4731 The @code{b} stands for brief.
4732 @end ifclear
4733 This switch causes GNAT to generate the
4734 brief format error messages to @file{stderr} (the standard error
4735 file) as well as the verbose
4736 format message or full listing (which as usual is written to
4737 @file{stdout} (the standard output file).
4738
4739 @item -gnatm=@var{n}
4740 @cindex @option{-gnatm} (@command{gcc})
4741 @ifclear vms
4742 The @code{m} stands for maximum.
4743 @end ifclear
4744 @var{n} is a decimal integer in the
4745 range of 1 to 999999 and limits the number of error or warning
4746 messages to be generated. For example, using
4747 @option{-gnatm2} might yield
4748
4749 @smallexample
4750 e.adb:3:04: Incorrect spelling of keyword "function"
4751 e.adb:5:35: missing ".."
4752 fatal error: maximum number of errors detected
4753 compilation abandoned
4754 @end smallexample
4755
4756 @noindent
4757 The default setting if
4758 no switch is given is 9999. If the number of warnings reaches this
4759 limit, then a message is output and further warnings are suppressed,
4760 but the compilation is continued. If the number of error messages
4761 reaches this limit, then a message is output and the compilation
4762 is abandoned. A value of zero means that no limit applies.
4763
4764 @noindent
4765 Note that the equal sign is optional, so the switches
4766 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4767
4768 @item -gnatf
4769 @cindex @option{-gnatf} (@command{gcc})
4770 @cindex Error messages, suppressing
4771 @ifclear vms
4772 The @code{f} stands for full.
4773 @end ifclear
4774 Normally, the compiler suppresses error messages that are likely to be
4775 redundant. This switch causes all error
4776 messages to be generated. In particular, in the case of
4777 references to undefined variables. If a given variable is referenced
4778 several times, the normal format of messages is
4779 @smallexample
4780 e.adb:7:07: "V" is undefined (more references follow)
4781 @end smallexample
4782
4783 @noindent
4784 where the parenthetical comment warns that there are additional
4785 references to the variable @code{V}. Compiling the same program with the
4786 @option{-gnatf} switch yields
4787
4788 @smallexample
4789 e.adb:7:07: "V" is undefined
4790 e.adb:8:07: "V" is undefined
4791 e.adb:8:12: "V" is undefined
4792 e.adb:8:16: "V" is undefined
4793 e.adb:9:07: "V" is undefined
4794 e.adb:9:12: "V" is undefined
4795 @end smallexample
4796
4797 @noindent
4798 The @option{-gnatf} switch also generates additional information for
4799 some error messages.  Some examples are:
4800
4801 @itemize @bullet
4802 @item
4803 Details on possibly non-portable unchecked conversion
4804 @item
4805 List possible interpretations for ambiguous calls
4806 @item
4807 Additional details on incorrect parameters
4808 @end itemize
4809
4810 @item -gnatjnn
4811 @cindex @option{-gnatjnn} (@command{gcc})
4812 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4813 with continuation lines are treated as though the continuation lines were
4814 separate messages (and so a warning with two continuation lines counts as
4815 three warnings, and is listed as three separate messages).
4816
4817 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4818 messages are output in a different manner. A message and all its continuation
4819 lines are treated as a unit, and count as only one warning or message in the
4820 statistics totals. Furthermore, the message is reformatted so that no line
4821 is longer than nn characters.
4822
4823 @item -gnatq
4824 @cindex @option{-gnatq} (@command{gcc})
4825 @ifclear vms
4826 The @code{q} stands for quit (really ``don't quit'').
4827 @end ifclear
4828 In normal operation mode, the compiler first parses the program and
4829 determines if there are any syntax errors. If there are, appropriate
4830 error messages are generated and compilation is immediately terminated.
4831 This switch tells
4832 GNAT to continue with semantic analysis even if syntax errors have been
4833 found. This may enable the detection of more errors in a single run. On
4834 the other hand, the semantic analyzer is more likely to encounter some
4835 internal fatal error when given a syntactically invalid tree.
4836
4837 @item -gnatQ
4838 @cindex @option{-gnatQ} (@command{gcc})
4839 In normal operation mode, the @file{ALI} file is not generated if any
4840 illegalities are detected in the program. The use of @option{-gnatQ} forces
4841 generation of the @file{ALI} file. This file is marked as being in
4842 error, so it cannot be used for binding purposes, but it does contain
4843 reasonably complete cross-reference information, and thus may be useful
4844 for use by tools (e.g., semantic browsing tools or integrated development
4845 environments) that are driven from the @file{ALI} file. This switch
4846 implies @option{-gnatq}, since the semantic phase must be run to get a
4847 meaningful ALI file.
4848
4849 In addition, if @option{-gnatt} is also specified, then the tree file is
4850 generated even if there are illegalities. It may be useful in this case
4851 to also specify @option{-gnatq} to ensure that full semantic processing
4852 occurs. The resulting tree file can be processed by ASIS, for the purpose
4853 of providing partial information about illegal units, but if the error
4854 causes the tree to be badly malformed, then ASIS may crash during the
4855 analysis.
4856
4857 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4858 being in error, @command{gnatmake} will attempt to recompile the source when it
4859 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4860
4861 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4862 since ALI files are never generated if @option{-gnats} is set.
4863
4864 @end table
4865
4866 @node Warning Message Control
4867 @subsection Warning Message Control
4868 @cindex Warning messages
4869 @noindent
4870 In addition to error messages, which correspond to illegalities as defined
4871 in the Ada Reference Manual, the compiler detects two kinds of warning
4872 situations.
4873
4874 First, the compiler considers some constructs suspicious and generates a
4875 warning message to alert you to a possible error. Second, if the
4876 compiler detects a situation that is sure to raise an exception at
4877 run time, it generates a warning message. The following shows an example
4878 of warning messages:
4879 @smallexample
4880 e.adb:4:24: warning: creation of object may raise Storage_Error
4881 e.adb:10:17: warning: static value out of range
4882 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4883 @end smallexample
4884
4885 @noindent
4886 GNAT considers a large number of situations as appropriate
4887 for the generation of warning messages. As always, warnings are not
4888 definite indications of errors. For example, if you do an out-of-range
4889 assignment with the deliberate intention of raising a
4890 @code{Constraint_Error} exception, then the warning that may be
4891 issued does not indicate an error. Some of the situations for which GNAT
4892 issues warnings (at least some of the time) are given in the following
4893 list. This list is not complete, and new warnings are often added to
4894 subsequent versions of GNAT. The list is intended to give a general idea
4895 of the kinds of warnings that are generated.
4896
4897 @itemize @bullet
4898 @item
4899 Possible infinitely recursive calls
4900
4901 @item
4902 Out-of-range values being assigned
4903
4904 @item
4905 Possible order of elaboration problems
4906
4907 @item
4908 Assertions (pragma Assert) that are sure to fail
4909
4910 @item
4911 Unreachable code
4912
4913 @item
4914 Address clauses with possibly unaligned values, or where an attempt is
4915 made to overlay a smaller variable with a larger one.
4916
4917 @item
4918 Fixed-point type declarations with a null range
4919
4920 @item
4921 Direct_IO or Sequential_IO instantiated with a type that has access values
4922
4923 @item
4924 Variables that are never assigned a value
4925
4926 @item
4927 Variables that are referenced before being initialized
4928
4929 @item
4930 Task entries with no corresponding @code{accept} statement
4931
4932 @item
4933 Duplicate accepts for the same task entry in a @code{select}
4934
4935 @item
4936 Objects that take too much storage
4937
4938 @item
4939 Unchecked conversion between types of differing sizes
4940
4941 @item
4942 Missing @code{return} statement along some execution path in a function
4943
4944 @item
4945 Incorrect (unrecognized) pragmas
4946
4947 @item
4948 Incorrect external names
4949
4950 @item
4951 Allocation from empty storage pool
4952
4953 @item
4954 Potentially blocking operation in protected type
4955
4956 @item
4957 Suspicious parenthesization of expressions
4958
4959 @item
4960 Mismatching bounds in an aggregate
4961
4962 @item
4963 Attempt to return local value by reference
4964
4965 @item
4966 Premature instantiation of a generic body
4967
4968 @item
4969 Attempt to pack aliased components
4970
4971 @item
4972 Out of bounds array subscripts
4973
4974 @item
4975 Wrong length on string assignment
4976
4977 @item
4978 Violations of style rules if style checking is enabled
4979
4980 @item
4981 Unused @code{with} clauses
4982
4983 @item
4984 @code{Bit_Order} usage that does not have any effect
4985
4986 @item
4987 @code{Standard.Duration} used to resolve universal fixed expression
4988
4989 @item
4990 Dereference of possibly null value
4991
4992 @item
4993 Declaration that is likely to cause storage error
4994
4995 @item
4996 Internal GNAT unit @code{with}'ed by application unit
4997
4998 @item
4999 Values known to be out of range at compile time
5000
5001 @item
5002 Unreferenced labels and variables
5003
5004 @item
5005 Address overlays that could clobber memory
5006
5007 @item
5008 Unexpected initialization when address clause present
5009
5010 @item
5011 Bad alignment for address clause
5012
5013 @item
5014 Useless type conversions
5015
5016 @item
5017 Redundant assignment statements and other redundant constructs
5018
5019 @item
5020 Useless exception handlers
5021
5022 @item
5023 Accidental hiding of name by child unit
5024
5025 @item
5026 Access before elaboration detected at compile time
5027
5028 @item
5029 A range in a @code{for} loop that is known to be null or might be null
5030
5031 @end itemize
5032
5033 @noindent
5034 The following section lists compiler switches that are available
5035 to control the handling of warning messages. It is also possible
5036 to exercise much finer control over what warnings are issued and
5037 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5038 gnat_rm, GNAT Reference manual}.
5039
5040 @table @option
5041 @c !sort!
5042 @item -gnatwa
5043 @emph{Activate all optional errors.}
5044 @cindex @option{-gnatwa} (@command{gcc})
5045 This switch activates most optional warning messages, see remaining list
5046 in this section for details on optional warning messages that can be
5047 individually controlled.  The warnings that are not turned on by this
5048 switch are
5049 @option{-gnatwd} (implicit dereferencing),
5050 @option{-gnatwh} (hiding),
5051 @option{-gnatwl} (elaboration warnings),
5052 @option{-gnatw.o} (warn on values set by out parameters ignored)
5053 and @option{-gnatwt} (tracking of deleted conditional code).
5054 All other optional warnings are turned on.
5055
5056 @item -gnatwA
5057 @emph{Suppress all optional errors.}
5058 @cindex @option{-gnatwA} (@command{gcc})
5059 This switch suppresses all optional warning messages, see remaining list
5060 in this section for details on optional warning messages that can be
5061 individually controlled.
5062
5063 @item -gnatw.a
5064 @emph{Activate warnings on failing assertions.}
5065 @cindex @option{-gnatw.a} (@command{gcc})
5066 @cindex Assert failures
5067 This switch activates warnings for assertions where the compiler can tell at
5068 compile time that the assertion will fail. Note that this warning is given
5069 even if assertions are disabled. The default is that such warnings are
5070 generated.
5071
5072 @item -gnatw.A
5073 @emph{Suppress warnings on failing assertions.}
5074 @cindex @option{-gnatw.A} (@command{gcc})
5075 @cindex Assert failures
5076 This switch suppresses warnings for assertions where the compiler can tell at
5077 compile time that the assertion will fail.
5078
5079 @item -gnatwb
5080 @emph{Activate warnings on bad fixed values.}
5081 @cindex @option{-gnatwb} (@command{gcc})
5082 @cindex Bad fixed values
5083 @cindex Fixed-point Small value
5084 @cindex Small value
5085 This switch activates warnings for static fixed-point expressions whose
5086 value is not an exact multiple of Small. Such values are implementation
5087 dependent, since an implementation is free to choose either of the multiples
5088 that surround the value. GNAT always chooses the closer one, but this is not
5089 required behavior, and it is better to specify a value that is an exact
5090 multiple, ensuring predictable execution. The default is that such warnings
5091 are not generated.
5092
5093 @item -gnatwB
5094 @emph{Suppress warnings on bad fixed values.}
5095 @cindex @option{-gnatwB} (@command{gcc})
5096 This switch suppresses warnings for static fixed-point expressions whose
5097 value is not an exact multiple of Small.
5098
5099 @item -gnatw.b
5100 @emph{Activate warnings on biased representation.}
5101 @cindex @option{-gnatw.b} (@command{gcc})
5102 @cindex Biased representation
5103 This switch activates warnings when a size clause, value size clause, component
5104 clause, or component size clause forces the use of biased representation for an
5105 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5106 to represent 10/11). The default is that such warnings are generated.
5107
5108 @item -gnatw.B
5109 @emph{Suppress warnings on biased representation.}
5110 @cindex @option{-gnatwB} (@command{gcc})
5111 This switch suppresses warnings for representation clauses that force the use
5112 of biased representation.
5113
5114 @item -gnatwc
5115 @emph{Activate warnings on conditionals.}
5116 @cindex @option{-gnatwc} (@command{gcc})
5117 @cindex Conditionals, constant
5118 This switch activates warnings for conditional expressions used in
5119 tests that are known to be True or False at compile time. The default
5120 is that such warnings are not generated.
5121 Note that this warning does
5122 not get issued for the use of boolean variables or constants whose
5123 values are known at compile time, since this is a standard technique
5124 for conditional compilation in Ada, and this would generate too many
5125 false positive warnings.
5126
5127 This warning option also activates a special test for comparisons using
5128 the operators ``>='' and`` <=''.
5129 If the compiler can tell that only the equality condition is possible,
5130 then it will warn that the ``>'' or ``<'' part of the test
5131 is useless and that the operator could be replaced by ``=''.
5132 An example would be comparing a @code{Natural} variable <= 0.
5133
5134 This warning option also generates warnings if
5135 one or both tests is optimized away in a membership test for integer
5136 values if the result can be determined at compile time. Range tests on
5137 enumeration types are not included, since it is common for such tests
5138 to include an end point.
5139
5140 This warning can also be turned on using @option{-gnatwa}.
5141
5142 @item -gnatwC
5143 @emph{Suppress warnings on conditionals.}
5144 @cindex @option{-gnatwC} (@command{gcc})
5145 This switch suppresses warnings for conditional expressions used in
5146 tests that are known to be True or False at compile time.
5147
5148 @item -gnatw.c
5149 @emph{Activate warnings on missing component clauses.}
5150 @cindex @option{-gnatw.c} (@command{gcc})
5151 @cindex Component clause, missing
5152 This switch activates warnings for record components where a record
5153 representation clause is present and has component clauses for the
5154 majority, but not all, of the components. A warning is given for each
5155 component for which no component clause is present.
5156
5157 This warning can also be turned on using @option{-gnatwa}.
5158
5159 @item -gnatw.C
5160 @emph{Suppress warnings on missing component clauses.}
5161 @cindex @option{-gnatwC} (@command{gcc})
5162 This switch suppresses warnings for record components that are
5163 missing a component clause in the situation described above.
5164
5165 @item -gnatwd
5166 @emph{Activate warnings on implicit dereferencing.}
5167 @cindex @option{-gnatwd} (@command{gcc})
5168 If this switch is set, then the use of a prefix of an access type
5169 in an indexed component, slice, or selected component without an
5170 explicit @code{.all} will generate a warning. With this warning
5171 enabled, access checks occur only at points where an explicit
5172 @code{.all} appears in the source code (assuming no warnings are
5173 generated as a result of this switch). The default is that such
5174 warnings are not generated.
5175 Note that @option{-gnatwa} does not affect the setting of
5176 this warning option.
5177
5178 @item -gnatwD
5179 @emph{Suppress warnings on implicit dereferencing.}
5180 @cindex @option{-gnatwD} (@command{gcc})
5181 @cindex Implicit dereferencing
5182 @cindex Dereferencing, implicit
5183 This switch suppresses warnings for implicit dereferences in
5184 indexed components, slices, and selected components.
5185
5186 @item -gnatwe
5187 @emph{Treat warnings as errors.}
5188 @cindex @option{-gnatwe} (@command{gcc})
5189 @cindex Warnings, treat as error
5190 This switch causes warning messages to be treated as errors.
5191 The warning string still appears, but the warning messages are counted
5192 as errors, and prevent the generation of an object file.
5193
5194 @item -gnatw.e
5195 @emph{Activate every optional warning}
5196 @cindex @option{-gnatw.e} (@command{gcc})
5197 @cindex Warnings, activate every optional warning
5198 This switch activates all optional warnings, including those which
5199 are not activated by @code{-gnatwa}.
5200
5201 @item -gnatwf
5202 @emph{Activate warnings on unreferenced formals.}
5203 @cindex @option{-gnatwf} (@command{gcc})
5204 @cindex Formals, unreferenced
5205 This switch causes a warning to be generated if a formal parameter
5206 is not referenced in the body of the subprogram. This warning can
5207 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5208 default is that these warnings are not generated.
5209
5210 @item -gnatwF
5211 @emph{Suppress warnings on unreferenced formals.}
5212 @cindex @option{-gnatwF} (@command{gcc})
5213 This switch suppresses warnings for unreferenced formal
5214 parameters. Note that the
5215 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5216 effect of warning on unreferenced entities other than subprogram
5217 formals.
5218
5219 @item -gnatwg
5220 @emph{Activate warnings on unrecognized pragmas.}
5221 @cindex @option{-gnatwg} (@command{gcc})
5222 @cindex Pragmas, unrecognized
5223 This switch causes a warning to be generated if an unrecognized
5224 pragma is encountered. Apart from issuing this warning, the
5225 pragma is ignored and has no effect. This warning can
5226 also be turned on using @option{-gnatwa}. The default
5227 is that such warnings are issued (satisfying the Ada Reference
5228 Manual requirement that such warnings appear).
5229
5230 @item -gnatwG
5231 @emph{Suppress warnings on unrecognized pragmas.}
5232 @cindex @option{-gnatwG} (@command{gcc})
5233 This switch suppresses warnings for unrecognized pragmas.
5234
5235 @item -gnatwh
5236 @emph{Activate warnings on hiding.}
5237 @cindex @option{-gnatwh} (@command{gcc})
5238 @cindex Hiding of Declarations
5239 This switch activates warnings on hiding declarations.
5240 A declaration is considered hiding
5241 if it is for a non-overloadable entity, and it declares an entity with the
5242 same name as some other entity that is directly or use-visible. The default
5243 is that such warnings are not generated.
5244 Note that @option{-gnatwa} does not affect the setting of this warning option.
5245
5246 @item -gnatwH
5247 @emph{Suppress warnings on hiding.}
5248 @cindex @option{-gnatwH} (@command{gcc})
5249 This switch suppresses warnings on hiding declarations.
5250
5251 @item -gnatwi
5252 @emph{Activate warnings on implementation units.}
5253 @cindex @option{-gnatwi} (@command{gcc})
5254 This switch activates warnings for a @code{with} of an internal GNAT
5255 implementation unit, defined as any unit from the @code{Ada},
5256 @code{Interfaces}, @code{GNAT},
5257 ^^@code{DEC},^ or @code{System}
5258 hierarchies that is not
5259 documented in either the Ada Reference Manual or the GNAT
5260 Programmer's Reference Manual. Such units are intended only
5261 for internal implementation purposes and should not be @code{with}'ed
5262 by user programs. The default is that such warnings are generated
5263 This warning can also be turned on using @option{-gnatwa}.
5264
5265 @item -gnatwI
5266 @emph{Disable warnings on implementation units.}
5267 @cindex @option{-gnatwI} (@command{gcc})
5268 This switch disables warnings for a @code{with} of an internal GNAT
5269 implementation unit.
5270
5271 @item -gnatwj
5272 @emph{Activate warnings on obsolescent features (Annex J).}
5273 @cindex @option{-gnatwj} (@command{gcc})
5274 @cindex Features, obsolescent
5275 @cindex Obsolescent features
5276 If this warning option is activated, then warnings are generated for
5277 calls to subprograms marked with @code{pragma Obsolescent} and
5278 for use of features in Annex J of the Ada Reference Manual. In the
5279 case of Annex J, not all features are flagged. In particular use
5280 of the renamed packages (like @code{Text_IO}) and use of package
5281 @code{ASCII} are not flagged, since these are very common and
5282 would generate many annoying positive warnings. The default is that
5283 such warnings are not generated. This warning is also turned on by
5284 the use of @option{-gnatwa}.
5285
5286 In addition to the above cases, warnings are also generated for
5287 GNAT features that have been provided in past versions but which
5288 have been superseded (typically by features in the new Ada standard).
5289 For example, @code{pragma Ravenscar} will be flagged since its
5290 function is replaced by @code{pragma Profile(Ravenscar)}.
5291
5292 Note that this warning option functions differently from the
5293 restriction @code{No_Obsolescent_Features} in two respects.
5294 First, the restriction applies only to annex J features.
5295 Second, the restriction does flag uses of package @code{ASCII}.
5296
5297 @item -gnatwJ
5298 @emph{Suppress warnings on obsolescent features (Annex J).}
5299 @cindex @option{-gnatwJ} (@command{gcc})
5300 This switch disables warnings on use of obsolescent features.
5301
5302 @item -gnatwk
5303 @emph{Activate warnings on variables that could be constants.}
5304 @cindex @option{-gnatwk} (@command{gcc})
5305 This switch activates warnings for variables that are initialized but
5306 never modified, and then could be declared constants. The default is that
5307 such warnings are not given.
5308 This warning can also be turned on using @option{-gnatwa}.
5309
5310 @item -gnatwK
5311 @emph{Suppress warnings on variables that could be constants.}
5312 @cindex @option{-gnatwK} (@command{gcc})
5313 This switch disables warnings on variables that could be declared constants.
5314
5315 @item -gnatwl
5316 @emph{Activate warnings for elaboration pragmas.}
5317 @cindex @option{-gnatwl} (@command{gcc})
5318 @cindex Elaboration, warnings
5319 This switch activates warnings on missing
5320 @code{Elaborate_All} and @code{Elaborate} pragmas.
5321 See the section in this guide on elaboration checking for details on
5322 when such pragmas should be used. In dynamic elaboration mode, this switch
5323 generations warnings about the need to add elaboration pragmas. Note however,
5324 that if you blindly follow these warnings, and add @code{Elaborate_All}
5325 warnings wherever they are recommended, you basically end up with the
5326 equivalent of the static elaboration model, which may not be what you want for
5327 legacy code for which the static model does not work.
5328
5329 For the static model, the messages generated are labeled "info:" (for
5330 information messages). They are not warnings to add elaboration pragmas,
5331 merely informational messages showing what implicit elaboration pragmas
5332 have been added, for use in analyzing elaboration circularity problems.
5333
5334 Warnings are also generated if you
5335 are using the static mode of elaboration, and a @code{pragma Elaborate}
5336 is encountered. The default is that such warnings
5337 are not generated.
5338 This warning is not automatically turned on by the use of @option{-gnatwa}.
5339
5340 @item -gnatwL
5341 @emph{Suppress warnings for elaboration pragmas.}
5342 @cindex @option{-gnatwL} (@command{gcc})
5343 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5344 See the section in this guide on elaboration checking for details on
5345 when such pragmas should be used.
5346
5347 @item -gnatwm
5348 @emph{Activate warnings on modified but unreferenced variables.}
5349 @cindex @option{-gnatwm} (@command{gcc})
5350 This switch activates warnings for variables that are assigned (using
5351 an initialization value or with one or more assignment statements) but
5352 whose value is never read. The warning is suppressed for volatile
5353 variables and also for variables that are renamings of other variables
5354 or for which an address clause is given.
5355 This warning can also be turned on using @option{-gnatwa}.
5356 The default is that these warnings are not given.
5357
5358 @item -gnatwM
5359 @emph{Disable warnings on modified but unreferenced variables.}
5360 @cindex @option{-gnatwM} (@command{gcc})
5361 This switch disables warnings for variables that are assigned or
5362 initialized, but never read.
5363
5364 @item -gnatw.m
5365 @emph{Activate warnings on suspicious modulus values.}
5366 @cindex @option{-gnatw.m} (@command{gcc})
5367 This switch activates warnings for modulus values that seem suspicious.
5368 The cases caught are where the size is the same as the modulus (e.g.
5369 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5370 with no size clause. The guess in both cases is that 2**x was intended
5371 rather than x. The default is that these warnings are given.
5372
5373 @item -gnatw.M
5374 @emph{Disable warnings on suspicious modulus values.}
5375 @cindex @option{-gnatw.M} (@command{gcc})
5376 This switch disables warnings for suspicious modulus values.
5377
5378 @item -gnatwn
5379 @emph{Set normal warnings mode.}
5380 @cindex @option{-gnatwn} (@command{gcc})
5381 This switch sets normal warning mode, in which enabled warnings are
5382 issued and treated as warnings rather than errors. This is the default
5383 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5384 an explicit @option{-gnatws} or
5385 @option{-gnatwe}. It also cancels the effect of the
5386 implicit @option{-gnatwe} that is activated by the
5387 use of @option{-gnatg}.
5388
5389 @item -gnatwo
5390 @emph{Activate warnings on address clause overlays.}
5391 @cindex @option{-gnatwo} (@command{gcc})
5392 @cindex Address Clauses, warnings
5393 This switch activates warnings for possibly unintended initialization
5394 effects of defining address clauses that cause one variable to overlap
5395 another. The default is that such warnings are generated.
5396 This warning can also be turned on using @option{-gnatwa}.
5397
5398 @item -gnatwO
5399 @emph{Suppress warnings on address clause overlays.}
5400 @cindex @option{-gnatwO} (@command{gcc})
5401 This switch suppresses warnings on possibly unintended initialization
5402 effects of defining address clauses that cause one variable to overlap
5403 another.
5404
5405 @item -gnatw.o
5406 @emph{Activate warnings on modified but unreferenced out parameters.}
5407 @cindex @option{-gnatw.o} (@command{gcc})
5408 This switch activates warnings for variables that are modified by using
5409 them as actuals for a call to a procedure with an out mode formal, where
5410 the resulting assigned value is never read. It is applicable in the case
5411 where there is more than one out mode formal. If there is only one out
5412 mode formal, the warning is issued by default (controlled by -gnatwu).
5413 The warning is suppressed for volatile
5414 variables and also for variables that are renamings of other variables
5415 or for which an address clause is given.
5416 The default is that these warnings are not given. Note that this warning
5417 is not included in -gnatwa, it must be activated explicitly.
5418
5419 @item -gnatw.O
5420 @emph{Disable warnings on modified but unreferenced out parameters.}
5421 @cindex @option{-gnatw.O} (@command{gcc})
5422 This switch suppresses warnings for variables that are modified by using
5423 them as actuals for a call to a procedure with an out mode formal, where
5424 the resulting assigned value is never read.
5425
5426 @item -gnatwp
5427 @emph{Activate warnings on ineffective pragma Inlines.}
5428 @cindex @option{-gnatwp} (@command{gcc})
5429 @cindex Inlining, warnings
5430 This switch activates warnings for failure of front end inlining
5431 (activated by @option{-gnatN}) to inline a particular call. There are
5432 many reasons for not being able to inline a call, including most
5433 commonly that the call is too complex to inline. The default is
5434 that such warnings are not given.
5435 This warning can also be turned on using @option{-gnatwa}.
5436 Warnings on ineffective inlining by the gcc back-end can be activated
5437 separately, using the gcc switch -Winline.
5438
5439 @item -gnatwP
5440 @emph{Suppress warnings on ineffective pragma Inlines.}
5441 @cindex @option{-gnatwP} (@command{gcc})
5442 This switch suppresses warnings on ineffective pragma Inlines. If the
5443 inlining mechanism cannot inline a call, it will simply ignore the
5444 request silently.
5445
5446 @item -gnatw.p
5447 @emph{Activate warnings on parameter ordering.}
5448 @cindex @option{-gnatw.p} (@command{gcc})
5449 @cindex Parameter order, warnings
5450 This switch activates warnings for cases of suspicious parameter
5451 ordering when the list of arguments are all simple identifiers that
5452 match the names of the formals, but are in a different order. The
5453 warning is suppressed if any use of named parameter notation is used,
5454 so this is the appropriate way to suppress a false positive (and
5455 serves to emphasize that the "misordering" is deliberate). The
5456 default is
5457 that such warnings are not given.
5458 This warning can also be turned on using @option{-gnatwa}.
5459
5460 @item -gnatw.P
5461 @emph{Suppress warnings on parameter ordering.}
5462 @cindex @option{-gnatw.P} (@command{gcc})
5463 This switch suppresses warnings on cases of suspicious parameter
5464 ordering.
5465
5466 @item -gnatwq
5467 @emph{Activate warnings on questionable missing parentheses.}
5468 @cindex @option{-gnatwq} (@command{gcc})
5469 @cindex Parentheses, warnings
5470 This switch activates warnings for cases where parentheses are not used and
5471 the result is potential ambiguity from a readers point of view. For example
5472 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5473 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5474 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5475 follow the rule of always parenthesizing to make the association clear, and
5476 this warning switch warns if such parentheses are not present. The default
5477 is that these warnings are given.
5478 This warning can also be turned on using @option{-gnatwa}.
5479
5480 @item -gnatwQ
5481 @emph{Suppress warnings on questionable missing parentheses.}
5482 @cindex @option{-gnatwQ} (@command{gcc})
5483 This switch suppresses warnings for cases where the association is not
5484 clear and the use of parentheses is preferred.
5485
5486 @item -gnatwr
5487 @emph{Activate warnings on redundant constructs.}
5488 @cindex @option{-gnatwr} (@command{gcc})
5489 This switch activates warnings for redundant constructs. The following
5490 is the current list of constructs regarded as redundant:
5491
5492 @itemize @bullet
5493 @item
5494 Assignment of an item to itself.
5495 @item
5496 Type conversion that converts an expression to its own type.
5497 @item
5498 Use of the attribute @code{Base} where @code{typ'Base} is the same
5499 as @code{typ}.
5500 @item
5501 Use of pragma @code{Pack} when all components are placed by a record
5502 representation clause.
5503 @item
5504 Exception handler containing only a reraise statement (raise with no
5505 operand) which has no effect.
5506 @item
5507 Use of the operator abs on an operand that is known at compile time
5508 to be non-negative
5509 @item
5510 Comparison of boolean expressions to an explicit True value.
5511 @end itemize
5512
5513 This warning can also be turned on using @option{-gnatwa}.
5514 The default is that warnings for redundant constructs are not given.
5515
5516 @item -gnatwR
5517 @emph{Suppress warnings on redundant constructs.}
5518 @cindex @option{-gnatwR} (@command{gcc})
5519 This switch suppresses warnings for redundant constructs.
5520
5521 @item -gnatw.r
5522 @emph{Activate warnings for object renaming function.}
5523 @cindex @option{-gnatw.r} (@command{gcc})
5524 This switch activates warnings for an object renaming that renames a
5525 function call, which is equivalent to a constant declaration (as
5526 opposed to renaming the function itself).  The default is that these
5527 warnings are given.  This warning can also be turned on using
5528 @option{-gnatwa}.
5529
5530 @item -gnatw.R
5531 @emph{Suppress warnings for object renaming function.}
5532 @cindex @option{-gnatwT} (@command{gcc})
5533 This switch suppresses warnings for object renaming function.
5534
5535 @item -gnatws
5536 @emph{Suppress all warnings.}
5537 @cindex @option{-gnatws} (@command{gcc})
5538 This switch completely suppresses the
5539 output of all warning messages from the GNAT front end.
5540 Note that it does not suppress warnings from the @command{gcc} back end.
5541 To suppress these back end warnings as well, use the switch @option{-w}
5542 in addition to @option{-gnatws}.
5543
5544 @item -gnatwt
5545 @emph{Activate warnings for tracking of deleted conditional code.}
5546 @cindex @option{-gnatwt} (@command{gcc})
5547 @cindex Deactivated code, warnings
5548 @cindex Deleted code, warnings
5549 This switch activates warnings for tracking of code in conditionals (IF and
5550 CASE statements) that is detected to be dead code which cannot be executed, and
5551 which is removed by the front end. This warning is off by default, and is not
5552 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5553 useful for detecting deactivated code in certified applications.
5554
5555 @item -gnatwT
5556 @emph{Suppress warnings for tracking of deleted conditional code.}
5557 @cindex @option{-gnatwT} (@command{gcc})
5558 This switch suppresses warnings for tracking of deleted conditional code.
5559
5560 @item -gnatwu
5561 @emph{Activate warnings on unused entities.}
5562 @cindex @option{-gnatwu} (@command{gcc})
5563 This switch activates warnings to be generated for entities that
5564 are declared but not referenced, and for units that are @code{with}'ed
5565 and not
5566 referenced. In the case of packages, a warning is also generated if
5567 no entities in the package are referenced. This means that if the package
5568 is referenced but the only references are in @code{use}
5569 clauses or @code{renames}
5570 declarations, a warning is still generated. A warning is also generated
5571 for a generic package that is @code{with}'ed but never instantiated.
5572 In the case where a package or subprogram body is compiled, and there
5573 is a @code{with} on the corresponding spec
5574 that is only referenced in the body,
5575 a warning is also generated, noting that the
5576 @code{with} can be moved to the body. The default is that
5577 such warnings are not generated.
5578 This switch also activates warnings on unreferenced formals
5579 (it includes the effect of @option{-gnatwf}).
5580 This warning can also be turned on using @option{-gnatwa}.
5581
5582 @item -gnatwU
5583 @emph{Suppress warnings on unused entities.}
5584 @cindex @option{-gnatwU} (@command{gcc})
5585 This switch suppresses warnings for unused entities and packages.
5586 It also turns off warnings on unreferenced formals (and thus includes
5587 the effect of @option{-gnatwF}).
5588
5589 @item -gnatwv
5590 @emph{Activate warnings on unassigned variables.}
5591 @cindex @option{-gnatwv} (@command{gcc})
5592 @cindex Unassigned variable warnings
5593 This switch activates warnings for access to variables which
5594 may not be properly initialized. The default is that
5595 such warnings are generated.
5596 This warning can also be turned on using @option{-gnatwa}.
5597
5598 @item -gnatwV
5599 @emph{Suppress warnings on unassigned variables.}
5600 @cindex @option{-gnatwV} (@command{gcc})
5601 This switch suppresses warnings for access to variables which
5602 may not be properly initialized.
5603 For variables of a composite type, the warning can also be suppressed in
5604 Ada 2005 by using a default initialization with a box. For example, if
5605 Table is an array of records whose components are only partially uninitialized,
5606 then the following code:
5607
5608 @smallexample @c ada
5609    Tab : Table := (others => <>);
5610 @end smallexample
5611
5612 will suppress warnings on subsequent statements that access components
5613 of variable Tab.
5614
5615 @item -gnatww
5616 @emph{Activate warnings on wrong low bound assumption.}
5617 @cindex @option{-gnatww} (@command{gcc})
5618 @cindex String indexing warnings
5619 This switch activates warnings for indexing an unconstrained string parameter
5620 with a literal or S'Length. This is a case where the code is assuming that the
5621 low bound is one, which is in general not true (for example when a slice is
5622 passed). The default is that such warnings are generated.
5623 This warning can also be turned on using @option{-gnatwa}.
5624
5625 @item -gnatwW
5626 @emph{Suppress warnings on wrong low bound assumption.}
5627 @cindex @option{-gnatwW} (@command{gcc})
5628 This switch suppresses warnings for indexing an unconstrained string parameter
5629 with a literal or S'Length. Note that this warning can also be suppressed
5630 in a particular case by adding an
5631 assertion that the lower bound is 1,
5632 as shown in the following example.
5633
5634 @smallexample @c ada
5635    procedure K (S : String) is
5636       pragma Assert (S'First = 1);
5637       @dots{}
5638 @end smallexample
5639
5640 @item -gnatw.w
5641 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5642 @cindex @option{-gnatw.w} (@command{gcc})
5643 @cindex Warnings Off control
5644 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5645 where either the pragma is entirely useless (because it suppresses no
5646 warnings), or it could be replaced by @code{pragma Unreferenced} or
5647 @code{pragma Unmodified}.The default is that these warnings are not given.
5648 Note that this warning is not included in -gnatwa, it must be
5649 activated explicitly.
5650
5651 @item -gnatw.W
5652 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5653 @cindex @option{-gnatw.W} (@command{gcc})
5654 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5655
5656 @item -gnatwx
5657 @emph{Activate warnings on Export/Import pragmas.}
5658 @cindex @option{-gnatwx} (@command{gcc})
5659 @cindex Export/Import pragma warnings
5660 This switch activates warnings on Export/Import pragmas when
5661 the compiler detects a possible conflict between the Ada and
5662 foreign language calling sequences. For example, the use of
5663 default parameters in a convention C procedure is dubious
5664 because the C compiler cannot supply the proper default, so
5665 a warning is issued. The default is that such warnings are
5666 generated.
5667 This warning can also be turned on using @option{-gnatwa}.
5668
5669 @item -gnatwX
5670 @emph{Suppress warnings on Export/Import pragmas.}
5671 @cindex @option{-gnatwX} (@command{gcc})
5672 This switch suppresses warnings on Export/Import pragmas.
5673 The sense of this is that you are telling the compiler that
5674 you know what you are doing in writing the pragma, and it
5675 should not complain at you.
5676
5677 @item -gnatw.x
5678 @emph{Activate warnings for No_Exception_Propagation mode.}
5679 @cindex @option{-gnatwm} (@command{gcc})
5680 This switch activates warnings for exception usage when pragma Restrictions
5681 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5682 explicit exception raises which are not covered by a local handler, and for
5683 exception handlers which do not cover a local raise. The default is that these
5684 warnings are not given.
5685
5686 @item -gnatw.X
5687 @emph{Disable warnings for No_Exception_Propagation mode.}
5688 This switch disables warnings for exception usage when pragma Restrictions
5689 (No_Exception_Propagation) is in effect.
5690
5691 @item -gnatwy
5692 @emph{Activate warnings for Ada 2005 compatibility issues.}
5693 @cindex @option{-gnatwy} (@command{gcc})
5694 @cindex Ada 2005 compatibility issues warnings
5695 For the most part Ada 2005 is upwards compatible with Ada 95,
5696 but there are some exceptions (for example the fact that
5697 @code{interface} is now a reserved word in Ada 2005). This
5698 switch activates several warnings to help in identifying
5699 and correcting such incompatibilities. The default is that
5700 these warnings are generated. Note that at one point Ada 2005
5701 was called Ada 0Y, hence the choice of character.
5702 This warning can also be turned on using @option{-gnatwa}.
5703
5704 @item -gnatwY
5705 @emph{Disable warnings for Ada 2005 compatibility issues.}
5706 @cindex @option{-gnatwY} (@command{gcc})
5707 @cindex Ada 2005 compatibility issues warnings
5708 This switch suppresses several warnings intended to help in identifying
5709 incompatibilities between Ada 95 and Ada 2005.
5710
5711 @item -gnatwz
5712 @emph{Activate warnings on unchecked conversions.}
5713 @cindex @option{-gnatwz} (@command{gcc})
5714 @cindex Unchecked_Conversion warnings
5715 This switch activates warnings for unchecked conversions
5716 where the types are known at compile time to have different
5717 sizes. The default
5718 is that such warnings are generated. Warnings are also
5719 generated for subprogram pointers with different conventions,
5720 and, on VMS only, for data pointers with different conventions.
5721 This warning can also be turned on using @option{-gnatwa}.
5722
5723 @item -gnatwZ
5724 @emph{Suppress warnings on unchecked conversions.}
5725 @cindex @option{-gnatwZ} (@command{gcc})
5726 This switch suppresses warnings for unchecked conversions
5727 where the types are known at compile time to have different
5728 sizes or conventions.
5729
5730 @item ^-Wunused^WARNINGS=UNUSED^
5731 @cindex @option{-Wunused}
5732 The warnings controlled by the @option{-gnatw} switch are generated by
5733 the front end of the compiler. The @option{GCC} back end can provide
5734 additional warnings and they are controlled by the @option{-W} switch.
5735 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5736 warnings for entities that are declared but not referenced.
5737
5738 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5739 @cindex @option{-Wuninitialized}
5740 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5741 the back end warning for uninitialized variables. This switch must be
5742 used in conjunction with an optimization level greater than zero.
5743
5744 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5745 @cindex @option{-Wall}
5746 This switch enables all the above warnings from the @option{GCC} back end.
5747 The code generator detects a number of warning situations that are missed
5748 by the @option{GNAT} front end, and this switch can be used to activate them.
5749 The use of this switch also sets the default front end warning mode to
5750 @option{-gnatwa}, that is, most front end warnings activated as well.
5751
5752 @item ^-w^/NO_BACK_END_WARNINGS^
5753 @cindex @option{-w}
5754 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5755 The use of this switch also sets the default front end warning mode to
5756 @option{-gnatws}, that is, front end warnings suppressed as well.
5757
5758 @end table
5759
5760 @noindent
5761 @ifclear vms
5762 A string of warning parameters can be used in the same parameter. For example:
5763
5764 @smallexample
5765 -gnatwaLe
5766 @end smallexample
5767
5768 @noindent
5769 will turn on all optional warnings except for elaboration pragma warnings,
5770 and also specify that warnings should be treated as errors.
5771 @end ifclear
5772 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5773
5774 @table @option
5775 @c !sort!
5776 @item -gnatwC
5777 @item -gnatwD
5778 @item -gnatwF
5779 @item -gnatwg
5780 @item -gnatwH
5781 @item -gnatwi
5782 @item -gnatwJ
5783 @item -gnatwK
5784 @item -gnatwL
5785 @item -gnatwM
5786 @item -gnatwn
5787 @item -gnatwo
5788 @item -gnatwP
5789 @item -gnatwR
5790 @item -gnatwU
5791 @item -gnatwv
5792 @item -gnatwz
5793 @item -gnatwx
5794
5795 @end table
5796
5797 @node Debugging and Assertion Control
5798 @subsection Debugging and Assertion Control
5799
5800 @table @option
5801 @item -gnata
5802 @cindex @option{-gnata} (@command{gcc})
5803 @findex Assert
5804 @findex Debug
5805 @cindex Assertions
5806
5807 @noindent
5808 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5809 are ignored. This switch, where @samp{a} stands for assert, causes
5810 @code{Assert} and @code{Debug} pragmas to be activated.
5811
5812 The pragmas have the form:
5813
5814 @smallexample
5815 @cartouche
5816    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5817                       @var{static-string-expression}@r{]})
5818    @b{pragma} Debug (@var{procedure call})
5819 @end cartouche
5820 @end smallexample
5821
5822 @noindent
5823 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5824 If the result is @code{True}, the pragma has no effect (other than
5825 possible side effects from evaluating the expression). If the result is
5826 @code{False}, the exception @code{Assert_Failure} declared in the package
5827 @code{System.Assertions} is
5828 raised (passing @var{static-string-expression}, if present, as the
5829 message associated with the exception). If no string expression is
5830 given the default is a string giving the file name and line number
5831 of the pragma.
5832
5833 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5834 @code{pragma Debug} may appear within a declaration sequence, allowing
5835 debugging procedures to be called between declarations.
5836
5837 @ifset vms
5838 @item /DEBUG@r{[}=debug-level@r{]}
5839 @itemx  /NODEBUG
5840 Specifies how much debugging information is to be included in
5841 the resulting object file where 'debug-level' is one of the following:
5842 @table @code
5843 @item   TRACEBACK
5844 Include both debugger symbol records and traceback
5845 the object file.
5846 This is the default setting.
5847 @item   ALL
5848 Include both debugger symbol records and traceback in
5849 object file.
5850 @item   NONE
5851 Excludes both debugger symbol records and traceback
5852 the object file. Same as /NODEBUG.
5853 @item   SYMBOLS
5854 Includes only debugger symbol records in the object
5855 file. Note that this doesn't include traceback information.
5856 @end table
5857 @end ifset
5858 @end table
5859
5860 @node Validity Checking
5861 @subsection Validity Checking
5862 @findex Validity Checking
5863
5864 @noindent
5865 The Ada Reference Manual defines the concept of invalid values (see
5866 RM 13.9.1). The primary source of invalid values is uninitialized
5867 variables. A scalar variable that is left uninitialized may contain
5868 an invalid value; the concept of invalid does not apply to access or
5869 composite types.
5870
5871 It is an error to read an invalid value, but the RM does not require
5872 run-time checks to detect such errors, except for some minimal
5873 checking to prevent erroneous execution (i.e. unpredictable
5874 behavior). This corresponds to the @option{-gnatVd} switch below,
5875 which is the default. For example, by default, if the expression of a
5876 case statement is invalid, it will raise Constraint_Error rather than
5877 causing a wild jump, and if an array index on the left-hand side of an
5878 assignment is invalid, it will raise Constraint_Error rather than
5879 overwriting an arbitrary memory location.
5880
5881 The @option{-gnatVa} may be used to enable additional validity checks,
5882 which are not required by the RM. These checks are often very
5883 expensive (which is why the RM does not require them). These checks
5884 are useful in tracking down uninitialized variables, but they are
5885 not usually recommended for production builds.
5886
5887 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5888 control; you can enable whichever validity checks you desire. However,
5889 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5890 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5891 sufficient for non-debugging use.
5892
5893 The @option{-gnatB} switch tells the compiler to assume that all
5894 values are valid (that is, within their declared subtype range)
5895 except in the context of a use of the Valid attribute. This means
5896 the compiler can generate more efficient code, since the range
5897 of values is better known at compile time. However, an uninitialized
5898 variable can cause wild jumps and memory corruption in this mode.
5899
5900 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5901 checking mode as described below.
5902 @ifclear vms
5903 The @code{x} argument is a string of letters that
5904 indicate validity checks that are performed or not performed in addition
5905 to the default checks required by Ada as described above.
5906 @end ifclear
5907 @ifset vms
5908 The options allowed for this qualifier
5909 indicate validity checks that are performed or not performed in addition
5910 to the default checks required by Ada as described above.
5911 @end ifset
5912
5913 @table @option
5914 @c !sort!
5915 @item -gnatVa
5916 @emph{All validity checks.}
5917 @cindex @option{-gnatVa} (@command{gcc})
5918 All validity checks are turned on.
5919 @ifclear vms
5920 That is, @option{-gnatVa} is
5921 equivalent to @option{gnatVcdfimorst}.
5922 @end ifclear
5923
5924 @item -gnatVc
5925 @emph{Validity checks for copies.}
5926 @cindex @option{-gnatVc} (@command{gcc})
5927 The right hand side of assignments, and the initializing values of
5928 object declarations are validity checked.
5929
5930 @item -gnatVd
5931 @emph{Default (RM) validity checks.}
5932 @cindex @option{-gnatVd} (@command{gcc})
5933 Some validity checks are done by default following normal Ada semantics
5934 (RM 13.9.1 (9-11)).
5935 A check is done in case statements that the expression is within the range
5936 of the subtype. If it is not, Constraint_Error is raised.
5937 For assignments to array components, a check is done that the expression used
5938 as index is within the range. If it is not, Constraint_Error is raised.
5939 Both these validity checks may be turned off using switch @option{-gnatVD}.
5940 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5941 switch @option{-gnatVd} will leave the checks turned on.
5942 Switch @option{-gnatVD} should be used only if you are sure that all such
5943 expressions have valid values. If you use this switch and invalid values
5944 are present, then the program is erroneous, and wild jumps or memory
5945 overwriting may occur.
5946
5947 @item -gnatVe
5948 @emph{Validity checks for elementary components.}
5949 @cindex @option{-gnatVe} (@command{gcc})
5950 In the absence of this switch, assignments to record or array components are
5951 not validity checked, even if validity checks for assignments generally
5952 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5953 require valid data, but assignment of individual components does. So for
5954 example, there is a difference between copying the elements of an array with a
5955 slice assignment, compared to assigning element by element in a loop. This
5956 switch allows you to turn off validity checking for components, even when they
5957 are assigned component by component.
5958
5959 @item -gnatVf
5960 @emph{Validity checks for floating-point values.}
5961 @cindex @option{-gnatVf} (@command{gcc})
5962 In the absence of this switch, validity checking occurs only for discrete
5963 values. If @option{-gnatVf} is specified, then validity checking also applies
5964 for floating-point values, and NaNs and infinities are considered invalid,
5965 as well as out of range values for constrained types. Note that this means
5966 that standard IEEE infinity mode is not allowed. The exact contexts
5967 in which floating-point values are checked depends on the setting of other
5968 options. For example,
5969 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5970 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5971 (the order does not matter) specifies that floating-point parameters of mode
5972 @code{in} should be validity checked.
5973
5974 @item -gnatVi
5975 @emph{Validity checks for @code{in} mode parameters}
5976 @cindex @option{-gnatVi} (@command{gcc})
5977 Arguments for parameters of mode @code{in} are validity checked in function
5978 and procedure calls at the point of call.
5979
5980 @item -gnatVm
5981 @emph{Validity checks for @code{in out} mode parameters.}
5982 @cindex @option{-gnatVm} (@command{gcc})
5983 Arguments for parameters of mode @code{in out} are validity checked in
5984 procedure calls at the point of call. The @code{'m'} here stands for
5985 modify, since this concerns parameters that can be modified by the call.
5986 Note that there is no specific option to test @code{out} parameters,
5987 but any reference within the subprogram will be tested in the usual
5988 manner, and if an invalid value is copied back, any reference to it
5989 will be subject to validity checking.
5990
5991 @item -gnatVn
5992 @emph{No validity checks.}
5993 @cindex @option{-gnatVn} (@command{gcc})
5994 This switch turns off all validity checking, including the default checking
5995 for case statements and left hand side subscripts. Note that the use of
5996 the switch @option{-gnatp} suppresses all run-time checks, including
5997 validity checks, and thus implies @option{-gnatVn}. When this switch
5998 is used, it cancels any other @option{-gnatV} previously issued.
5999
6000 @item -gnatVo
6001 @emph{Validity checks for operator and attribute operands.}
6002 @cindex @option{-gnatVo} (@command{gcc})
6003 Arguments for predefined operators and attributes are validity checked.
6004 This includes all operators in package @code{Standard},
6005 the shift operators defined as intrinsic in package @code{Interfaces}
6006 and operands for attributes such as @code{Pos}. Checks are also made
6007 on individual component values for composite comparisons, and on the
6008 expressions in type conversions and qualified expressions. Checks are
6009 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6010
6011 @item -gnatVp
6012 @emph{Validity checks for parameters.}
6013 @cindex @option{-gnatVp} (@command{gcc})
6014 This controls the treatment of parameters within a subprogram (as opposed
6015 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6016 of parameters on a call. If either of these call options is used, then
6017 normally an assumption is made within a subprogram that the input arguments
6018 have been validity checking at the point of call, and do not need checking
6019 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6020 is not made, and parameters are not assumed to be valid, so their validity
6021 will be checked (or rechecked) within the subprogram.
6022
6023 @item -gnatVr
6024 @emph{Validity checks for function returns.}
6025 @cindex @option{-gnatVr} (@command{gcc})
6026 The expression in @code{return} statements in functions is validity
6027 checked.
6028
6029 @item -gnatVs
6030 @emph{Validity checks for subscripts.}
6031 @cindex @option{-gnatVs} (@command{gcc})
6032 All subscripts expressions are checked for validity, whether they appear
6033 on the right side or left side (in default mode only left side subscripts
6034 are validity checked).
6035
6036 @item -gnatVt
6037 @emph{Validity checks for tests.}
6038 @cindex @option{-gnatVt} (@command{gcc})
6039 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6040 statements are checked, as well as guard expressions in entry calls.
6041
6042 @end table
6043
6044 @noindent
6045 The @option{-gnatV} switch may be followed by
6046 ^a string of letters^a list of options^
6047 to turn on a series of validity checking options.
6048 For example,
6049 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6050 specifies that in addition to the default validity checking, copies and
6051 function return expressions are to be validity checked.
6052 In order to make it easier
6053 to specify the desired combination of effects,
6054 @ifclear vms
6055 the upper case letters @code{CDFIMORST} may
6056 be used to turn off the corresponding lower case option.
6057 @end ifclear
6058 @ifset vms
6059 the prefix @code{NO} on an option turns off the corresponding validity
6060 checking:
6061 @itemize @bullet
6062 @item @code{NOCOPIES}
6063 @item @code{NODEFAULT}
6064 @item @code{NOFLOATS}
6065 @item @code{NOIN_PARAMS}
6066 @item @code{NOMOD_PARAMS}
6067 @item @code{NOOPERANDS}
6068 @item @code{NORETURNS}
6069 @item @code{NOSUBSCRIPTS}
6070 @item @code{NOTESTS}
6071 @end itemize
6072 @end ifset
6073 Thus
6074 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6075 turns on all validity checking options except for
6076 checking of @code{@b{in out}} procedure arguments.
6077
6078 The specification of additional validity checking generates extra code (and
6079 in the case of @option{-gnatVa} the code expansion can be substantial).
6080 However, these additional checks can be very useful in detecting
6081 uninitialized variables, incorrect use of unchecked conversion, and other
6082 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6083 is useful in conjunction with the extra validity checking, since this
6084 ensures that wherever possible uninitialized variables have invalid values.
6085
6086 See also the pragma @code{Validity_Checks} which allows modification of
6087 the validity checking mode at the program source level, and also allows for
6088 temporary disabling of validity checks.
6089
6090 @node Style Checking
6091 @subsection Style Checking
6092 @findex Style checking
6093
6094 @noindent
6095 The @option{-gnaty^x^(option,option,@dots{})^} switch
6096 @cindex @option{-gnaty} (@command{gcc})
6097 causes the compiler to
6098 enforce specified style rules. A limited set of style rules has been used
6099 in writing the GNAT sources themselves. This switch allows user programs
6100 to activate all or some of these checks. If the source program fails a
6101 specified style check, an appropriate warning message is given, preceded by
6102 the character sequence ``(style)''.
6103 @ifset vms
6104 @code{(option,option,@dots{})} is a sequence of keywords
6105 @end ifset
6106 @ifclear vms
6107 The string @var{x} is a sequence of letters or digits
6108 @end ifclear
6109 indicating the particular style
6110 checks to be performed. The following checks are defined:
6111
6112 @table @option
6113 @c !sort!
6114 @item 0-9
6115 @emph{Specify indentation level.}
6116 If a digit from 1-9 appears
6117 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6118 then proper indentation is checked, with the digit indicating the
6119 indentation level required. A value of zero turns off this style check.
6120 The general style of required indentation is as specified by
6121 the examples in the Ada Reference Manual. Full line comments must be
6122 aligned with the @code{--} starting on a column that is a multiple of
6123 the alignment level, or they may be aligned the same way as the following
6124 non-blank line (this is useful when full line comments appear in the middle
6125 of a statement.
6126
6127 @item ^a^ATTRIBUTE^
6128 @emph{Check attribute casing.}
6129 Attribute names, including the case of keywords such as @code{digits}
6130 used as attributes names, must be written in mixed case, that is, the
6131 initial letter and any letter following an underscore must be uppercase.
6132 All other letters must be lowercase.
6133
6134 @item ^A^ARRAY_INDEXES^
6135 @emph{Use of array index numbers in array attributes.}
6136 When using the array attributes First, Last, Range,
6137 or Length, the index number must be omitted for one-dimensional arrays
6138 and is required for multi-dimensional arrays.
6139
6140 @item ^b^BLANKS^
6141 @emph{Blanks not allowed at statement end.}
6142 Trailing blanks are not allowed at the end of statements. The purpose of this
6143 rule, together with h (no horizontal tabs), is to enforce a canonical format
6144 for the use of blanks to separate source tokens.
6145
6146 @item ^B^BOOLEAN_OPERATORS^
6147 @emph{Check Boolean operators.}
6148 The use of AND/OR operators is not permitted except in the cases of modular
6149 operands, array operands, and simple stand-alone boolean variables or
6150 boolean constants. In all other cases AND THEN/OR ELSE are required.
6151
6152 @item ^c^COMMENTS^
6153 @emph{Check comments.}
6154 Comments must meet the following set of rules:
6155
6156 @itemize @bullet
6157
6158 @item
6159 The ``@code{--}'' that starts the column must either start in column one,
6160 or else at least one blank must precede this sequence.
6161
6162 @item
6163 Comments that follow other tokens on a line must have at least one blank
6164 following the ``@code{--}'' at the start of the comment.
6165
6166 @item
6167 Full line comments must have two blanks following the ``@code{--}'' that
6168 starts the comment, with the following exceptions.
6169
6170 @item
6171 A line consisting only of the ``@code{--}'' characters, possibly preceded
6172 by blanks is permitted.
6173
6174 @item
6175 A comment starting with ``@code{--x}'' where @code{x} is a special character
6176 is permitted.
6177 This allows proper processing of the output generated by specialized tools
6178 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6179 annotation
6180 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6181 special character is defined as being in one of the ASCII ranges
6182 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6183 Note that this usage is not permitted
6184 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6185
6186 @item
6187 A line consisting entirely of minus signs, possibly preceded by blanks, is
6188 permitted. This allows the construction of box comments where lines of minus
6189 signs are used to form the top and bottom of the box.
6190
6191 @item
6192 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6193 least one blank follows the initial ``@code{--}''. Together with the preceding
6194 rule, this allows the construction of box comments, as shown in the following
6195 example:
6196 @smallexample
6197 ---------------------------
6198 -- This is a box comment --
6199 -- with two text lines.  --
6200 ---------------------------
6201 @end smallexample
6202 @end itemize
6203
6204 @item ^d^DOS_LINE_ENDINGS^
6205 @emph{Check no DOS line terminators present.}
6206 All lines must be terminated by a single ASCII.LF
6207 character (in particular the DOS line terminator sequence CR/LF is not
6208 allowed).
6209
6210 @item ^e^END^
6211 @emph{Check end/exit labels.}
6212 Optional labels on @code{end} statements ending subprograms and on
6213 @code{exit} statements exiting named loops, are required to be present.
6214
6215 @item ^f^VTABS^
6216 @emph{No form feeds or vertical tabs.}
6217 Neither form feeds nor vertical tab characters are permitted
6218 in the source text.
6219
6220 @item ^g^GNAT^
6221 @emph{GNAT style mode}
6222 The set of style check switches is set to match that used by the GNAT sources.
6223 This may be useful when developing code that is eventually intended to be
6224 incorporated into GNAT. For further details, see GNAT sources.
6225
6226 @item ^h^HTABS^
6227 @emph{No horizontal tabs.}
6228 Horizontal tab characters are not permitted in the source text.
6229 Together with the b (no blanks at end of line) check, this
6230 enforces a canonical form for the use of blanks to separate
6231 source tokens.
6232
6233 @item ^i^IF_THEN^
6234 @emph{Check if-then layout.}
6235 The keyword @code{then} must appear either on the same
6236 line as corresponding @code{if}, or on a line on its own, lined
6237 up under the @code{if} with at least one non-blank line in between
6238 containing all or part of the condition to be tested.
6239
6240 @item ^I^IN_MODE^
6241 @emph{check mode IN keywords}
6242 Mode @code{in} (the default mode) is not
6243 allowed to be given explicitly. @code{in out} is fine,
6244 but not @code{in} on its own.
6245
6246 @item ^k^KEYWORD^
6247 @emph{Check keyword casing.}
6248 All keywords must be in lower case (with the exception of keywords
6249 such as @code{digits} used as attribute names to which this check
6250 does not apply).
6251
6252 @item ^l^LAYOUT^
6253 @emph{Check layout.}
6254 Layout of statement and declaration constructs must follow the
6255 recommendations in the Ada Reference Manual, as indicated by the
6256 form of the syntax rules. For example an @code{else} keyword must
6257 be lined up with the corresponding @code{if} keyword.
6258
6259 There are two respects in which the style rule enforced by this check
6260 option are more liberal than those in the Ada Reference Manual. First
6261 in the case of record declarations, it is permissible to put the
6262 @code{record} keyword on the same line as the @code{type} keyword, and
6263 then the @code{end} in @code{end record} must line up under @code{type}.
6264 This is also permitted when the type declaration is split on two lines.
6265 For example, any of the following three layouts is acceptable:
6266
6267 @smallexample @c ada
6268 @cartouche
6269 type q is record
6270    a : integer;
6271    b : integer;
6272 end record;
6273
6274 type q is
6275    record
6276       a : integer;
6277       b : integer;
6278    end record;
6279
6280 type q is
6281    record
6282       a : integer;
6283       b : integer;
6284 end record;
6285
6286 @end cartouche
6287 @end smallexample
6288
6289 @noindent
6290 Second, in the case of a block statement, a permitted alternative
6291 is to put the block label on the same line as the @code{declare} or
6292 @code{begin} keyword, and then line the @code{end} keyword up under
6293 the block label. For example both the following are permitted:
6294
6295 @smallexample @c ada
6296 @cartouche
6297 Block : declare
6298    A : Integer := 3;
6299 begin
6300    Proc (A, A);
6301 end Block;
6302
6303 Block :
6304    declare
6305       A : Integer := 3;
6306    begin
6307       Proc (A, A);
6308    end Block;
6309 @end cartouche
6310 @end smallexample
6311
6312 @noindent
6313 The same alternative format is allowed for loops. For example, both of
6314 the following are permitted:
6315
6316 @smallexample @c ada
6317 @cartouche
6318 Clear : while J < 10 loop
6319    A (J) := 0;
6320 end loop Clear;
6321
6322 Clear :
6323    while J < 10 loop
6324       A (J) := 0;
6325    end loop Clear;
6326 @end cartouche
6327 @end smallexample
6328
6329 @item ^Lnnn^MAX_NESTING=nnn^
6330 @emph{Set maximum nesting level}
6331 The maximum level of nesting of constructs (including subprograms, loops,
6332 blocks, packages, and conditionals) may not exceed the given value
6333 @option{nnn}. A value of zero disconnects this style check.
6334
6335 @item ^m^LINE_LENGTH^
6336 @emph{Check maximum line length.}
6337 The length of source lines must not exceed 79 characters, including
6338 any trailing blanks. The value of 79 allows convenient display on an
6339 80 character wide device or window, allowing for possible special
6340 treatment of 80 character lines. Note that this count is of
6341 characters in the source text. This means that a tab character counts
6342 as one character in this count but a wide character sequence counts as
6343 a single character (however many bytes are needed in the encoding).
6344
6345 @item ^Mnnn^MAX_LENGTH=nnn^
6346 @emph{Set maximum line length.}
6347 The length of lines must not exceed the
6348 given value @option{nnn}. The maximum value that can be specified is 32767.
6349
6350 @item ^n^STANDARD_CASING^
6351 @emph{Check casing of entities in Standard.}
6352 Any identifier from Standard must be cased
6353 to match the presentation in the Ada Reference Manual (for example,
6354 @code{Integer} and @code{ASCII.NUL}).
6355
6356 @item ^N^NONE^
6357 @emph{Turn off all style checks}
6358 All style check options are turned off.
6359
6360 @item ^o^ORDERED_SUBPROGRAMS^
6361 @emph{Check order of subprogram bodies.}
6362 All subprogram bodies in a given scope
6363 (e.g.@: a package body) must be in alphabetical order. The ordering
6364 rule uses normal Ada rules for comparing strings, ignoring casing
6365 of letters, except that if there is a trailing numeric suffix, then
6366 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6367 before Junk10).
6368
6369 @item ^O^OVERRIDING_INDICATORS^
6370 @emph{Check that overriding subprograms are explicitly marked as such.}
6371 The declaration of a primitive operation of a type extension that overrides
6372 an inherited operation must carry an overriding indicator.
6373
6374 @item ^p^PRAGMA^
6375 @emph{Check pragma casing.}
6376 Pragma names must be written in mixed case, that is, the
6377 initial letter and any letter following an underscore must be uppercase.
6378 All other letters must be lowercase.
6379
6380 @item ^r^REFERENCES^
6381 @emph{Check references.}
6382 All identifier references must be cased in the same way as the
6383 corresponding declaration. No specific casing style is imposed on
6384 identifiers. The only requirement is for consistency of references
6385 with declarations.
6386
6387 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6388 @emph{Check no statements after THEN/ELSE.}
6389 No statements are allowed
6390 on the same line as a THEN or ELSE keyword following the
6391 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6392 and a special exception allows a pragma to appear after ELSE.
6393
6394 @item ^s^SPECS^
6395 @emph{Check separate specs.}
6396 Separate declarations (``specs'') are required for subprograms (a
6397 body is not allowed to serve as its own declaration). The only
6398 exception is that parameterless library level procedures are
6399 not required to have a separate declaration. This exception covers
6400 the most frequent form of main program procedures.
6401
6402 @item ^t^TOKEN^
6403 @emph{Check token spacing.}
6404 The following token spacing rules are enforced:
6405
6406 @itemize @bullet
6407
6408 @item
6409 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6410
6411 @item
6412 The token @code{=>} must be surrounded by spaces.
6413
6414 @item
6415 The token @code{<>} must be preceded by a space or a left parenthesis.
6416
6417 @item
6418 Binary operators other than @code{**} must be surrounded by spaces.
6419 There is no restriction on the layout of the @code{**} binary operator.
6420
6421 @item
6422 Colon must be surrounded by spaces.
6423
6424 @item
6425 Colon-equal (assignment, initialization) must be surrounded by spaces.
6426
6427 @item
6428 Comma must be the first non-blank character on the line, or be
6429 immediately preceded by a non-blank character, and must be followed
6430 by a space.
6431
6432 @item
6433 If the token preceding a left parenthesis ends with a letter or digit, then
6434 a space must separate the two tokens.
6435
6436 @item
6437 A right parenthesis must either be the first non-blank character on
6438 a line, or it must be preceded by a non-blank character.
6439
6440 @item
6441 A semicolon must not be preceded by a space, and must not be followed by
6442 a non-blank character.
6443
6444 @item
6445 A unary plus or minus may not be followed by a space.
6446
6447 @item
6448 A vertical bar must be surrounded by spaces.
6449 @end itemize
6450
6451 @item ^u^UNNECESSARY_BLANK_LINES^
6452 @emph{Check unnecessary blank lines.}
6453 Unnecessary blank lines are not allowed. A blank line is considered
6454 unnecessary if it appears at the end of the file, or if more than
6455 one blank line occurs in sequence.
6456
6457 @item ^x^XTRA_PARENS^
6458 @emph{Check extra parentheses.}
6459 Unnecessary extra level of parentheses (C-style) are not allowed
6460 around conditions in @code{if} statements, @code{while} statements and
6461 @code{exit} statements.
6462
6463 @item ^y^ALL_BUILTIN^
6464 @emph{Set all standard style check options}
6465 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6466 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6467 @option{-gnatyS}, @option{-gnatyLnnn},
6468 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6469
6470 @ifclear vms
6471 @item -
6472 @emph{Remove style check options}
6473 This causes any subsequent options in the string to act as canceling the
6474 corresponding style check option. To cancel maximum nesting level control,
6475 use @option{L} parameter witout any integer value after that, because any
6476 digit following @option{-} in the parameter string of the @option{-gnaty}
6477 option will be threated as canceling indentation check. The same is true
6478 for @option{M} parameter. @option{y} and @option{N} parameters are not
6479 allowed after @option{-}.
6480
6481 @item +
6482 This causes any subsequent options in the string to enable the corresponding
6483 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6484 if any.
6485 @end ifclear
6486
6487 @ifset vms
6488 @item NOxxx
6489 @emph{Removing style check options}
6490 If the name of a style check is preceded by @option{NO} then the corresponding
6491 style check is turned off. For example @option{NOCOMMENTS} turns off style
6492 checking for comments.
6493 @end ifset
6494 @end table
6495
6496 @noindent
6497 In the above rules, appearing in column one is always permitted, that is,
6498 counts as meeting either a requirement for a required preceding space,
6499 or as meeting a requirement for no preceding space.
6500
6501 Appearing at the end of a line is also always permitted, that is, counts
6502 as meeting either a requirement for a following space, or as meeting
6503 a requirement for no following space.
6504
6505 @noindent
6506 If any of these style rules is violated, a message is generated giving
6507 details on the violation. The initial characters of such messages are
6508 always ``@code{(style)}''. Note that these messages are treated as warning
6509 messages, so they normally do not prevent the generation of an object
6510 file. The @option{-gnatwe} switch can be used to treat warning messages,
6511 including style messages, as fatal errors.
6512
6513 The switch
6514 @ifclear vms
6515 @option{-gnaty} on its own (that is not
6516 followed by any letters or digits), then the effect is equivalent
6517 to the use of @option{-gnatyy}, as described above, that is all
6518 built-in standard style check options are enabled.
6519
6520 @end ifclear
6521 @ifset vms
6522 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6523 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6524 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6525 @end ifset
6526
6527
6528
6529 The switch
6530 @ifclear vms
6531 @option{-gnatyN}
6532 @end ifclear
6533 @ifset vms
6534 /STYLE_CHECKS=NONE
6535 @end ifset
6536 clears any previously set style checks.
6537
6538 @node Run-Time Checks
6539 @subsection Run-Time Checks
6540 @cindex Division by zero
6541 @cindex Access before elaboration
6542 @cindex Checks, division by zero
6543 @cindex Checks, access before elaboration
6544 @cindex Checks, stack overflow checking
6545
6546 @noindent
6547 By default, the following checks are suppressed: integer overflow
6548 checks, stack overflow checks, and checks for access before
6549 elaboration on subprogram calls. All other checks, including range
6550 checks and array bounds checks, are turned on by default. The
6551 following @command{gcc} switches refine this default behavior.
6552
6553 @table @option
6554 @c !sort!
6555 @item -gnatp
6556 @cindex @option{-gnatp} (@command{gcc})
6557 @cindex Suppressing checks
6558 @cindex Checks, suppressing
6559 @findex Suppress
6560 This switch causes the unit to be compiled
6561 as though @code{pragma Suppress (All_checks)}
6562 had been present in the source. Validity checks are also eliminated (in
6563 other words @option{-gnatp} also implies @option{-gnatVn}.
6564 Use this switch to improve the performance
6565 of the code at the expense of safety in the presence of invalid data or
6566 program bugs.
6567
6568 Note that when checks are suppressed, the compiler is allowed, but not
6569 required, to omit the checking code. If the run-time cost of the
6570 checking code is zero or near-zero, the compiler will generate it even
6571 if checks are suppressed. In particular, if the compiler can prove
6572 that a certain check will necessarily fail, it will generate code to
6573 do an unconditional ``raise'', even if checks are suppressed. The
6574 compiler warns in this case. Another case in which checks may not be
6575 eliminated is when they are embedded in certain run time routines such
6576 as math library routines.
6577
6578 Of course, run-time checks are omitted whenever the compiler can prove
6579 that they will not fail, whether or not checks are suppressed.
6580
6581 Note that if you suppress a check that would have failed, program
6582 execution is erroneous, which means the behavior is totally
6583 unpredictable. The program might crash, or print wrong answers, or
6584 do anything else. It might even do exactly what you wanted it to do
6585 (and then it might start failing mysteriously next week or next
6586 year). The compiler will generate code based on the assumption that
6587 the condition being checked is true, which can result in disaster if
6588 that assumption is wrong.
6589
6590 @item -gnato
6591 @cindex @option{-gnato} (@command{gcc})
6592 @cindex Overflow checks
6593 @cindex Check, overflow
6594 Enables overflow checking for integer operations.
6595 This causes GNAT to generate slower and larger executable
6596 programs by adding code to check for overflow (resulting in raising
6597 @code{Constraint_Error} as required by standard Ada
6598 semantics). These overflow checks correspond to situations in which
6599 the true value of the result of an operation may be outside the base
6600 range of the result type. The following example shows the distinction:
6601
6602 @smallexample @c ada
6603 X1 : Integer := "Integer'Last";
6604 X2 : Integer range 1 .. 5 := "5";
6605 X3 : Integer := "Integer'Last";
6606 X4 : Integer range 1 .. 5 := "5";
6607 F  : Float := "2.0E+20";
6608 @dots{}
6609 X1 := X1 + 1;
6610 X2 := X2 + 1;
6611 X3 := Integer (F);
6612 X4 := Integer (F);
6613 @end smallexample
6614
6615 @noindent
6616 Note that if explicit values are assigned at compile time, the
6617 compiler may be able to detect overflow at compile time, in which case
6618 no actual run-time checking code is required, and Constraint_Error
6619 will be raised unconditionally, with or without
6620 @option{-gnato}. That's why the assigned values in the above fragment
6621 are in quotes, the meaning is "assign a value not known to the
6622 compiler that happens to be equal to ...". The remaining discussion
6623 assumes that the compiler cannot detect the values at compile time.
6624
6625 Here the first addition results in a value that is outside the base range
6626 of Integer, and hence requires an overflow check for detection of the
6627 constraint error. Thus the first assignment to @code{X1} raises a
6628 @code{Constraint_Error} exception only if @option{-gnato} is set.
6629
6630 The second increment operation results in a violation of the explicit
6631 range constraint; such range checks are performed by default, and are
6632 unaffected by @option{-gnato}.
6633
6634 The two conversions of @code{F} both result in values that are outside
6635 the base range of type @code{Integer} and thus will raise
6636 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6637 The fact that the result of the second conversion is assigned to
6638 variable @code{X4} with a restricted range is irrelevant, since the problem
6639 is in the conversion, not the assignment.
6640
6641 Basically the rule is that in the default mode (@option{-gnato} not
6642 used), the generated code assures that all integer variables stay
6643 within their declared ranges, or within the base range if there is
6644 no declared range. This prevents any serious problems like indexes
6645 out of range for array operations.
6646
6647 What is not checked in default mode is an overflow that results in
6648 an in-range, but incorrect value. In the above example, the assignments
6649 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6650 range of the target variable, but the result is wrong in the sense that
6651 it is too large to be represented correctly. Typically the assignment
6652 to @code{X1} will result in wrap around to the largest negative number.
6653 The conversions of @code{F} will result in some @code{Integer} value
6654 and if that integer value is out of the @code{X4} range then the
6655 subsequent assignment would generate an exception.
6656
6657 @findex Machine_Overflows
6658 Note that the @option{-gnato} switch does not affect the code generated
6659 for any floating-point operations; it applies only to integer
6660 semantics).
6661 For floating-point, GNAT has the @code{Machine_Overflows}
6662 attribute set to @code{False} and the normal mode of operation is to
6663 generate IEEE NaN and infinite values on overflow or invalid operations
6664 (such as dividing 0.0 by 0.0).
6665
6666 The reason that we distinguish overflow checking from other kinds of
6667 range constraint checking is that a failure of an overflow check, unlike
6668 for example the failure of a range check, can result in an incorrect
6669 value, but cannot cause random memory destruction (like an out of range
6670 subscript), or a wild jump (from an out of range case value). Overflow
6671 checking is also quite expensive in time and space, since in general it
6672 requires the use of double length arithmetic.
6673
6674 Note again that @option{-gnato} is off by default, so overflow checking is
6675 not performed in default mode. This means that out of the box, with the
6676 default settings, GNAT does not do all the checks expected from the
6677 language description in the Ada Reference Manual. If you want all constraint
6678 checks to be performed, as described in this Manual, then you must
6679 explicitly use the -gnato switch either on the @command{gnatmake} or
6680 @command{gcc} command.
6681
6682 @item -gnatE
6683 @cindex @option{-gnatE} (@command{gcc})
6684 @cindex Elaboration checks
6685 @cindex Check, elaboration
6686 Enables dynamic checks for access-before-elaboration
6687 on subprogram calls and generic instantiations.
6688 Note that @option{-gnatE} is not necessary for safety, because in the
6689 default mode, GNAT ensures statically that the checks would not fail.
6690 For full details of the effect and use of this switch,
6691 @xref{Compiling Using gcc}.
6692
6693 @item -fstack-check
6694 @cindex @option{-fstack-check} (@command{gcc})
6695 @cindex Stack Overflow Checking
6696 @cindex Checks, stack overflow checking
6697 Activates stack overflow checking. For full details of the effect and use of
6698 this switch see @ref{Stack Overflow Checking}.
6699 @end table
6700
6701 @findex Unsuppress
6702 @noindent
6703 The setting of these switches only controls the default setting of the
6704 checks. You may modify them using either @code{Suppress} (to remove
6705 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6706 the program source.
6707
6708 @node Using gcc for Syntax Checking
6709 @subsection Using @command{gcc} for Syntax Checking
6710 @table @option
6711 @item -gnats
6712 @cindex @option{-gnats} (@command{gcc})
6713 @ifclear vms
6714
6715 @noindent
6716 The @code{s} stands for ``syntax''.
6717 @end ifclear
6718
6719 Run GNAT in syntax checking only mode. For
6720 example, the command
6721
6722 @smallexample
6723 $ gcc -c -gnats x.adb
6724 @end smallexample
6725
6726 @noindent
6727 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6728 series of files in a single command
6729 @ifclear vms
6730 , and can use wild cards to specify such a group of files.
6731 Note that you must specify the @option{-c} (compile
6732 only) flag in addition to the @option{-gnats} flag.
6733 @end ifclear
6734 .
6735 You may use other switches in conjunction with @option{-gnats}. In
6736 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6737 format of any generated error messages.
6738
6739 When the source file is empty or contains only empty lines and/or comments,
6740 the output is a warning:
6741
6742 @smallexample
6743 $ gcc -c -gnats -x ada toto.txt
6744 toto.txt:1:01: warning: empty file, contains no compilation units
6745 $
6746 @end smallexample
6747
6748 Otherwise, the output is simply the error messages, if any. No object file or
6749 ALI file is generated by a syntax-only compilation. Also, no units other
6750 than the one specified are accessed. For example, if a unit @code{X}
6751 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6752 check only mode does not access the source file containing unit
6753 @code{Y}.
6754
6755 @cindex Multiple units, syntax checking
6756 Normally, GNAT allows only a single unit in a source file. However, this
6757 restriction does not apply in syntax-check-only mode, and it is possible
6758 to check a file containing multiple compilation units concatenated
6759 together. This is primarily used by the @code{gnatchop} utility
6760 (@pxref{Renaming Files Using gnatchop}).
6761 @end table
6762
6763 @node Using gcc for Semantic Checking
6764 @subsection Using @command{gcc} for Semantic Checking
6765 @table @option
6766 @item -gnatc
6767 @cindex @option{-gnatc} (@command{gcc})
6768
6769 @ifclear vms
6770 @noindent
6771 The @code{c} stands for ``check''.
6772 @end ifclear
6773 Causes the compiler to operate in semantic check mode,
6774 with full checking for all illegalities specified in the
6775 Ada Reference Manual, but without generation of any object code
6776 (no object file is generated).
6777
6778 Because dependent files must be accessed, you must follow the GNAT
6779 semantic restrictions on file structuring to operate in this mode:
6780
6781 @itemize @bullet
6782 @item
6783 The needed source files must be accessible
6784 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6785
6786 @item
6787 Each file must contain only one compilation unit.
6788
6789 @item
6790 The file name and unit name must match (@pxref{File Naming Rules}).
6791 @end itemize
6792
6793 The output consists of error messages as appropriate. No object file is
6794 generated. An @file{ALI} file is generated for use in the context of
6795 cross-reference tools, but this file is marked as not being suitable
6796 for binding (since no object file is generated).
6797 The checking corresponds exactly to the notion of
6798 legality in the Ada Reference Manual.
6799
6800 Any unit can be compiled in semantics-checking-only mode, including
6801 units that would not normally be compiled (subunits,
6802 and specifications where a separate body is present).
6803 @end table
6804
6805 @node Compiling Different Versions of Ada
6806 @subsection Compiling Different Versions of Ada
6807
6808 @noindent
6809 The switches described in this section allow you to explicitly specify
6810 the version of the Ada language that your programs are written in.
6811 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6812 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6813 indicate Ada 83 compatibility mode.
6814
6815 @table @option
6816 @cindex Compatibility with Ada 83
6817
6818 @item -gnat83 (Ada 83 Compatibility Mode)
6819 @cindex @option{-gnat83} (@command{gcc})
6820 @cindex ACVC, Ada 83 tests
6821 @cindex Ada 83 mode
6822
6823 @noindent
6824 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6825 specifies that the program is to be compiled in Ada 83 mode. With
6826 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6827 semantics where this can be done easily.
6828 It is not possible to guarantee this switch does a perfect
6829 job; some subtle tests, such as are
6830 found in earlier ACVC tests (and that have been removed from the ACATS suite
6831 for Ada 95), might not compile correctly.
6832 Nevertheless, this switch may be useful in some circumstances, for example
6833 where, due to contractual reasons, existing code needs to be maintained
6834 using only Ada 83 features.
6835
6836 With few exceptions (most notably the need to use @code{<>} on
6837 @cindex Generic formal parameters
6838 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6839 reserved words, and the use of packages
6840 with optional bodies), it is not necessary to specify the
6841 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6842 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6843 a correct Ada 83 program is usually also a correct program
6844 in these later versions of the language standard.
6845 For further information, please refer to @ref{Compatibility and Porting Guide}.
6846
6847 @item -gnat95 (Ada 95 mode)
6848 @cindex @option{-gnat95} (@command{gcc})
6849 @cindex Ada 95 mode
6850
6851 @noindent
6852 This switch directs the compiler to implement the Ada 95 version of the
6853 language.
6854 Since Ada 95 is almost completely upwards
6855 compatible with Ada 83, Ada 83 programs may generally be compiled using
6856 this switch (see the description of the @option{-gnat83} switch for further
6857 information about Ada 83 mode).
6858 If an Ada 2005 program is compiled in Ada 95 mode,
6859 uses of the new Ada 2005 features will cause error
6860 messages or warnings.
6861
6862 This switch also can be used to cancel the effect of a previous
6863 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6864
6865 @item -gnat05 (Ada 2005 mode)
6866 @cindex @option{-gnat05} (@command{gcc})
6867 @cindex Ada 2005 mode
6868
6869 @noindent
6870 This switch directs the compiler to implement the Ada 2005 version of the
6871 language.
6872 Since Ada 2005 is almost completely upwards
6873 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6874 may generally be compiled using this switch (see the description of the
6875 @option{-gnat83} and @option{-gnat95} switches for further
6876 information).
6877
6878 For information about the approved ``Ada Issues'' that have been incorporated
6879 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6880 Included with GNAT releases is a file @file{features-ada0y} that describes
6881 the set of implemented Ada 2005 features.
6882 @end table
6883
6884
6885 @node Character Set Control
6886 @subsection Character Set Control
6887 @table @option
6888 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6889 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6890
6891 @noindent
6892 Normally GNAT recognizes the Latin-1 character set in source program
6893 identifiers, as described in the Ada Reference Manual.
6894 This switch causes
6895 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6896 single character ^^or word^ indicating the character set, as follows:
6897
6898 @table @code
6899 @item 1
6900 ISO 8859-1 (Latin-1) identifiers
6901
6902 @item 2
6903 ISO 8859-2 (Latin-2) letters allowed in identifiers
6904
6905 @item 3
6906 ISO 8859-3 (Latin-3) letters allowed in identifiers
6907
6908 @item 4
6909 ISO 8859-4 (Latin-4) letters allowed in identifiers
6910
6911 @item 5
6912 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6913
6914 @item 9
6915 ISO 8859-15 (Latin-9) letters allowed in identifiers
6916
6917 @item ^p^PC^
6918 IBM PC letters (code page 437) allowed in identifiers
6919
6920 @item ^8^PC850^
6921 IBM PC letters (code page 850) allowed in identifiers
6922
6923 @item ^f^FULL_UPPER^
6924 Full upper-half codes allowed in identifiers
6925
6926 @item ^n^NO_UPPER^
6927 No upper-half codes allowed in identifiers
6928
6929 @item ^w^WIDE^
6930 Wide-character codes (that is, codes greater than 255)
6931 allowed in identifiers
6932 @end table
6933
6934 @xref{Foreign Language Representation}, for full details on the
6935 implementation of these character sets.
6936
6937 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6938 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6939 Specify the method of encoding for wide characters.
6940 @var{e} is one of the following:
6941
6942 @table @code
6943
6944 @item ^h^HEX^
6945 Hex encoding (brackets coding also recognized)
6946
6947 @item ^u^UPPER^
6948 Upper half encoding (brackets encoding also recognized)
6949
6950 @item ^s^SHIFT_JIS^
6951 Shift/JIS encoding (brackets encoding also recognized)
6952
6953 @item ^e^EUC^
6954 EUC encoding (brackets encoding also recognized)
6955
6956 @item ^8^UTF8^
6957 UTF-8 encoding (brackets encoding also recognized)
6958
6959 @item ^b^BRACKETS^
6960 Brackets encoding only (default value)
6961 @end table
6962 For full details on these encoding
6963 methods see @ref{Wide Character Encodings}.
6964 Note that brackets coding is always accepted, even if one of the other
6965 options is specified, so for example @option{-gnatW8} specifies that both
6966 brackets and UTF-8 encodings will be recognized. The units that are
6967 with'ed directly or indirectly will be scanned using the specified
6968 representation scheme, and so if one of the non-brackets scheme is
6969 used, it must be used consistently throughout the program. However,
6970 since brackets encoding is always recognized, it may be conveniently
6971 used in standard libraries, allowing these libraries to be used with
6972 any of the available coding schemes.
6973 scheme.
6974
6975 If no @option{-gnatW?} parameter is present, then the default
6976 representation is normally Brackets encoding only. However, if the
6977 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6978 byte order mark or BOM for UTF-8), then these three characters are
6979 skipped and the default representation for the file is set to UTF-8.
6980
6981 Note that the wide character representation that is specified (explicitly
6982 or by default) for the main program also acts as the default encoding used
6983 for Wide_Text_IO files if not specifically overridden by a WCEM form
6984 parameter.
6985
6986 @end table
6987 @node File Naming Control
6988 @subsection File Naming Control
6989
6990 @table @option
6991 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6992 @cindex @option{-gnatk} (@command{gcc})
6993 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6994 1-999, indicates the maximum allowable length of a file name (not
6995 including the @file{.ads} or @file{.adb} extension). The default is not
6996 to enable file name krunching.
6997
6998 For the source file naming rules, @xref{File Naming Rules}.
6999 @end table
7000
7001 @node Subprogram Inlining Control
7002 @subsection Subprogram Inlining Control
7003
7004 @table @option
7005 @c !sort!
7006 @item -gnatn
7007 @cindex @option{-gnatn} (@command{gcc})
7008 @ifclear vms
7009 The @code{n} here is intended to suggest the first syllable of the
7010 word ``inline''.
7011 @end ifclear
7012 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7013 inlining to actually occur, optimization must be enabled. To enable
7014 inlining of subprograms specified by pragma @code{Inline},
7015 you must also specify this switch.
7016 In the absence of this switch, GNAT does not attempt
7017 inlining and does not need to access the bodies of
7018 subprograms for which @code{pragma Inline} is specified if they are not
7019 in the current unit.
7020
7021 If you specify this switch the compiler will access these bodies,
7022 creating an extra source dependency for the resulting object file, and
7023 where possible, the call will be inlined.
7024 For further details on when inlining is possible
7025 see @ref{Inlining of Subprograms}.
7026
7027 @item -gnatN
7028 @cindex @option{-gnatN} (@command{gcc})
7029 This switch activates front-end inlining which also
7030 generates additional dependencies.
7031
7032 When using a gcc-based back end (in practice this means using any version
7033 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7034 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7035 Historically front end inlining was more extensive than the gcc back end
7036 inlining, but that is no longer the case.
7037 @end table
7038
7039 @node Auxiliary Output Control
7040 @subsection Auxiliary Output Control
7041
7042 @table @option
7043 @item -gnatt
7044 @cindex @option{-gnatt} (@command{gcc})
7045 @cindex Writing internal trees
7046 @cindex Internal trees, writing to file
7047 Causes GNAT to write the internal tree for a unit to a file (with the
7048 extension @file{.adt}.
7049 This not normally required, but is used by separate analysis tools.
7050 Typically
7051 these tools do the necessary compilations automatically, so you should
7052 not have to specify this switch in normal operation.
7053 Note that the combination of switches @option{-gnatct}
7054 generates a tree in the form required by ASIS applications.
7055
7056 @item -gnatu
7057 @cindex @option{-gnatu} (@command{gcc})
7058 Print a list of units required by this compilation on @file{stdout}.
7059 The listing includes all units on which the unit being compiled depends
7060 either directly or indirectly.
7061
7062 @ifclear vms
7063 @item -pass-exit-codes
7064 @cindex @option{-pass-exit-codes} (@command{gcc})
7065 If this switch is not used, the exit code returned by @command{gcc} when
7066 compiling multiple files indicates whether all source files have
7067 been successfully used to generate object files or not.
7068
7069 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7070 exit status and allows an integrated development environment to better
7071 react to a compilation failure. Those exit status are:
7072
7073 @table @asis
7074 @item 5
7075 There was an error in at least one source file.
7076 @item 3
7077 At least one source file did not generate an object file.
7078 @item 2
7079 The compiler died unexpectedly (internal error for example).
7080 @item 0
7081 An object file has been generated for every source file.
7082 @end table
7083 @end ifclear
7084 @end table
7085
7086 @node Debugging Control
7087 @subsection Debugging Control
7088
7089 @table @option
7090 @c !sort!
7091 @cindex Debugging options
7092 @ifclear vms
7093 @item -gnatd@var{x}
7094 @cindex @option{-gnatd} (@command{gcc})
7095 Activate internal debugging switches. @var{x} is a letter or digit, or
7096 string of letters or digits, which specifies the type of debugging
7097 outputs desired. Normally these are used only for internal development
7098 or system debugging purposes. You can find full documentation for these
7099 switches in the body of the @code{Debug} unit in the compiler source
7100 file @file{debug.adb}.
7101 @end ifclear
7102
7103 @item -gnatG[=nn]
7104 @cindex @option{-gnatG} (@command{gcc})
7105 This switch causes the compiler to generate auxiliary output containing
7106 a pseudo-source listing of the generated expanded code. Like most Ada
7107 compilers, GNAT works by first transforming the high level Ada code into
7108 lower level constructs. For example, tasking operations are transformed
7109 into calls to the tasking run-time routines. A unique capability of GNAT
7110 is to list this expanded code in a form very close to normal Ada source.
7111 This is very useful in understanding the implications of various Ada
7112 usage on the efficiency of the generated code. There are many cases in
7113 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7114 generate a lot of run-time code. By using @option{-gnatG} you can identify
7115 these cases, and consider whether it may be desirable to modify the coding
7116 approach to improve efficiency.
7117
7118 The optional parameter @code{nn} if present after -gnatG specifies an
7119 alternative maximum line length that overrides the normal default of 72.
7120 This value is in the range 40-999999, values less than 40 being silently
7121 reset to 40. The equal sign is optional.
7122
7123 The format of the output is very similar to standard Ada source, and is
7124 easily understood by an Ada programmer. The following special syntactic
7125 additions correspond to low level features used in the generated code that
7126 do not have any exact analogies in pure Ada source form. The following
7127 is a partial list of these special constructions. See the spec
7128 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7129
7130 If the switch @option{-gnatL} is used in conjunction with
7131 @cindex @option{-gnatL} (@command{gcc})
7132 @option{-gnatG}, then the original source lines are interspersed
7133 in the expanded source (as comment lines with the original line number).
7134
7135 @table @code
7136 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7137 Shows the storage pool being used for an allocator.
7138
7139 @item at end @var{procedure-name};
7140 Shows the finalization (cleanup) procedure for a scope.
7141
7142 @item (if @var{expr} then @var{expr} else @var{expr})
7143 Conditional expression equivalent to the @code{x?y:z} construction in C.
7144
7145 @item @var{target}^^^(@var{source})
7146 A conversion with floating-point truncation instead of rounding.
7147
7148 @item @var{target}?(@var{source})
7149 A conversion that bypasses normal Ada semantic checking. In particular
7150 enumeration types and fixed-point types are treated simply as integers.
7151
7152 @item @var{target}?^^^(@var{source})
7153 Combines the above two cases.
7154
7155 @item @var{x} #/ @var{y}
7156 @itemx @var{x} #mod @var{y}
7157 @itemx @var{x} #* @var{y}
7158 @itemx @var{x} #rem @var{y}
7159 A division or multiplication of fixed-point values which are treated as
7160 integers without any kind of scaling.
7161
7162 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7163 Shows the storage pool associated with a @code{free} statement.
7164
7165 @item [subtype or type declaration]
7166 Used to list an equivalent declaration for an internally generated
7167 type that is referenced elsewhere in the listing.
7168
7169 @item freeze @var{type-name} @ovar{actions}
7170 Shows the point at which @var{type-name} is frozen, with possible
7171 associated actions to be performed at the freeze point.
7172
7173 @item reference @var{itype}
7174 Reference (and hence definition) to internal type @var{itype}.
7175
7176 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7177 Intrinsic function call.
7178
7179 @item @var{label-name} : label
7180 Declaration of label @var{labelname}.
7181
7182 @item #$ @var{subprogram-name}
7183 An implicit call to a run-time support routine
7184 (to meet the requirement of H.3.1(9) in a
7185 convenient manner).
7186
7187 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7188 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7189 @var{expr}, but handled more efficiently).
7190
7191 @item [constraint_error]
7192 Raise the @code{Constraint_Error} exception.
7193
7194 @item @var{expression}'reference
7195 A pointer to the result of evaluating @var{expression}.
7196
7197 @item @var{target-type}!(@var{source-expression})
7198 An unchecked conversion of @var{source-expression} to @var{target-type}.
7199
7200 @item [@var{numerator}/@var{denominator}]
7201 Used to represent internal real literals (that) have no exact
7202 representation in base 2-16 (for example, the result of compile time
7203 evaluation of the expression 1.0/27.0).
7204 @end table
7205
7206 @item -gnatD[=nn]
7207 @cindex @option{-gnatD} (@command{gcc})
7208 When used in conjunction with @option{-gnatG}, this switch causes
7209 the expanded source, as described above for
7210 @option{-gnatG} to be written to files with names
7211 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7212 instead of to the standard output file. For
7213 example, if the source file name is @file{hello.adb}, then a file
7214 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7215 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7216 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7217 you to do source level debugging using the generated code which is
7218 sometimes useful for complex code, for example to find out exactly
7219 which part of a complex construction raised an exception. This switch
7220 also suppress generation of cross-reference information (see
7221 @option{-gnatx}) since otherwise the cross-reference information
7222 would refer to the @file{^.dg^.DG^} file, which would cause
7223 confusion since this is not the original source file.
7224
7225 Note that @option{-gnatD} actually implies @option{-gnatG}
7226 automatically, so it is not necessary to give both options.
7227 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7228
7229 If the switch @option{-gnatL} is used in conjunction with
7230 @cindex @option{-gnatL} (@command{gcc})
7231 @option{-gnatDG}, then the original source lines are interspersed
7232 in the expanded source (as comment lines with the original line number).
7233
7234 The optional parameter @code{nn} if present after -gnatD specifies an
7235 alternative maximum line length that overrides the normal default of 72.
7236 This value is in the range 40-999999, values less than 40 being silently
7237 reset to 40. The equal sign is optional.
7238
7239 @item -gnatr
7240 @cindex @option{-gnatr} (@command{gcc})
7241 @cindex pragma Restrictions
7242 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7243 so that violation of restrictions causes warnings rather than illegalities.
7244 This is useful during the development process when new restrictions are added
7245 or investigated. The switch also causes pragma Profile to be treated as
7246 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7247 restriction warnings rather than restrictions.
7248
7249 @ifclear vms
7250 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7251 @cindex @option{-gnatR} (@command{gcc})
7252 This switch controls output from the compiler of a listing showing
7253 representation information for declared types and objects. For
7254 @option{-gnatR0}, no information is output (equivalent to omitting
7255 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7256 so @option{-gnatR} with no parameter has the same effect), size and alignment
7257 information is listed for declared array and record types. For
7258 @option{-gnatR2}, size and alignment information is listed for all
7259 declared types and objects. Finally @option{-gnatR3} includes symbolic
7260 expressions for values that are computed at run time for
7261 variant records. These symbolic expressions have a mostly obvious
7262 format with #n being used to represent the value of the n'th
7263 discriminant. See source files @file{repinfo.ads/adb} in the
7264 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7265 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7266 the output is to a file with the name @file{^file.rep^file_REP^} where
7267 file is the name of the corresponding source file.
7268 @end ifclear
7269 @ifset vms
7270 @item /REPRESENTATION_INFO
7271 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7272 This qualifier controls output from the compiler of a listing showing
7273 representation information for declared types and objects. For
7274 @option{/REPRESENTATION_INFO=NONE}, no information is output
7275 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7276 @option{/REPRESENTATION_INFO} without option is equivalent to
7277 @option{/REPRESENTATION_INFO=ARRAYS}.
7278 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7279 information is listed for declared array and record types. For
7280 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7281 is listed for all expression information for values that are computed
7282 at run time for variant records. These symbolic expressions have a mostly
7283 obvious format with #n being used to represent the value of the n'th
7284 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7285 @code{GNAT} sources for full details on the format of
7286 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7287 If _FILE is added at the end of an option
7288 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7289 then the output is to a file with the name @file{file_REP} where
7290 file is the name of the corresponding source file.
7291 @end ifset
7292 Note that it is possible for record components to have zero size. In
7293 this case, the component clause uses an obvious extension of permitted
7294 Ada syntax, for example @code{at 0 range 0 .. -1}.
7295
7296 Representation information requires that code be generated (since it is the
7297 code generator that lays out complex data structures). If an attempt is made
7298 to output representation information when no code is generated, for example
7299 when a subunit is compiled on its own, then no information can be generated
7300 and the compiler outputs a message to this effect.
7301
7302 @item -gnatS
7303 @cindex @option{-gnatS} (@command{gcc})
7304 The use of the switch @option{-gnatS} for an
7305 Ada compilation will cause the compiler to output a
7306 representation of package Standard in a form very
7307 close to standard Ada. It is not quite possible to
7308 do this entirely in standard Ada (since new
7309 numeric base types cannot be created in standard
7310 Ada), but the output is easily
7311 readable to any Ada programmer, and is useful to
7312 determine the characteristics of target dependent
7313 types in package Standard.
7314
7315 @item -gnatx
7316 @cindex @option{-gnatx} (@command{gcc})
7317 Normally the compiler generates full cross-referencing information in
7318 the @file{ALI} file. This information is used by a number of tools,
7319 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7320 suppresses this information. This saves some space and may slightly
7321 speed up compilation, but means that these tools cannot be used.
7322 @end table
7323
7324 @node Exception Handling Control
7325 @subsection Exception Handling Control
7326
7327 @noindent
7328 GNAT uses two methods for handling exceptions at run-time. The
7329 @code{setjmp/longjmp} method saves the context when entering
7330 a frame with an exception handler. Then when an exception is
7331 raised, the context can be restored immediately, without the
7332 need for tracing stack frames. This method provides very fast
7333 exception propagation, but introduces significant overhead for
7334 the use of exception handlers, even if no exception is raised.
7335
7336 The other approach is called ``zero cost'' exception handling.
7337 With this method, the compiler builds static tables to describe
7338 the exception ranges. No dynamic code is required when entering
7339 a frame containing an exception handler. When an exception is
7340 raised, the tables are used to control a back trace of the
7341 subprogram invocation stack to locate the required exception
7342 handler. This method has considerably poorer performance for
7343 the propagation of exceptions, but there is no overhead for
7344 exception handlers if no exception is raised. Note that in this
7345 mode and in the context of mixed Ada and C/C++ programming,
7346 to propagate an exception through a C/C++ code, the C/C++ code
7347 must be compiled with the @option{-funwind-tables} GCC's
7348 option.
7349
7350 The following switches may be used to control which of the
7351 two exception handling methods is used.
7352
7353 @table @option
7354 @c !sort!
7355
7356 @item --RTS=sjlj
7357 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7358 This switch causes the setjmp/longjmp run-time (when available) to be used
7359 for exception handling. If the default
7360 mechanism for the target is zero cost exceptions, then
7361 this switch can be used to modify this default, and must be
7362 used for all units in the partition.
7363 This option is rarely used. One case in which it may be
7364 advantageous is if you have an application where exception
7365 raising is common and the overall performance of the
7366 application is improved by favoring exception propagation.
7367
7368 @item --RTS=zcx
7369 @cindex @option{--RTS=zcx} (@command{gnatmake})
7370 @cindex Zero Cost Exceptions
7371 This switch causes the zero cost approach to be used
7372 for exception handling. If this is the default mechanism for the
7373 target (see below), then this switch is unneeded. If the default
7374 mechanism for the target is setjmp/longjmp exceptions, then
7375 this switch can be used to modify this default, and must be
7376 used for all units in the partition.
7377 This option can only be used if the zero cost approach
7378 is available for the target in use, otherwise it will generate an error.
7379 @end table
7380
7381 @noindent
7382 The same option @option{--RTS} must be used both for @command{gcc}
7383 and @command{gnatbind}. Passing this option to @command{gnatmake}
7384 (@pxref{Switches for gnatmake}) will ensure the required consistency
7385 through the compilation and binding steps.
7386
7387 @node Units to Sources Mapping Files
7388 @subsection Units to Sources Mapping Files
7389
7390 @table @option
7391
7392 @item -gnatem=@var{path}
7393 @cindex @option{-gnatem} (@command{gcc})
7394 A mapping file is a way to communicate to the compiler two mappings:
7395 from unit names to file names (without any directory information) and from
7396 file names to path names (with full directory information). These mappings
7397 are used by the compiler to short-circuit the path search.
7398
7399 The use of mapping files is not required for correct operation of the
7400 compiler, but mapping files can improve efficiency, particularly when
7401 sources are read over a slow network connection. In normal operation,
7402 you need not be concerned with the format or use of mapping files,
7403 and the @option{-gnatem} switch is not a switch that you would use
7404 explicitly. It is intended primarily for use by automatic tools such as
7405 @command{gnatmake} running under the project file facility. The
7406 description here of the format of mapping files is provided
7407 for completeness and for possible use by other tools.
7408
7409 A mapping file is a sequence of sets of three lines. In each set, the
7410 first line is the unit name, in lower case, with @code{%s} appended
7411 for specs and @code{%b} appended for bodies; the second line is the
7412 file name; and the third line is the path name.
7413
7414 Example:
7415 @smallexample
7416    main%b
7417    main.2.ada
7418    /gnat/project1/sources/main.2.ada
7419 @end smallexample
7420
7421 When the switch @option{-gnatem} is specified, the compiler will
7422 create in memory the two mappings from the specified file. If there is
7423 any problem (nonexistent file, truncated file or duplicate entries),
7424 no mapping will be created.
7425
7426 Several @option{-gnatem} switches may be specified; however, only the
7427 last one on the command line will be taken into account.
7428
7429 When using a project file, @command{gnatmake} creates a temporary
7430 mapping file and communicates it to the compiler using this switch.
7431
7432 @end table
7433
7434 @node Integrated Preprocessing
7435 @subsection Integrated Preprocessing
7436
7437 @noindent
7438 GNAT sources may be preprocessed immediately before compilation.
7439 In this case, the actual
7440 text of the source is not the text of the source file, but is derived from it
7441 through a process called preprocessing. Integrated preprocessing is specified
7442 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7443 indicates, through a text file, the preprocessing data to be used.
7444 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7445
7446 @noindent
7447 Note that when integrated preprocessing is used, the output from the
7448 preprocessor is not written to any external file. Instead it is passed
7449 internally to the compiler. If you need to preserve the result of
7450 preprocessing in a file, then you should use @command{gnatprep}
7451 to perform the desired preprocessing in stand-alone mode.
7452
7453 @noindent
7454 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7455 used when Integrated Preprocessing is used. The reason is that preprocessing
7456 with another Preprocessing Data file without changing the sources will
7457 not trigger recompilation without this switch.
7458
7459 @noindent
7460 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7461 always trigger recompilation for sources that are preprocessed,
7462 because @command{gnatmake} cannot compute the checksum of the source after
7463 preprocessing.
7464
7465 @noindent
7466 The actual preprocessing function is described in details in section
7467 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7468 preprocessing is triggered and parameterized.
7469
7470 @table @code
7471
7472 @item -gnatep=@var{file}
7473 @cindex @option{-gnatep} (@command{gcc})
7474 This switch indicates to the compiler the file name (without directory
7475 information) of the preprocessor data file to use. The preprocessor data file
7476 should be found in the source directories.
7477
7478 @noindent
7479 A preprocessing data file is a text file with significant lines indicating
7480 how should be preprocessed either a specific source or all sources not
7481 mentioned in other lines. A significant line is a nonempty, non-comment line.
7482 Comments are similar to Ada comments.
7483
7484 @noindent
7485 Each significant line starts with either a literal string or the character '*'.
7486 A literal string is the file name (without directory information) of the source
7487 to preprocess. A character '*' indicates the preprocessing for all the sources
7488 that are not specified explicitly on other lines (order of the lines is not
7489 significant). It is an error to have two lines with the same file name or two
7490 lines starting with the character '*'.
7491
7492 @noindent
7493 After the file name or the character '*', another optional literal string
7494 indicating the file name of the definition file to be used for preprocessing
7495 (@pxref{Form of Definitions File}). The definition files are found by the
7496 compiler in one of the source directories. In some cases, when compiling
7497 a source in a directory other than the current directory, if the definition
7498 file is in the current directory, it may be necessary to add the current
7499 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7500 the compiler would not find the definition file.
7501
7502 @noindent
7503 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7504 be found. Those ^switches^switches^ are:
7505
7506 @table @code
7507
7508 @item -b
7509 Causes both preprocessor lines and the lines deleted by
7510 preprocessing to be replaced by blank lines, preserving the line number.
7511 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7512 it cancels the effect of @option{-c}.
7513
7514 @item -c
7515 Causes both preprocessor lines and the lines deleted
7516 by preprocessing to be retained as comments marked
7517 with the special string ``@code{--! }''.
7518
7519 @item -Dsymbol=value
7520 Define or redefine a symbol, associated with value. A symbol is an Ada
7521 identifier, or an Ada reserved word, with the exception of @code{if},
7522 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7523 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7524 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7525 same name defined in a definition file.
7526
7527 @item -s
7528 Causes a sorted list of symbol names and values to be
7529 listed on the standard output file.
7530
7531 @item -u
7532 Causes undefined symbols to be treated as having the value @code{FALSE}
7533 in the context
7534 of a preprocessor test. In the absence of this option, an undefined symbol in
7535 a @code{#if} or @code{#elsif} test will be treated as an error.
7536
7537 @end table
7538
7539 @noindent
7540 Examples of valid lines in a preprocessor data file:
7541
7542 @smallexample
7543   "toto.adb"  "prep.def" -u
7544   --  preprocess "toto.adb", using definition file "prep.def",
7545   --  undefined symbol are False.
7546
7547   * -c -DVERSION=V101
7548   --  preprocess all other sources without a definition file;
7549   --  suppressed lined are commented; symbol VERSION has the value V101.
7550
7551   "titi.adb" "prep2.def" -s
7552   --  preprocess "titi.adb", using definition file "prep2.def";
7553   --  list all symbols with their values.
7554 @end smallexample
7555
7556 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7557 @cindex @option{-gnateD} (@command{gcc})
7558 Define or redefine a preprocessing symbol, associated with value. If no value
7559 is given on the command line, then the value of the symbol is @code{True}.
7560 A symbol is an identifier, following normal Ada (case-insensitive)
7561 rules for its syntax, and value is any sequence (including an empty sequence)
7562 of characters from the set (letters, digits, period, underline).
7563 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7564 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7565
7566 @noindent
7567 A symbol declared with this ^switch^switch^ on the command line replaces a
7568 symbol with the same name either in a definition file or specified with a
7569 ^switch^switch^ -D in the preprocessor data file.
7570
7571 @noindent
7572 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7573
7574 @item -gnateG
7575 When integrated preprocessing is performed and the preprocessor modifies
7576 the source text, write the result of this preprocessing into a file
7577 <source>^.prep^_prep^.
7578
7579 @end table
7580
7581 @node Code Generation Control
7582 @subsection Code Generation Control
7583
7584 @noindent
7585
7586 The GCC technology provides a wide range of target dependent
7587 @option{-m} switches for controlling
7588 details of code generation with respect to different versions of
7589 architectures. This includes variations in instruction sets (e.g.@:
7590 different members of the power pc family), and different requirements
7591 for optimal arrangement of instructions (e.g.@: different members of
7592 the x86 family). The list of available @option{-m} switches may be
7593 found in the GCC documentation.
7594
7595 Use of these @option{-m} switches may in some cases result in improved
7596 code performance.
7597
7598 The GNAT Pro technology is tested and qualified without any
7599 @option{-m} switches,
7600 so generally the most reliable approach is to avoid the use of these
7601 switches. However, we generally expect most of these switches to work
7602 successfully with GNAT Pro, and many customers have reported successful
7603 use of these options.
7604
7605 Our general advice is to avoid the use of @option{-m} switches unless
7606 special needs lead to requirements in this area. In particular,
7607 there is no point in using @option{-m} switches to improve performance
7608 unless you actually see a performance improvement.
7609
7610 @ifset vms
7611 @node Return Codes
7612 @subsection Return Codes
7613 @cindex Return Codes
7614 @cindex @option{/RETURN_CODES=VMS}
7615
7616 @noindent
7617 On VMS, GNAT compiled programs return POSIX-style codes by default,
7618 e.g.@: @option{/RETURN_CODES=POSIX}.
7619
7620 To enable VMS style return codes, use GNAT BIND and LINK with the option
7621 @option{/RETURN_CODES=VMS}. For example:
7622
7623 @smallexample
7624 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7625 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7626 @end smallexample
7627
7628 @noindent
7629 Programs built with /RETURN_CODES=VMS are suitable to be called in
7630 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7631 are suitable for spawning with appropriate GNAT RTL routines.
7632
7633 @end ifset
7634
7635 @node Search Paths and the Run-Time Library (RTL)
7636 @section Search Paths and the Run-Time Library (RTL)
7637
7638 @noindent
7639 With the GNAT source-based library system, the compiler must be able to
7640 find source files for units that are needed by the unit being compiled.
7641 Search paths are used to guide this process.
7642
7643 The compiler compiles one source file whose name must be given
7644 explicitly on the command line. In other words, no searching is done
7645 for this file. To find all other source files that are needed (the most
7646 common being the specs of units), the compiler examines the following
7647 directories, in the following order:
7648
7649 @enumerate
7650 @item
7651 The directory containing the source file of the main unit being compiled
7652 (the file name on the command line).
7653
7654 @item
7655 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7656 @command{gcc} command line, in the order given.
7657
7658 @item
7659 @findex ADA_PRJ_INCLUDE_FILE
7660 Each of the directories listed in the text file whose name is given
7661 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7662
7663 @noindent
7664 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7665 driver when project files are used. It should not normally be set
7666 by other means.
7667
7668 @item
7669 @findex ADA_INCLUDE_PATH
7670 Each of the directories listed in the value of the
7671 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7672 @ifclear vms
7673 Construct this value
7674 exactly as the @env{PATH} environment variable: a list of directory
7675 names separated by colons (semicolons when working with the NT version).
7676 @end ifclear
7677 @ifset vms
7678 Normally, define this value as a logical name containing a comma separated
7679 list of directory names.
7680
7681 This variable can also be defined by means of an environment string
7682 (an argument to the HP C exec* set of functions).
7683
7684 Logical Name:
7685 @smallexample
7686 DEFINE ANOTHER_PATH FOO:[BAG]
7687 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7688 @end smallexample
7689
7690 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7691 first, followed by the standard Ada
7692 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7693 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7694 (Text_IO, Sequential_IO, etc)
7695 instead of the standard Ada packages. Thus, in order to get the standard Ada
7696 packages by default, ADA_INCLUDE_PATH must be redefined.
7697 @end ifset
7698
7699 @item
7700 The content of the @file{ada_source_path} file which is part of the GNAT
7701 installation tree and is used to store standard libraries such as the
7702 GNAT Run Time Library (RTL) source files.
7703 @ifclear vms
7704 @ref{Installing a library}
7705 @end ifclear
7706 @end enumerate
7707
7708 @noindent
7709 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7710 inhibits the use of the directory
7711 containing the source file named in the command line. You can still
7712 have this directory on your search path, but in this case it must be
7713 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7714
7715 Specifying the switch @option{-nostdinc}
7716 inhibits the search of the default location for the GNAT Run Time
7717 Library (RTL) source files.
7718
7719 The compiler outputs its object files and ALI files in the current
7720 working directory.
7721 @ifclear vms
7722 Caution: The object file can be redirected with the @option{-o} switch;
7723 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7724 so the @file{ALI} file will not go to the right place. Therefore, you should
7725 avoid using the @option{-o} switch.
7726 @end ifclear
7727
7728 @findex System.IO
7729 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7730 children make up the GNAT RTL, together with the simple @code{System.IO}
7731 package used in the @code{"Hello World"} example. The sources for these units
7732 are needed by the compiler and are kept together in one directory. Not
7733 all of the bodies are needed, but all of the sources are kept together
7734 anyway. In a normal installation, you need not specify these directory
7735 names when compiling or binding. Either the environment variables or
7736 the built-in defaults cause these files to be found.
7737
7738 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7739 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7740 consisting of child units of @code{GNAT}. This is a collection of generally
7741 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7742 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7743
7744 Besides simplifying access to the RTL, a major use of search paths is
7745 in compiling sources from multiple directories. This can make
7746 development environments much more flexible.
7747
7748 @node Order of Compilation Issues
7749 @section Order of Compilation Issues
7750
7751 @noindent
7752 If, in our earlier example, there was a spec for the @code{hello}
7753 procedure, it would be contained in the file @file{hello.ads}; yet this
7754 file would not have to be explicitly compiled. This is the result of the
7755 model we chose to implement library management. Some of the consequences
7756 of this model are as follows:
7757
7758 @itemize @bullet
7759 @item
7760 There is no point in compiling specs (except for package
7761 specs with no bodies) because these are compiled as needed by clients. If
7762 you attempt a useless compilation, you will receive an error message.
7763 It is also useless to compile subunits because they are compiled as needed
7764 by the parent.
7765
7766 @item
7767 There are no order of compilation requirements: performing a
7768 compilation never obsoletes anything. The only way you can obsolete
7769 something and require recompilations is to modify one of the
7770 source files on which it depends.
7771
7772 @item
7773 There is no library as such, apart from the ALI files
7774 (@pxref{The Ada Library Information Files}, for information on the format
7775 of these files). For now we find it convenient to create separate ALI files,
7776 but eventually the information therein may be incorporated into the object
7777 file directly.
7778
7779 @item
7780 When you compile a unit, the source files for the specs of all units
7781 that it @code{with}'s, all its subunits, and the bodies of any generics it
7782 instantiates must be available (reachable by the search-paths mechanism
7783 described above), or you will receive a fatal error message.
7784 @end itemize
7785
7786 @node Examples
7787 @section Examples
7788
7789 @noindent
7790 The following are some typical Ada compilation command line examples:
7791
7792 @table @code
7793 @item $ gcc -c xyz.adb
7794 Compile body in file @file{xyz.adb} with all default options.
7795
7796 @ifclear vms
7797 @item $ gcc -c -O2 -gnata xyz-def.adb
7798 @end ifclear
7799 @ifset vms
7800 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7801 @end ifset
7802
7803 Compile the child unit package in file @file{xyz-def.adb} with extensive
7804 optimizations, and pragma @code{Assert}/@code{Debug} statements
7805 enabled.
7806
7807 @item $ gcc -c -gnatc abc-def.adb
7808 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7809 mode.
7810 @end table
7811
7812 @node Binding Using gnatbind
7813 @chapter Binding Using @code{gnatbind}
7814 @findex gnatbind
7815
7816 @menu
7817 * Running gnatbind::
7818 * Switches for gnatbind::
7819 * Command-Line Access::
7820 * Search Paths for gnatbind::
7821 * Examples of gnatbind Usage::
7822 @end menu
7823
7824 @noindent
7825 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7826 to bind compiled GNAT objects.
7827
7828 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7829 driver (see @ref{The GNAT Driver and Project Files}).
7830
7831 The @code{gnatbind} program performs four separate functions:
7832
7833 @enumerate
7834 @item
7835 Checks that a program is consistent, in accordance with the rules in
7836 Chapter 10 of the Ada Reference Manual. In particular, error
7837 messages are generated if a program uses inconsistent versions of a
7838 given unit.
7839
7840 @item
7841 Checks that an acceptable order of elaboration exists for the program
7842 and issues an error message if it cannot find an order of elaboration
7843 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7844
7845 @item
7846 Generates a main program incorporating the given elaboration order.
7847 This program is a small Ada package (body and spec) that
7848 must be subsequently compiled
7849 using the GNAT compiler. The necessary compilation step is usually
7850 performed automatically by @command{gnatlink}. The two most important
7851 functions of this program
7852 are to call the elaboration routines of units in an appropriate order
7853 and to call the main program.
7854
7855 @item
7856 Determines the set of object files required by the given main program.
7857 This information is output in the forms of comments in the generated program,
7858 to be read by the @command{gnatlink} utility used to link the Ada application.
7859 @end enumerate
7860
7861 @node Running gnatbind
7862 @section Running @code{gnatbind}
7863
7864 @noindent
7865 The form of the @code{gnatbind} command is
7866
7867 @smallexample
7868 $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7869 @end smallexample
7870
7871 @noindent
7872 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7873 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7874 package in two files whose names are
7875 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7876 For example, if given the
7877 parameter @file{hello.ali}, for a main program contained in file
7878 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7879 and @file{b~hello.adb}.
7880
7881 When doing consistency checking, the binder takes into consideration
7882 any source files it can locate. For example, if the binder determines
7883 that the given main program requires the package @code{Pack}, whose
7884 @file{.ALI}
7885 file is @file{pack.ali} and whose corresponding source spec file is
7886 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7887 (using the same search path conventions as previously described for the
7888 @command{gcc} command). If it can locate this source file, it checks that
7889 the time stamps
7890 or source checksums of the source and its references to in @file{ALI} files
7891 match. In other words, any @file{ALI} files that mentions this spec must have
7892 resulted from compiling this version of the source file (or in the case
7893 where the source checksums match, a version close enough that the
7894 difference does not matter).
7895
7896 @cindex Source files, use by binder
7897 The effect of this consistency checking, which includes source files, is
7898 that the binder ensures that the program is consistent with the latest
7899 version of the source files that can be located at bind time. Editing a
7900 source file without compiling files that depend on the source file cause
7901 error messages to be generated by the binder.
7902
7903 For example, suppose you have a main program @file{hello.adb} and a
7904 package @code{P}, from file @file{p.ads} and you perform the following
7905 steps:
7906
7907 @enumerate
7908 @item
7909 Enter @code{gcc -c hello.adb} to compile the main program.
7910
7911 @item
7912 Enter @code{gcc -c p.ads} to compile package @code{P}.
7913
7914 @item
7915 Edit file @file{p.ads}.
7916
7917 @item
7918 Enter @code{gnatbind hello}.
7919 @end enumerate
7920
7921 @noindent
7922 At this point, the file @file{p.ali} contains an out-of-date time stamp
7923 because the file @file{p.ads} has been edited. The attempt at binding
7924 fails, and the binder generates the following error messages:
7925
7926 @smallexample
7927 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7928 error: "p.ads" has been modified and must be recompiled
7929 @end smallexample
7930
7931 @noindent
7932 Now both files must be recompiled as indicated, and then the bind can
7933 succeed, generating a main program. You need not normally be concerned
7934 with the contents of this file, but for reference purposes a sample
7935 binder output file is given in @ref{Example of Binder Output File}.
7936
7937 In most normal usage, the default mode of @command{gnatbind} which is to
7938 generate the main package in Ada, as described in the previous section.
7939 In particular, this means that any Ada programmer can read and understand
7940 the generated main program. It can also be debugged just like any other
7941 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7942 @command{gnatbind} and @command{gnatlink}.
7943
7944 However for some purposes it may be convenient to generate the main
7945 program in C rather than Ada. This may for example be helpful when you
7946 are generating a mixed language program with the main program in C. The
7947 GNAT compiler itself is an example.
7948 The use of the @option{^-C^/BIND_FILE=C^} switch
7949 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7950 be generated in C (and compiled using the gnu C compiler).
7951
7952 @node Switches for gnatbind
7953 @section Switches for @command{gnatbind}
7954
7955 @noindent
7956 The following switches are available with @code{gnatbind}; details will
7957 be presented in subsequent sections.
7958
7959 @menu
7960 * Consistency-Checking Modes::
7961 * Binder Error Message Control::
7962 * Elaboration Control::
7963 * Output Control::
7964 * Binding with Non-Ada Main Programs::
7965 * Binding Programs with No Main Subprogram::
7966 @end menu
7967
7968 @table @option
7969 @c !sort!
7970
7971 @item --version
7972 @cindex @option{--version} @command{gnatbind}
7973 Display Copyright and version, then exit disregarding all other options.
7974
7975 @item --help
7976 @cindex @option{--help} @command{gnatbind}
7977 If @option{--version} was not used, display usage, then exit disregarding
7978 all other options.
7979
7980 @item -a
7981 @cindex @option{-a} @command{gnatbind}
7982 Indicates that, if supported by the platform, the adainit procedure should
7983 be treated as an initialisation routine by the linker (a constructor). This
7984 is intended to be used by the Project Manager to automatically initialize
7985 shared Stand-Alone Libraries.
7986
7987 @item ^-aO^/OBJECT_SEARCH^
7988 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7989 Specify directory to be searched for ALI files.
7990
7991 @item ^-aI^/SOURCE_SEARCH^
7992 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7993 Specify directory to be searched for source file.
7994
7995 @item ^-A^/BIND_FILE=ADA^
7996 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7997 Generate binder program in Ada (default)
7998
7999 @item ^-b^/REPORT_ERRORS=BRIEF^
8000 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8001 Generate brief messages to @file{stderr} even if verbose mode set.
8002
8003 @item ^-c^/NOOUTPUT^
8004 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8005 Check only, no generation of binder output file.
8006
8007 @item ^-C^/BIND_FILE=C^
8008 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
8009 Generate binder program in C
8010
8011 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8012 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8013 This switch can be used to change the default task stack size value
8014 to a specified size @var{nn}, which is expressed in bytes by default, or
8015 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8016 with @var{m}.
8017 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8018 in effect, to completing all task specs with
8019 @smallexample @c ada
8020    pragma Storage_Size (nn);
8021 @end smallexample
8022 When they do not already have such a pragma.
8023
8024 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8025 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8026 This switch can be used to change the default secondary stack size value
8027 to a specified size @var{nn}, which is expressed in bytes by default, or
8028 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8029 with @var{m}.
8030
8031 The secondary stack is used to deal with functions that return a variable
8032 sized result, for example a function returning an unconstrained
8033 String. There are two ways in which this secondary stack is allocated.
8034
8035 For most targets, the secondary stack is growing on demand and is allocated
8036 as a chain of blocks in the heap. The -D option is not very
8037 relevant. It only give some control over the size of the allocated
8038 blocks (whose size is the minimum of the default secondary stack size value,
8039 and the actual size needed for the current allocation request).
8040
8041 For certain targets, notably VxWorks 653,
8042 the secondary stack is allocated by carving off a fixed ratio chunk of the
8043 primary task stack. The -D option is used to define the
8044 size of the environment task's secondary stack.
8045
8046 @item ^-e^/ELABORATION_DEPENDENCIES^
8047 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8048 Output complete list of elaboration-order dependencies.
8049
8050 @item ^-E^/STORE_TRACEBACKS^
8051 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8052 Store tracebacks in exception occurrences when the target supports it.
8053 This is the default with the zero cost exception mechanism.
8054 @ignore
8055 @c The following may get moved to an appendix
8056 This option is currently supported on the following targets:
8057 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8058 @end ignore
8059 See also the packages @code{GNAT.Traceback} and
8060 @code{GNAT.Traceback.Symbolic} for more information.
8061 @ifclear vms
8062 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8063 @command{gcc} option.
8064 @end ifclear
8065
8066 @item ^-F^/FORCE_ELABS_FLAGS^
8067 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8068 Force the checks of elaboration flags. @command{gnatbind} does not normally
8069 generate checks of elaboration flags for the main executable, except when
8070 a Stand-Alone Library is used. However, there are cases when this cannot be
8071 detected by gnatbind. An example is importing an interface of a Stand-Alone
8072 Library through a pragma Import and only specifying through a linker switch
8073 this Stand-Alone Library. This switch is used to guarantee that elaboration
8074 flag checks are generated.
8075
8076 @item ^-h^/HELP^
8077 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8078 Output usage (help) information
8079
8080 @item ^-I^/SEARCH^
8081 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8082 Specify directory to be searched for source and ALI files.
8083
8084 @item ^-I-^/NOCURRENT_DIRECTORY^
8085 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8086 Do not look for sources in the current directory where @code{gnatbind} was
8087 invoked, and do not look for ALI files in the directory containing the
8088 ALI file named in the @code{gnatbind} command line.
8089
8090 @item ^-l^/ORDER_OF_ELABORATION^
8091 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8092 Output chosen elaboration order.
8093
8094 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8095 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8096 Bind the units for library building. In this case the adainit and
8097 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8098 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8099 ^@var{xxx}final^@var{XXX}FINAL^.
8100 Implies ^-n^/NOCOMPILE^.
8101 @ifclear vms
8102 (@xref{GNAT and Libraries}, for more details.)
8103 @end ifclear
8104 @ifset vms
8105 On OpenVMS, these init and final procedures are exported in uppercase
8106 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8107 the init procedure will be "TOTOINIT" and the exported name of the final
8108 procedure will be "TOTOFINAL".
8109 @end ifset
8110
8111 @item ^-Mxyz^/RENAME_MAIN=xyz^
8112 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8113 Rename generated main program from main to xyz. This option is
8114 supported on cross environments only.
8115
8116 @item ^-m^/ERROR_LIMIT=^@var{n}
8117 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8118 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8119 in the range 1..999999. The default value if no switch is
8120 given is 9999. If the number of warnings reaches this limit, then a
8121 message is output and further warnings are suppressed, the bind
8122 continues in this case. If the number of errors reaches this
8123 limit, then a message is output and the bind is abandoned.
8124 A value of zero means that no limit is enforced. The equal
8125 sign is optional.
8126
8127 @ifset unw
8128 Furthermore, under Windows, the sources pointed to by the libraries path
8129 set in the registry are not searched for.
8130 @end ifset
8131
8132 @item ^-n^/NOMAIN^
8133 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8134 No main program.
8135
8136 @item -nostdinc
8137 @cindex @option{-nostdinc} (@command{gnatbind})
8138 Do not look for sources in the system default directory.
8139
8140 @item -nostdlib
8141 @cindex @option{-nostdlib} (@command{gnatbind})
8142 Do not look for library files in the system default directory.
8143
8144 @item --RTS=@var{rts-path}
8145 @cindex @option{--RTS} (@code{gnatbind})
8146 Specifies the default location of the runtime library. Same meaning as the
8147 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8148
8149 @item ^-o ^/OUTPUT=^@var{file}
8150 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8151 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8152 Note that if this option is used, then linking must be done manually,
8153 gnatlink cannot be used.
8154
8155 @item ^-O^/OBJECT_LIST^
8156 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8157 Output object list.
8158
8159 @item ^-p^/PESSIMISTIC_ELABORATION^
8160 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8161 Pessimistic (worst-case) elaboration order
8162
8163 @item ^-R^-R^
8164 @cindex @option{^-R^-R^} (@command{gnatbind})
8165 Output closure source list.
8166
8167 @item ^-s^/READ_SOURCES=ALL^
8168 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8169 Require all source files to be present.
8170
8171 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8172 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8173 Specifies the value to be used when detecting uninitialized scalar
8174 objects with pragma Initialize_Scalars.
8175 The @var{xxx} ^string specified with the switch^option^ may be either
8176 @itemize @bullet
8177 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8178 @item ``@option{^lo^LOW^}'' for the lowest possible value
8179 @item ``@option{^hi^HIGH^}'' for the highest possible value
8180 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8181 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8182 @end itemize
8183
8184 In addition, you can specify @option{-Sev} to indicate that the value is
8185 to be set at run time. In this case, the program will look for an environment
8186 @cindex GNAT_INIT_SCALARS
8187 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8188 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8189 If no environment variable is found, or if it does not have a valid value,
8190 then the default is @option{in} (invalid values).
8191
8192 @ifclear vms
8193 @item -static
8194 @cindex @option{-static} (@code{gnatbind})
8195 Link against a static GNAT run time.
8196
8197 @item -shared
8198 @cindex @option{-shared} (@code{gnatbind})
8199 Link against a shared GNAT run time when available.
8200 @end ifclear
8201
8202 @item ^-t^/NOTIME_STAMP_CHECK^
8203 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8204 Tolerate time stamp and other consistency errors
8205
8206 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8207 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8208 Set the time slice value to @var{n} milliseconds. If the system supports
8209 the specification of a specific time slice value, then the indicated value
8210 is used. If the system does not support specific time slice values, but
8211 does support some general notion of round-robin scheduling, then any
8212 nonzero value will activate round-robin scheduling.
8213
8214 A value of zero is treated specially. It turns off time
8215 slicing, and in addition, indicates to the tasking run time that the
8216 semantics should match as closely as possible the Annex D
8217 requirements of the Ada RM, and in particular sets the default
8218 scheduling policy to @code{FIFO_Within_Priorities}.
8219
8220 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8221 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8222 Enable dynamic stack usage, with @var{n} results stored and displayed
8223 at program termination. A result is generated when a task
8224 terminates. Results that can't be stored are displayed on the fly, at
8225 task termination. This option is currently not supported on Itanium
8226 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8227
8228 @item ^-v^/REPORT_ERRORS=VERBOSE^
8229 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8230 Verbose mode. Write error messages, header, summary output to
8231 @file{stdout}.
8232
8233 @ifclear vms
8234 @item -w@var{x}
8235 @cindex @option{-w} (@code{gnatbind})
8236 Warning mode (@var{x}=s/e for suppress/treat as error)
8237 @end ifclear
8238
8239 @ifset vms
8240 @item /WARNINGS=NORMAL
8241 @cindex @option{/WARNINGS} (@code{gnatbind})
8242 Normal warnings mode. Warnings are issued but ignored
8243
8244 @item /WARNINGS=SUPPRESS
8245 @cindex @option{/WARNINGS} (@code{gnatbind})
8246 All warning messages are suppressed
8247
8248 @item /WARNINGS=ERROR
8249 @cindex @option{/WARNINGS} (@code{gnatbind})
8250 Warning messages are treated as fatal errors
8251 @end ifset
8252
8253 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8254 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8255 Override default wide character encoding for standard Text_IO files.
8256
8257 @item ^-x^/READ_SOURCES=NONE^
8258 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8259 Exclude source files (check object consistency only).
8260
8261 @ifset vms
8262 @item /READ_SOURCES=AVAILABLE
8263 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8264 Default mode, in which sources are checked for consistency only if
8265 they are available.
8266 @end ifset
8267
8268 @item ^-y^/ENABLE_LEAP_SECONDS^
8269 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8270 Enable leap seconds support in @code{Ada.Calendar} and its children.
8271
8272 @item ^-z^/ZERO_MAIN^
8273 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8274 No main subprogram.
8275 @end table
8276
8277 @ifclear vms
8278 @noindent
8279 You may obtain this listing of switches by running @code{gnatbind} with
8280 no arguments.
8281 @end ifclear
8282
8283 @node Consistency-Checking Modes
8284 @subsection Consistency-Checking Modes
8285
8286 @noindent
8287 As described earlier, by default @code{gnatbind} checks
8288 that object files are consistent with one another and are consistent
8289 with any source files it can locate. The following switches control binder
8290 access to sources.
8291
8292 @table @option
8293 @c !sort!
8294 @item ^-s^/READ_SOURCES=ALL^
8295 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8296 Require source files to be present. In this mode, the binder must be
8297 able to locate all source files that are referenced, in order to check
8298 their consistency. In normal mode, if a source file cannot be located it
8299 is simply ignored. If you specify this switch, a missing source
8300 file is an error.
8301
8302 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8303 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8304 Override default wide character encoding for standard Text_IO files.
8305 Normally the default wide character encoding method used for standard
8306 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8307 the main source input (see description of switch
8308 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8309 use of this switch for the binder (which has the same set of
8310 possible arguments) overrides this default as specified.
8311
8312 @item ^-x^/READ_SOURCES=NONE^
8313 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8314 Exclude source files. In this mode, the binder only checks that ALI
8315 files are consistent with one another. Source files are not accessed.
8316 The binder runs faster in this mode, and there is still a guarantee that
8317 the resulting program is self-consistent.
8318 If a source file has been edited since it was last compiled, and you
8319 specify this switch, the binder will not detect that the object
8320 file is out of date with respect to the source file. Note that this is the
8321 mode that is automatically used by @command{gnatmake} because in this
8322 case the checking against sources has already been performed by
8323 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8324
8325 @ifset vms
8326 @item /READ_SOURCES=AVAILABLE
8327 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8328 This is the default mode in which source files are checked if they are
8329 available, and ignored if they are not available.
8330 @end ifset
8331 @end table
8332
8333 @node Binder Error Message Control
8334 @subsection Binder Error Message Control
8335
8336 @noindent
8337 The following switches provide control over the generation of error
8338 messages from the binder:
8339
8340 @table @option
8341 @c !sort!
8342 @item ^-v^/REPORT_ERRORS=VERBOSE^
8343 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8344 Verbose mode. In the normal mode, brief error messages are generated to
8345 @file{stderr}. If this switch is present, a header is written
8346 to @file{stdout} and any error messages are directed to @file{stdout}.
8347 All that is written to @file{stderr} is a brief summary message.
8348
8349 @item ^-b^/REPORT_ERRORS=BRIEF^
8350 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8351 Generate brief error messages to @file{stderr} even if verbose mode is
8352 specified. This is relevant only when used with the
8353 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8354
8355 @ifclear vms
8356 @item -m@var{n}
8357 @cindex @option{-m} (@code{gnatbind})
8358 Limits the number of error messages to @var{n}, a decimal integer in the
8359 range 1-999. The binder terminates immediately if this limit is reached.
8360
8361 @item -M@var{xxx}
8362 @cindex @option{-M} (@code{gnatbind})
8363 Renames the generated main program from @code{main} to @code{xxx}.
8364 This is useful in the case of some cross-building environments, where
8365 the actual main program is separate from the one generated
8366 by @code{gnatbind}.
8367 @end ifclear
8368
8369 @item ^-ws^/WARNINGS=SUPPRESS^
8370 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8371 @cindex Warnings
8372 Suppress all warning messages.
8373
8374 @item ^-we^/WARNINGS=ERROR^
8375 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8376 Treat any warning messages as fatal errors.
8377
8378 @ifset vms
8379 @item /WARNINGS=NORMAL
8380 Standard mode with warnings generated, but warnings do not get treated
8381 as errors.
8382 @end ifset
8383
8384 @item ^-t^/NOTIME_STAMP_CHECK^
8385 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8386 @cindex Time stamp checks, in binder
8387 @cindex Binder consistency checks
8388 @cindex Consistency checks, in binder
8389 The binder performs a number of consistency checks including:
8390
8391 @itemize @bullet
8392 @item
8393 Check that time stamps of a given source unit are consistent
8394 @item
8395 Check that checksums of a given source unit are consistent
8396 @item
8397 Check that consistent versions of @code{GNAT} were used for compilation
8398 @item
8399 Check consistency of configuration pragmas as required
8400 @end itemize
8401
8402 @noindent
8403 Normally failure of such checks, in accordance with the consistency
8404 requirements of the Ada Reference Manual, causes error messages to be
8405 generated which abort the binder and prevent the output of a binder
8406 file and subsequent link to obtain an executable.
8407
8408 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8409 into warnings, so that
8410 binding and linking can continue to completion even in the presence of such
8411 errors. The result may be a failed link (due to missing symbols), or a
8412 non-functional executable which has undefined semantics.
8413 @emph{This means that
8414 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8415 with extreme care.}
8416 @end table
8417
8418 @node Elaboration Control
8419 @subsection Elaboration Control
8420
8421 @noindent
8422 The following switches provide additional control over the elaboration
8423 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8424
8425 @table @option
8426 @item ^-p^/PESSIMISTIC_ELABORATION^
8427 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8428 Normally the binder attempts to choose an elaboration order that is
8429 likely to minimize the likelihood of an elaboration order error resulting
8430 in raising a @code{Program_Error} exception. This switch reverses the
8431 action of the binder, and requests that it deliberately choose an order
8432 that is likely to maximize the likelihood of an elaboration error.
8433 This is useful in ensuring portability and avoiding dependence on
8434 accidental fortuitous elaboration ordering.
8435
8436 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8437 switch if dynamic
8438 elaboration checking is used (@option{-gnatE} switch used for compilation).
8439 This is because in the default static elaboration mode, all necessary
8440 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8441 These implicit pragmas are still respected by the binder in
8442 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8443 safe elaboration order is assured.
8444 @end table
8445
8446 @node Output Control
8447 @subsection Output Control
8448
8449 @noindent
8450 The following switches allow additional control over the output
8451 generated by the binder.
8452
8453 @table @option
8454 @c !sort!
8455
8456 @item ^-A^/BIND_FILE=ADA^
8457 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
8458 Generate binder program in Ada (default). The binder program is named
8459 @file{b~@var{mainprog}.adb} by default. This can be changed with
8460 @option{^-o^/OUTPUT^} @code{gnatbind} option.
8461
8462 @item ^-c^/NOOUTPUT^
8463 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8464 Check only. Do not generate the binder output file. In this mode the
8465 binder performs all error checks but does not generate an output file.
8466
8467 @item ^-C^/BIND_FILE=C^
8468 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
8469 Generate binder program in C. The binder program is named
8470 @file{b_@var{mainprog}.c}.
8471 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
8472 option.
8473
8474 @item ^-e^/ELABORATION_DEPENDENCIES^
8475 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8476 Output complete list of elaboration-order dependencies, showing the
8477 reason for each dependency. This output can be rather extensive but may
8478 be useful in diagnosing problems with elaboration order. The output is
8479 written to @file{stdout}.
8480
8481 @item ^-h^/HELP^
8482 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8483 Output usage information. The output is written to @file{stdout}.
8484
8485 @item ^-K^/LINKER_OPTION_LIST^
8486 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8487 Output linker options to @file{stdout}. Includes library search paths,
8488 contents of pragmas Ident and Linker_Options, and libraries added
8489 by @code{gnatbind}.
8490
8491 @item ^-l^/ORDER_OF_ELABORATION^
8492 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8493 Output chosen elaboration order. The output is written to @file{stdout}.
8494
8495 @item ^-O^/OBJECT_LIST^
8496 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8497 Output full names of all the object files that must be linked to provide
8498 the Ada component of the program. The output is written to @file{stdout}.
8499 This list includes the files explicitly supplied and referenced by the user
8500 as well as implicitly referenced run-time unit files. The latter are
8501 omitted if the corresponding units reside in shared libraries. The
8502 directory names for the run-time units depend on the system configuration.
8503
8504 @item ^-o ^/OUTPUT=^@var{file}
8505 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8506 Set name of output file to @var{file} instead of the normal
8507 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8508 binder generated body filename. In C mode you would normally give
8509 @var{file} an extension of @file{.c} because it will be a C source program.
8510 Note that if this option is used, then linking must be done manually.
8511 It is not possible to use gnatlink in this case, since it cannot locate
8512 the binder file.
8513
8514 @item ^-r^/RESTRICTION_LIST^
8515 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8516 Generate list of @code{pragma Restrictions} that could be applied to
8517 the current unit. This is useful for code audit purposes, and also may
8518 be used to improve code generation in some cases.
8519
8520 @end table
8521
8522 @node Binding with Non-Ada Main Programs
8523 @subsection Binding with Non-Ada Main Programs
8524
8525 @noindent
8526 In our description so far we have assumed that the main
8527 program is in Ada, and that the task of the binder is to generate a
8528 corresponding function @code{main} that invokes this Ada main
8529 program. GNAT also supports the building of executable programs where
8530 the main program is not in Ada, but some of the called routines are
8531 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8532 The following switch is used in this situation:
8533
8534 @table @option
8535 @item ^-n^/NOMAIN^
8536 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8537 No main program. The main program is not in Ada.
8538 @end table
8539
8540 @noindent
8541 In this case, most of the functions of the binder are still required,
8542 but instead of generating a main program, the binder generates a file
8543 containing the following callable routines:
8544
8545 @table @code
8546 @item adainit
8547 @findex adainit
8548 You must call this routine to initialize the Ada part of the program by
8549 calling the necessary elaboration routines. A call to @code{adainit} is
8550 required before the first call to an Ada subprogram.
8551
8552 Note that it is assumed that the basic execution environment must be setup
8553 to be appropriate for Ada execution at the point where the first Ada
8554 subprogram is called. In particular, if the Ada code will do any
8555 floating-point operations, then the FPU must be setup in an appropriate
8556 manner. For the case of the x86, for example, full precision mode is
8557 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8558 that the FPU is in the right state.
8559
8560 @item adafinal
8561 @findex adafinal
8562 You must call this routine to perform any library-level finalization
8563 required by the Ada subprograms. A call to @code{adafinal} is required
8564 after the last call to an Ada subprogram, and before the program
8565 terminates.
8566 @end table
8567
8568 @noindent
8569 If the @option{^-n^/NOMAIN^} switch
8570 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8571 @cindex Binder, multiple input files
8572 is given, more than one ALI file may appear on
8573 the command line for @code{gnatbind}. The normal @dfn{closure}
8574 calculation is performed for each of the specified units. Calculating
8575 the closure means finding out the set of units involved by tracing
8576 @code{with} references. The reason it is necessary to be able to
8577 specify more than one ALI file is that a given program may invoke two or
8578 more quite separate groups of Ada units.
8579
8580 The binder takes the name of its output file from the last specified ALI
8581 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8582 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8583 The output is an Ada unit in source form that can
8584 be compiled with GNAT unless the -C switch is used in which case the
8585 output is a C source file, which must be compiled using the C compiler.
8586 This compilation occurs automatically as part of the @command{gnatlink}
8587 processing.
8588
8589 Currently the GNAT run time requires a FPU using 80 bits mode
8590 precision. Under targets where this is not the default it is required to
8591 call GNAT.Float_Control.Reset before using floating point numbers (this
8592 include float computation, float input and output) in the Ada code. A
8593 side effect is that this could be the wrong mode for the foreign code
8594 where floating point computation could be broken after this call.
8595
8596 @node Binding Programs with No Main Subprogram
8597 @subsection Binding Programs with No Main Subprogram
8598
8599 @noindent
8600 It is possible to have an Ada program which does not have a main
8601 subprogram. This program will call the elaboration routines of all the
8602 packages, then the finalization routines.
8603
8604 The following switch is used to bind programs organized in this manner:
8605
8606 @table @option
8607 @item ^-z^/ZERO_MAIN^
8608 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8609 Normally the binder checks that the unit name given on the command line
8610 corresponds to a suitable main subprogram. When this switch is used,
8611 a list of ALI files can be given, and the execution of the program
8612 consists of elaboration of these units in an appropriate order. Note
8613 that the default wide character encoding method for standard Text_IO
8614 files is always set to Brackets if this switch is set (you can use
8615 the binder switch
8616 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8617 @end table
8618
8619 @node Command-Line Access
8620 @section Command-Line Access
8621
8622 @noindent
8623 The package @code{Ada.Command_Line} provides access to the command-line
8624 arguments and program name. In order for this interface to operate
8625 correctly, the two variables
8626
8627 @smallexample
8628 @group
8629 int gnat_argc;
8630 char **gnat_argv;
8631 @end group
8632 @end smallexample
8633
8634 @noindent
8635 @findex gnat_argv
8636 @findex gnat_argc
8637 are declared in one of the GNAT library routines. These variables must
8638 be set from the actual @code{argc} and @code{argv} values passed to the
8639 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8640 generates the C main program to automatically set these variables.
8641 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8642 set these variables. If they are not set, the procedures in
8643 @code{Ada.Command_Line} will not be available, and any attempt to use
8644 them will raise @code{Constraint_Error}. If command line access is
8645 required, your main program must set @code{gnat_argc} and
8646 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8647 it.
8648
8649 @node Search Paths for gnatbind
8650 @section Search Paths for @code{gnatbind}
8651
8652 @noindent
8653 The binder takes the name of an ALI file as its argument and needs to
8654 locate source files as well as other ALI files to verify object consistency.
8655
8656 For source files, it follows exactly the same search rules as @command{gcc}
8657 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8658 directories searched are:
8659
8660 @enumerate
8661 @item
8662 The directory containing the ALI file named in the command line, unless
8663 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8664
8665 @item
8666 All directories specified by @option{^-I^/SEARCH^}
8667 switches on the @code{gnatbind}
8668 command line, in the order given.
8669
8670 @item
8671 @findex ADA_PRJ_OBJECTS_FILE
8672 Each of the directories listed in the text file whose name is given
8673 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8674
8675 @noindent
8676 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8677 driver when project files are used. It should not normally be set
8678 by other means.
8679
8680 @item
8681 @findex ADA_OBJECTS_PATH
8682 Each of the directories listed in the value of the
8683 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8684 @ifset unw
8685 Construct this value
8686 exactly as the @env{PATH} environment variable: a list of directory
8687 names separated by colons (semicolons when working with the NT version
8688 of GNAT).
8689 @end ifset
8690 @ifset vms
8691 Normally, define this value as a logical name containing a comma separated
8692 list of directory names.
8693
8694 This variable can also be defined by means of an environment string
8695 (an argument to the HP C exec* set of functions).
8696
8697 Logical Name:
8698 @smallexample
8699 DEFINE ANOTHER_PATH FOO:[BAG]
8700 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8701 @end smallexample
8702
8703 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8704 first, followed by the standard Ada
8705 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8706 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8707 (Text_IO, Sequential_IO, etc)
8708 instead of the standard Ada packages. Thus, in order to get the standard Ada
8709 packages by default, ADA_OBJECTS_PATH must be redefined.
8710 @end ifset
8711
8712 @item
8713 The content of the @file{ada_object_path} file which is part of the GNAT
8714 installation tree and is used to store standard libraries such as the
8715 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8716 specified.
8717 @ifclear vms
8718 @ref{Installing a library}
8719 @end ifclear
8720 @end enumerate
8721
8722 @noindent
8723 In the binder the switch @option{^-I^/SEARCH^}
8724 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8725 is used to specify both source and
8726 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8727 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8728 instead if you want to specify
8729 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8730 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8731 if you want to specify library paths
8732 only. This means that for the binder
8733 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8734 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8735 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8736 The binder generates the bind file (a C language source file) in the
8737 current working directory.
8738
8739 @findex Ada
8740 @findex System
8741 @findex Interfaces
8742 @findex GNAT
8743 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8744 children make up the GNAT Run-Time Library, together with the package
8745 GNAT and its children, which contain a set of useful additional
8746 library functions provided by GNAT. The sources for these units are
8747 needed by the compiler and are kept together in one directory. The ALI
8748 files and object files generated by compiling the RTL are needed by the
8749 binder and the linker and are kept together in one directory, typically
8750 different from the directory containing the sources. In a normal
8751 installation, you need not specify these directory names when compiling
8752 or binding. Either the environment variables or the built-in defaults
8753 cause these files to be found.
8754
8755 Besides simplifying access to the RTL, a major use of search paths is
8756 in compiling sources from multiple directories. This can make
8757 development environments much more flexible.
8758
8759 @node Examples of gnatbind Usage
8760 @section Examples of @code{gnatbind} Usage
8761
8762 @noindent
8763 This section contains a number of examples of using the GNAT binding
8764 utility @code{gnatbind}.
8765
8766 @table @code
8767 @item gnatbind hello
8768 The main program @code{Hello} (source program in @file{hello.adb}) is
8769 bound using the standard switch settings. The generated main program is
8770 @file{b~hello.adb}. This is the normal, default use of the binder.
8771
8772 @ifclear vms
8773 @item gnatbind hello -o mainprog.adb
8774 @end ifclear
8775 @ifset vms
8776 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8777 @end ifset
8778 The main program @code{Hello} (source program in @file{hello.adb}) is
8779 bound using the standard switch settings. The generated main program is
8780 @file{mainprog.adb} with the associated spec in
8781 @file{mainprog.ads}. Note that you must specify the body here not the
8782 spec, in the case where the output is in Ada. Note that if this option
8783 is used, then linking must be done manually, since gnatlink will not
8784 be able to find the generated file.
8785
8786 @ifclear vms
8787 @item gnatbind main -C -o mainprog.c -x
8788 @end ifclear
8789 @ifset vms
8790 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8791 @end ifset
8792 The main program @code{Main} (source program in
8793 @file{main.adb}) is bound, excluding source files from the
8794 consistency checking, generating
8795 the file @file{mainprog.c}.
8796
8797 @ifclear vms
8798 @item gnatbind -x main_program -C -o mainprog.c
8799 This command is exactly the same as the previous example. Switches may
8800 appear anywhere in the command line, and single letter switches may be
8801 combined into a single switch.
8802 @end ifclear
8803
8804 @ifclear vms
8805 @item gnatbind -n math dbase -C -o ada-control.c
8806 @end ifclear
8807 @ifset vms
8808 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8809 @end ifset
8810 The main program is in a language other than Ada, but calls to
8811 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8812 to @code{gnatbind} generates the file @file{ada-control.c} containing
8813 the @code{adainit} and @code{adafinal} routines to be called before and
8814 after accessing the Ada units.
8815 @end table
8816
8817 @c ------------------------------------
8818 @node Linking Using gnatlink
8819 @chapter Linking Using @command{gnatlink}
8820 @c ------------------------------------
8821 @findex gnatlink
8822
8823 @noindent
8824 This chapter discusses @command{gnatlink}, a tool that links
8825 an Ada program and builds an executable file. This utility
8826 invokes the system linker ^(via the @command{gcc} command)^^
8827 with a correct list of object files and library references.
8828 @command{gnatlink} automatically determines the list of files and
8829 references for the Ada part of a program. It uses the binder file
8830 generated by the @command{gnatbind} to determine this list.
8831
8832 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8833 driver (see @ref{The GNAT Driver and Project Files}).
8834
8835 @menu
8836 * Running gnatlink::
8837 * Switches for gnatlink::
8838 @end menu
8839
8840 @node Running gnatlink
8841 @section Running @command{gnatlink}
8842
8843 @noindent
8844 The form of the @command{gnatlink} command is
8845
8846 @smallexample
8847 $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8848            @ovar{non-Ada objects} @ovar{linker options}
8849 @end smallexample
8850
8851 @noindent
8852 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8853 non-Ada objects
8854 or linker options) may be in any order, provided that no non-Ada object may
8855 be mistaken for a main @file{ALI} file.
8856 Any file name @file{F} without the @file{.ali}
8857 extension will be taken as the main @file{ALI} file if a file exists
8858 whose name is the concatenation of @file{F} and @file{.ali}.
8859
8860 @noindent
8861 @file{@var{mainprog}.ali} references the ALI file of the main program.
8862 The @file{.ali} extension of this file can be omitted. From this
8863 reference, @command{gnatlink} locates the corresponding binder file
8864 @file{b~@var{mainprog}.adb} and, using the information in this file along
8865 with the list of non-Ada objects and linker options, constructs a
8866 linker command file to create the executable.
8867
8868 The arguments other than the @command{gnatlink} switches and the main
8869 @file{ALI} file are passed to the linker uninterpreted.
8870 They typically include the names of
8871 object files for units written in other languages than Ada and any library
8872 references required to resolve references in any of these foreign language
8873 units, or in @code{Import} pragmas in any Ada units.
8874
8875 @var{linker options} is an optional list of linker specific
8876 switches.
8877 The default linker called by gnatlink is @command{gcc} which in
8878 turn calls the appropriate system linker.
8879 Standard options for the linker such as @option{-lmy_lib} or
8880 @option{-Ldir} can be added as is.
8881 For options that are not recognized by
8882 @command{gcc} as linker options, use the @command{gcc} switches
8883 @option{-Xlinker} or @option{-Wl,}.
8884 Refer to the GCC documentation for
8885 details. Here is an example showing how to generate a linker map:
8886
8887 @smallexample
8888 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8889 @end smallexample
8890
8891 Using @var{linker options} it is possible to set the program stack and
8892 heap size.
8893 @ifset unw
8894 See @ref{Setting Stack Size from gnatlink} and
8895 @ref{Setting Heap Size from gnatlink}.
8896 @end ifset
8897
8898 @command{gnatlink} determines the list of objects required by the Ada
8899 program and prepends them to the list of objects passed to the linker.
8900 @command{gnatlink} also gathers any arguments set by the use of
8901 @code{pragma Linker_Options} and adds them to the list of arguments
8902 presented to the linker.
8903
8904 @ifset vms
8905 @command{gnatlink} accepts the following types of extra files on the command
8906 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8907 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8908 handled according to their extension.
8909 @end ifset
8910
8911 @node Switches for gnatlink
8912 @section Switches for @command{gnatlink}
8913
8914 @noindent
8915 The following switches are available with the @command{gnatlink} utility:
8916
8917 @table @option
8918 @c !sort!
8919
8920 @item --version
8921 @cindex @option{--version} @command{gnatlink}
8922 Display Copyright and version, then exit disregarding all other options.
8923
8924 @item --help
8925 @cindex @option{--help} @command{gnatlink}
8926 If @option{--version} was not used, display usage, then exit disregarding
8927 all other options.
8928
8929 @item ^-A^/BIND_FILE=ADA^
8930 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8931 The binder has generated code in Ada. This is the default.
8932
8933 @item ^-C^/BIND_FILE=C^
8934 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8935 If instead of generating a file in Ada, the binder has generated one in
8936 C, then the linker needs to know about it. Use this switch to signal
8937 to @command{gnatlink} that the binder has generated C code rather than
8938 Ada code.
8939
8940 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8941 @cindex Command line length
8942 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8943 On some targets, the command line length is limited, and @command{gnatlink}
8944 will generate a separate file for the linker if the list of object files
8945 is too long.
8946 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8947 to be generated even if
8948 the limit is not exceeded. This is useful in some cases to deal with
8949 special situations where the command line length is exceeded.
8950
8951 @item ^-g^/DEBUG^
8952 @cindex Debugging information, including
8953 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8954 The option to include debugging information causes the Ada bind file (in
8955 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8956 @option{^-g^/DEBUG^}.
8957 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8958 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8959 Without @option{^-g^/DEBUG^}, the binder removes these files by
8960 default. The same procedure apply if a C bind file was generated using
8961 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8962 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8963
8964 @item ^-n^/NOCOMPILE^
8965 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8966 Do not compile the file generated by the binder. This may be used when
8967 a link is rerun with different options, but there is no need to recompile
8968 the binder file.
8969
8970 @item ^-v^/VERBOSE^
8971 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8972 Causes additional information to be output, including a full list of the
8973 included object files. This switch option is most useful when you want
8974 to see what set of object files are being used in the link step.
8975
8976 @item ^-v -v^/VERBOSE/VERBOSE^
8977 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8978 Very verbose mode. Requests that the compiler operate in verbose mode when
8979 it compiles the binder file, and that the system linker run in verbose mode.
8980
8981 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8982 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8983 @var{exec-name} specifies an alternate name for the generated
8984 executable program. If this switch is omitted, the executable has the same
8985 name as the main unit. For example, @code{gnatlink try.ali} creates
8986 an executable called @file{^try^TRY.EXE^}.
8987
8988 @ifclear vms
8989 @item -b @var{target}
8990 @cindex @option{-b} (@command{gnatlink})
8991 Compile your program to run on @var{target}, which is the name of a
8992 system configuration. You must have a GNAT cross-compiler built if
8993 @var{target} is not the same as your host system.
8994
8995 @item -B@var{dir}
8996 @cindex @option{-B} (@command{gnatlink})
8997 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8998 from @var{dir} instead of the default location. Only use this switch
8999 when multiple versions of the GNAT compiler are available.
9000 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9001 for further details. You would normally use the @option{-b} or
9002 @option{-V} switch instead.
9003
9004 @item --GCC=@var{compiler_name}
9005 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9006 Program used for compiling the binder file. The default is
9007 @command{gcc}. You need to use quotes around @var{compiler_name} if
9008 @code{compiler_name} contains spaces or other separator characters.
9009 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9010 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9011 inserted after your command name. Thus in the above example the compiler
9012 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9013 A limitation of this syntax is that the name and path name of the executable
9014 itself must not include any embedded spaces. If the compiler executable is
9015 different from the default one (gcc or <prefix>-gcc), then the back-end
9016 switches in the ALI file are not used to compile the binder generated source.
9017 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9018 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9019 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9020 is taken into account. However, all the additional switches are also taken
9021 into account. Thus,
9022 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9023 @option{--GCC="bar -x -y -z -t"}.
9024
9025 @item --LINK=@var{name}
9026 @cindex @option{--LINK=} (@command{gnatlink})
9027 @var{name} is the name of the linker to be invoked. This is especially
9028 useful in mixed language programs since languages such as C++ require
9029 their own linker to be used. When this switch is omitted, the default
9030 name for the linker is @command{gcc}. When this switch is used, the
9031 specified linker is called instead of @command{gcc} with exactly the same
9032 parameters that would have been passed to @command{gcc} so if the desired
9033 linker requires different parameters it is necessary to use a wrapper
9034 script that massages the parameters before invoking the real linker. It
9035 may be useful to control the exact invocation by using the verbose
9036 switch.
9037
9038 @end ifclear
9039
9040 @ifset vms
9041 @item /DEBUG=TRACEBACK
9042 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9043 This qualifier causes sufficient information to be included in the
9044 executable file to allow a traceback, but does not include the full
9045 symbol information needed by the debugger.
9046
9047 @item /IDENTIFICATION="<string>"
9048 @code{"<string>"} specifies the string to be stored in the image file
9049 identification field in the image header.
9050 It overrides any pragma @code{Ident} specified string.
9051
9052 @item /NOINHIBIT-EXEC
9053 Generate the executable file even if there are linker warnings.
9054
9055 @item /NOSTART_FILES
9056 Don't link in the object file containing the ``main'' transfer address.
9057 Used when linking with a foreign language main program compiled with an
9058 HP compiler.
9059
9060 @item /STATIC
9061 Prefer linking with object libraries over sharable images, even without
9062 /DEBUG.
9063 @end ifset
9064
9065 @end table
9066
9067 @node The GNAT Make Program gnatmake
9068 @chapter The GNAT Make Program @command{gnatmake}
9069 @findex gnatmake
9070
9071 @menu
9072 * Running gnatmake::
9073 * Switches for gnatmake::
9074 * Mode Switches for gnatmake::
9075 * Notes on the Command Line::
9076 * How gnatmake Works::
9077 * Examples of gnatmake Usage::
9078 @end menu
9079 @noindent
9080 A typical development cycle when working on an Ada program consists of
9081 the following steps:
9082
9083 @enumerate
9084 @item
9085 Edit some sources to fix bugs.
9086
9087 @item
9088 Add enhancements.
9089
9090 @item
9091 Compile all sources affected.
9092
9093 @item
9094 Rebind and relink.
9095
9096 @item
9097 Test.
9098 @end enumerate
9099
9100 @noindent
9101 The third step can be tricky, because not only do the modified files
9102 @cindex Dependency rules
9103 have to be compiled, but any files depending on these files must also be
9104 recompiled. The dependency rules in Ada can be quite complex, especially
9105 in the presence of overloading, @code{use} clauses, generics and inlined
9106 subprograms.
9107
9108 @command{gnatmake} automatically takes care of the third and fourth steps
9109 of this process. It determines which sources need to be compiled,
9110 compiles them, and binds and links the resulting object files.
9111
9112 Unlike some other Ada make programs, the dependencies are always
9113 accurately recomputed from the new sources. The source based approach of
9114 the GNAT compilation model makes this possible. This means that if
9115 changes to the source program cause corresponding changes in
9116 dependencies, they will always be tracked exactly correctly by
9117 @command{gnatmake}.
9118
9119 @node Running gnatmake
9120 @section Running @command{gnatmake}
9121
9122 @noindent
9123 The usual form of the @command{gnatmake} command is
9124
9125 @smallexample
9126 $ gnatmake @ovar{switches} @var{file_name}
9127       @ovar{file_names} @ovar{mode_switches}
9128 @end smallexample
9129
9130 @noindent
9131 The only required argument is one @var{file_name}, which specifies
9132 a compilation unit that is a main program. Several @var{file_names} can be
9133 specified: this will result in several executables being built.
9134 If @code{switches} are present, they can be placed before the first
9135 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9136 If @var{mode_switches} are present, they must always be placed after
9137 the last @var{file_name} and all @code{switches}.
9138
9139 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9140 extension may be omitted from the @var{file_name} arguments. However, if
9141 you are using non-standard extensions, then it is required that the
9142 extension be given. A relative or absolute directory path can be
9143 specified in a @var{file_name}, in which case, the input source file will
9144 be searched for in the specified directory only. Otherwise, the input
9145 source file will first be searched in the directory where
9146 @command{gnatmake} was invoked and if it is not found, it will be search on
9147 the source path of the compiler as described in
9148 @ref{Search Paths and the Run-Time Library (RTL)}.
9149
9150 All @command{gnatmake} output (except when you specify
9151 @option{^-M^/DEPENDENCIES_LIST^}) is to
9152 @file{stderr}. The output produced by the
9153 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9154 @file{stdout}.
9155
9156 @node Switches for gnatmake
9157 @section Switches for @command{gnatmake}
9158
9159 @noindent
9160 You may specify any of the following switches to @command{gnatmake}:
9161
9162 @table @option
9163 @c !sort!
9164
9165 @item --version
9166 @cindex @option{--version} @command{gnatmake}
9167 Display Copyright and version, then exit disregarding all other options.
9168
9169 @item --help
9170 @cindex @option{--help} @command{gnatmake}
9171 If @option{--version} was not used, display usage, then exit disregarding
9172 all other options.
9173
9174 @ifclear vms
9175 @item --GCC=@var{compiler_name}
9176 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9177 Program used for compiling. The default is `@command{gcc}'. You need to use
9178 quotes around @var{compiler_name} if @code{compiler_name} contains
9179 spaces or other separator characters. As an example @option{--GCC="foo -x
9180 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9181 compiler. A limitation of this syntax is that the name and path name of
9182 the executable itself must not include any embedded spaces. Note that
9183 switch @option{-c} is always inserted after your command name. Thus in the
9184 above example the compiler command that will be used by @command{gnatmake}
9185 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9186 used, only the last @var{compiler_name} is taken into account. However,
9187 all the additional switches are also taken into account. Thus,
9188 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9189 @option{--GCC="bar -x -y -z -t"}.
9190
9191 @item --GNATBIND=@var{binder_name}
9192 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9193 Program used for binding. The default is `@code{gnatbind}'. You need to
9194 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9195 or other separator characters. As an example @option{--GNATBIND="bar -x
9196 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9197 binder. Binder switches that are normally appended by @command{gnatmake}
9198 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9199 A limitation of this syntax is that the name and path name of the executable
9200 itself must not include any embedded spaces.
9201
9202 @item --GNATLINK=@var{linker_name}
9203 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9204 Program used for linking. The default is `@command{gnatlink}'. You need to
9205 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9206 or other separator characters. As an example @option{--GNATLINK="lan -x
9207 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9208 linker. Linker switches that are normally appended by @command{gnatmake} to
9209 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9210 A limitation of this syntax is that the name and path name of the executable
9211 itself must not include any embedded spaces.
9212
9213 @end ifclear
9214
9215 @item ^-a^/ALL_FILES^
9216 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9217 Consider all files in the make process, even the GNAT internal system
9218 files (for example, the predefined Ada library files), as well as any
9219 locked files. Locked files are files whose ALI file is write-protected.
9220 By default,
9221 @command{gnatmake} does not check these files,
9222 because the assumption is that the GNAT internal files are properly up
9223 to date, and also that any write protected ALI files have been properly
9224 installed. Note that if there is an installation problem, such that one
9225 of these files is not up to date, it will be properly caught by the
9226 binder.
9227 You may have to specify this switch if you are working on GNAT
9228 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9229 in conjunction with @option{^-f^/FORCE_COMPILE^}
9230 if you need to recompile an entire application,
9231 including run-time files, using special configuration pragmas,
9232 such as a @code{Normalize_Scalars} pragma.
9233
9234 By default
9235 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9236 internal files with
9237 @ifclear vms
9238 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9239 @end ifclear
9240 @ifset vms
9241 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9242 @end ifset
9243
9244 @item ^-b^/ACTIONS=BIND^
9245 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9246 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9247 compilation and binding, but no link.
9248 Can be combined with @option{^-l^/ACTIONS=LINK^}
9249 to do binding and linking. When not combined with
9250 @option{^-c^/ACTIONS=COMPILE^}
9251 all the units in the closure of the main program must have been previously
9252 compiled and must be up to date. The root unit specified by @var{file_name}
9253 may be given without extension, with the source extension or, if no GNAT
9254 Project File is specified, with the ALI file extension.
9255
9256 @item ^-c^/ACTIONS=COMPILE^
9257 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9258 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9259 is also specified. Do not perform linking, except if both
9260 @option{^-b^/ACTIONS=BIND^} and
9261 @option{^-l^/ACTIONS=LINK^} are also specified.
9262 If the root unit specified by @var{file_name} is not a main unit, this is the
9263 default. Otherwise @command{gnatmake} will attempt binding and linking
9264 unless all objects are up to date and the executable is more recent than
9265 the objects.
9266
9267 @item ^-C^/MAPPING^
9268 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9269 Use a temporary mapping file. A mapping file is a way to communicate
9270 to the compiler two mappings: from unit names to file names (without
9271 any directory information) and from file names to path names (with
9272 full directory information). A mapping file can make the compiler's
9273 file searches faster, especially if there are many source directories,
9274 or the sources are read over a slow network connection. If
9275 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9276 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9277 is initially populated based on the project file. If
9278 @option{^-C^/MAPPING^} is used without
9279 @option{^-P^/PROJECT_FILE^},
9280 the mapping file is initially empty. Each invocation of the compiler
9281 will add any newly accessed sources to the mapping file.
9282
9283 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9284 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9285 Use a specific mapping file. The file, specified as a path name (absolute or
9286 relative) by this switch, should already exist, otherwise the switch is
9287 ineffective. The specified mapping file will be communicated to the compiler.
9288 This switch is not compatible with a project file
9289 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9290 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9291
9292 @item ^-d^/DISPLAY_PROGRESS^
9293 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9294 Display progress for each source, up to date or not, as a single line
9295
9296 @smallexample
9297 completed x out of y (zz%)
9298 @end smallexample
9299
9300 If the file needs to be compiled this is displayed after the invocation of
9301 the compiler. These lines are displayed even in quiet output mode.
9302
9303 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9304 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9305 Put all object files and ALI file in directory @var{dir}.
9306 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9307 and ALI files go in the current working directory.
9308
9309 This switch cannot be used when using a project file.
9310
9311 @ifclear vms
9312 @item -eL
9313 @cindex @option{-eL} (@command{gnatmake})
9314 Follow all symbolic links when processing project files.
9315 @end ifclear
9316
9317 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9318 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9319 Output the commands for the compiler, the binder and the linker
9320 on ^standard output^SYS$OUTPUT^,
9321 instead of ^standard error^SYS$ERROR^.
9322
9323 @item ^-f^/FORCE_COMPILE^
9324 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9325 Force recompilations. Recompile all sources, even though some object
9326 files may be up to date, but don't recompile predefined or GNAT internal
9327 files or locked files (files with a write-protected ALI file),
9328 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9329
9330 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9331 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9332 When using project files, if some errors or warnings are detected during
9333 parsing and verbose mode is not in effect (no use of switch
9334 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9335 file, rather than its simple file name.
9336
9337 @item ^-g^/DEBUG^
9338 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9339 Enable debugging. This switch is simply passed to the compiler and to the
9340 linker.
9341
9342 @item ^-i^/IN_PLACE^
9343 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9344 In normal mode, @command{gnatmake} compiles all object files and ALI files
9345 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9346 then instead object files and ALI files that already exist are overwritten
9347 in place. This means that once a large project is organized into separate
9348 directories in the desired manner, then @command{gnatmake} will automatically
9349 maintain and update this organization. If no ALI files are found on the
9350 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9351 the new object and ALI files are created in the
9352 directory containing the source being compiled. If another organization
9353 is desired, where objects and sources are kept in different directories,
9354 a useful technique is to create dummy ALI files in the desired directories.
9355 When detecting such a dummy file, @command{gnatmake} will be forced to
9356 recompile the corresponding source file, and it will be put the resulting
9357 object and ALI files in the directory where it found the dummy file.
9358
9359 @item ^-j^/PROCESSES=^@var{n}
9360 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9361 @cindex Parallel make
9362 Use @var{n} processes to carry out the (re)compilations. On a
9363 multiprocessor machine compilations will occur in parallel. In the
9364 event of compilation errors, messages from various compilations might
9365 get interspersed (but @command{gnatmake} will give you the full ordered
9366 list of failing compiles at the end). If this is problematic, rerun
9367 the make process with n set to 1 to get a clean list of messages.
9368
9369 @item ^-k^/CONTINUE_ON_ERROR^
9370 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9371 Keep going. Continue as much as possible after a compilation error. To
9372 ease the programmer's task in case of compilation errors, the list of
9373 sources for which the compile fails is given when @command{gnatmake}
9374 terminates.
9375
9376 If @command{gnatmake} is invoked with several @file{file_names} and with this
9377 switch, if there are compilation errors when building an executable,
9378 @command{gnatmake} will not attempt to build the following executables.
9379
9380 @item ^-l^/ACTIONS=LINK^
9381 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9382 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9383 and linking. Linking will not be performed if combined with
9384 @option{^-c^/ACTIONS=COMPILE^}
9385 but not with @option{^-b^/ACTIONS=BIND^}.
9386 When not combined with @option{^-b^/ACTIONS=BIND^}
9387 all the units in the closure of the main program must have been previously
9388 compiled and must be up to date, and the main program needs to have been bound.
9389 The root unit specified by @var{file_name}
9390 may be given without extension, with the source extension or, if no GNAT
9391 Project File is specified, with the ALI file extension.
9392
9393 @item ^-m^/MINIMAL_RECOMPILATION^
9394 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9395 Specify that the minimum necessary amount of recompilations
9396 be performed. In this mode @command{gnatmake} ignores time
9397 stamp differences when the only
9398 modifications to a source file consist in adding/removing comments,
9399 empty lines, spaces or tabs. This means that if you have changed the
9400 comments in a source file or have simply reformatted it, using this
9401 switch will tell @command{gnatmake} not to recompile files that depend on it
9402 (provided other sources on which these files depend have undergone no
9403 semantic modifications). Note that the debugging information may be
9404 out of date with respect to the sources if the @option{-m} switch causes
9405 a compilation to be switched, so the use of this switch represents a
9406 trade-off between compilation time and accurate debugging information.
9407
9408 @item ^-M^/DEPENDENCIES_LIST^
9409 @cindex Dependencies, producing list
9410 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9411 Check if all objects are up to date. If they are, output the object
9412 dependences to @file{stdout} in a form that can be directly exploited in
9413 a @file{Makefile}. By default, each source file is prefixed with its
9414 (relative or absolute) directory name. This name is whatever you
9415 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9416 and @option{^-I^/SEARCH^} switches. If you use
9417 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9418 @option{^-q^/QUIET^}
9419 (see below), only the source file names,
9420 without relative paths, are output. If you just specify the
9421 @option{^-M^/DEPENDENCIES_LIST^}
9422 switch, dependencies of the GNAT internal system files are omitted. This
9423 is typically what you want. If you also specify
9424 the @option{^-a^/ALL_FILES^} switch,
9425 dependencies of the GNAT internal files are also listed. Note that
9426 dependencies of the objects in external Ada libraries (see switch
9427 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9428 are never reported.
9429
9430 @item ^-n^/DO_OBJECT_CHECK^
9431 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9432 Don't compile, bind, or link. Checks if all objects are up to date.
9433 If they are not, the full name of the first file that needs to be
9434 recompiled is printed.
9435 Repeated use of this option, followed by compiling the indicated source
9436 file, will eventually result in recompiling all required units.
9437
9438 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9439 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9440 Output executable name. The name of the final executable program will be
9441 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9442 name for the executable will be the name of the input file in appropriate form
9443 for an executable file on the host system.
9444
9445 This switch cannot be used when invoking @command{gnatmake} with several
9446 @file{file_names}.
9447
9448 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9449 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9450 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9451 automatically missing object directories, library directories and exec
9452 directories.
9453
9454 @item ^-P^/PROJECT_FILE=^@var{project}
9455 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9456 Use project file @var{project}. Only one such switch can be used.
9457 @xref{gnatmake and Project Files}.
9458
9459 @item ^-q^/QUIET^
9460 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9461 Quiet. When this flag is not set, the commands carried out by
9462 @command{gnatmake} are displayed.
9463
9464 @item ^-s^/SWITCH_CHECK/^
9465 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9466 Recompile if compiler switches have changed since last compilation.
9467 All compiler switches but -I and -o are taken into account in the
9468 following way:
9469 orders between different ``first letter'' switches are ignored, but
9470 orders between same switches are taken into account. For example,
9471 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9472 is equivalent to @option{-O -g}.
9473
9474 This switch is recommended when Integrated Preprocessing is used.
9475
9476 @item ^-u^/UNIQUE^
9477 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9478 Unique. Recompile at most the main files. It implies -c. Combined with
9479 -f, it is equivalent to calling the compiler directly. Note that using
9480 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9481 (@pxref{Project Files and Main Subprograms}).
9482
9483 @item ^-U^/ALL_PROJECTS^
9484 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9485 When used without a project file or with one or several mains on the command
9486 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9487 on the command line, all sources of all project files are checked and compiled
9488 if not up to date, and libraries are rebuilt, if necessary.
9489
9490 @item ^-v^/REASONS^
9491 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9492 Verbose. Display the reason for all recompilations @command{gnatmake}
9493 decides are necessary, with the highest verbosity level.
9494
9495 @item ^-vl^/LOW_VERBOSITY^
9496 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9497 Verbosity level Low. Display fewer lines than in verbosity Medium.
9498
9499 @item ^-vm^/MEDIUM_VERBOSITY^
9500 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9501 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9502
9503 @item ^-vh^/HIGH_VERBOSITY^
9504 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9505 Verbosity level High. Equivalent to ^-v^/REASONS^.
9506
9507 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9508 Indicate the verbosity of the parsing of GNAT project files.
9509 @xref{Switches Related to Project Files}.
9510
9511 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9512 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9513 Indicate that sources that are not part of any Project File may be compiled.
9514 Normally, when using Project Files, only sources that are part of a Project
9515 File may be compile. When this switch is used, a source outside of all Project
9516 Files may be compiled. The ALI file and the object file will be put in the
9517 object directory of the main Project. The compilation switches used will only
9518 be those specified on the command line. Even when
9519 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9520 command line need to be sources of a project file.
9521
9522 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9523 Indicate that external variable @var{name} has the value @var{value}.
9524 The Project Manager will use this value for occurrences of
9525 @code{external(name)} when parsing the project file.
9526 @xref{Switches Related to Project Files}.
9527
9528 @item ^-z^/NOMAIN^
9529 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9530 No main subprogram. Bind and link the program even if the unit name
9531 given on the command line is a package name. The resulting executable
9532 will execute the elaboration routines of the package and its closure,
9533 then the finalization routines.
9534
9535 @end table
9536
9537 @table @asis
9538 @item @command{gcc} @asis{switches}
9539 @ifclear vms
9540 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9541 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9542 @end ifclear
9543 @ifset vms
9544 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9545 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9546 automatically treated as a compiler switch, and passed on to all
9547 compilations that are carried out.
9548 @end ifset
9549 @end table
9550
9551 @noindent
9552 Source and library search path switches:
9553
9554 @table @option
9555 @c !sort!
9556 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9557 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9558 When looking for source files also look in directory @var{dir}.
9559 The order in which source files search is undertaken is
9560 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9561
9562 @item ^-aL^/SKIP_MISSING=^@var{dir}
9563 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9564 Consider @var{dir} as being an externally provided Ada library.
9565 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9566 files have been located in directory @var{dir}. This allows you to have
9567 missing bodies for the units in @var{dir} and to ignore out of date bodies
9568 for the same units. You still need to specify
9569 the location of the specs for these units by using the switches
9570 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9571 or @option{^-I^/SEARCH=^@var{dir}}.
9572 Note: this switch is provided for compatibility with previous versions
9573 of @command{gnatmake}. The easier method of causing standard libraries
9574 to be excluded from consideration is to write-protect the corresponding
9575 ALI files.
9576
9577 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9578 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9579 When searching for library and object files, look in directory
9580 @var{dir}. The order in which library files are searched is described in
9581 @ref{Search Paths for gnatbind}.
9582
9583 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9584 @cindex Search paths, for @command{gnatmake}
9585 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9586 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9587 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9588
9589 @item ^-I^/SEARCH=^@var{dir}
9590 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9591 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9592 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9593
9594 @item ^-I-^/NOCURRENT_DIRECTORY^
9595 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9596 @cindex Source files, suppressing search
9597 Do not look for source files in the directory containing the source
9598 file named in the command line.
9599 Do not look for ALI or object files in the directory
9600 where @command{gnatmake} was invoked.
9601
9602 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9603 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9604 @cindex Linker libraries
9605 Add directory @var{dir} to the list of directories in which the linker
9606 will search for libraries. This is equivalent to
9607 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9608 @ifclear vms
9609 Furthermore, under Windows, the sources pointed to by the libraries path
9610 set in the registry are not searched for.
9611 @end ifclear
9612
9613 @item -nostdinc
9614 @cindex @option{-nostdinc} (@command{gnatmake})
9615 Do not look for source files in the system default directory.
9616
9617 @item -nostdlib
9618 @cindex @option{-nostdlib} (@command{gnatmake})
9619 Do not look for library files in the system default directory.
9620
9621 @item --RTS=@var{rts-path}
9622 @cindex @option{--RTS} (@command{gnatmake})
9623 Specifies the default location of the runtime library. GNAT looks for the
9624 runtime
9625 in the following directories, and stops as soon as a valid runtime is found
9626 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9627 @file{ada_object_path} present):
9628
9629 @itemize @bullet
9630 @item <current directory>/$rts_path
9631
9632 @item <default-search-dir>/$rts_path
9633
9634 @item <default-search-dir>/rts-$rts_path
9635 @end itemize
9636
9637 @noindent
9638 The selected path is handled like a normal RTS path.
9639
9640 @end table
9641
9642 @node Mode Switches for gnatmake
9643 @section Mode Switches for @command{gnatmake}
9644
9645 @noindent
9646 The mode switches (referred to as @code{mode_switches}) allow the
9647 inclusion of switches that are to be passed to the compiler itself, the
9648 binder or the linker. The effect of a mode switch is to cause all
9649 subsequent switches up to the end of the switch list, or up to the next
9650 mode switch, to be interpreted as switches to be passed on to the
9651 designated component of GNAT.
9652
9653 @table @option
9654 @c !sort!
9655 @item -cargs @var{switches}
9656 @cindex @option{-cargs} (@command{gnatmake})
9657 Compiler switches. Here @var{switches} is a list of switches
9658 that are valid switches for @command{gcc}. They will be passed on to
9659 all compile steps performed by @command{gnatmake}.
9660
9661 @item -bargs @var{switches}
9662 @cindex @option{-bargs} (@command{gnatmake})
9663 Binder switches. Here @var{switches} is a list of switches
9664 that are valid switches for @code{gnatbind}. They will be passed on to
9665 all bind steps performed by @command{gnatmake}.
9666
9667 @item -largs @var{switches}
9668 @cindex @option{-largs} (@command{gnatmake})
9669 Linker switches. Here @var{switches} is a list of switches
9670 that are valid switches for @command{gnatlink}. They will be passed on to
9671 all link steps performed by @command{gnatmake}.
9672
9673 @item -margs @var{switches}
9674 @cindex @option{-margs} (@command{gnatmake})
9675 Make switches. The switches are directly interpreted by @command{gnatmake},
9676 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9677 or @option{-largs}.
9678 @end table
9679
9680 @node Notes on the Command Line
9681 @section Notes on the Command Line
9682
9683 @noindent
9684 This section contains some additional useful notes on the operation
9685 of the @command{gnatmake} command.
9686
9687 @itemize @bullet
9688 @item
9689 @cindex Recompilation, by @command{gnatmake}
9690 If @command{gnatmake} finds no ALI files, it recompiles the main program
9691 and all other units required by the main program.
9692 This means that @command{gnatmake}
9693 can be used for the initial compile, as well as during subsequent steps of
9694 the development cycle.
9695
9696 @item
9697 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9698 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9699 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9700 warning.
9701
9702 @item
9703 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9704 is used to specify both source and
9705 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9706 instead if you just want to specify
9707 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9708 if you want to specify library paths
9709 only.
9710
9711 @item
9712 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9713 This may conveniently be used to exclude standard libraries from
9714 consideration and in particular it means that the use of the
9715 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9716 unless @option{^-a^/ALL_FILES^} is also specified.
9717
9718 @item
9719 @command{gnatmake} has been designed to make the use of Ada libraries
9720 particularly convenient. Assume you have an Ada library organized
9721 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9722 of your Ada compilation units,
9723 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9724 specs of these units, but no bodies. Then to compile a unit
9725 stored in @code{main.adb}, which uses this Ada library you would just type
9726
9727 @smallexample
9728 @ifclear vms
9729 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9730 @end ifclear
9731 @ifset vms
9732 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9733            /SKIP_MISSING=@i{[OBJ_DIR]} main
9734 @end ifset
9735 @end smallexample
9736
9737 @item
9738 Using @command{gnatmake} along with the
9739 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9740 switch provides a mechanism for avoiding unnecessary recompilations. Using
9741 this switch,
9742 you can update the comments/format of your
9743 source files without having to recompile everything. Note, however, that
9744 adding or deleting lines in a source files may render its debugging
9745 info obsolete. If the file in question is a spec, the impact is rather
9746 limited, as that debugging info will only be useful during the
9747 elaboration phase of your program. For bodies the impact can be more
9748 significant. In all events, your debugger will warn you if a source file
9749 is more recent than the corresponding object, and alert you to the fact
9750 that the debugging information may be out of date.
9751 @end itemize
9752
9753 @node How gnatmake Works
9754 @section How @command{gnatmake} Works
9755
9756 @noindent
9757 Generally @command{gnatmake} automatically performs all necessary
9758 recompilations and you don't need to worry about how it works. However,
9759 it may be useful to have some basic understanding of the @command{gnatmake}
9760 approach and in particular to understand how it uses the results of
9761 previous compilations without incorrectly depending on them.
9762
9763 First a definition: an object file is considered @dfn{up to date} if the
9764 corresponding ALI file exists and if all the source files listed in the
9765 dependency section of this ALI file have time stamps matching those in
9766 the ALI file. This means that neither the source file itself nor any
9767 files that it depends on have been modified, and hence there is no need
9768 to recompile this file.
9769
9770 @command{gnatmake} works by first checking if the specified main unit is up
9771 to date. If so, no compilations are required for the main unit. If not,
9772 @command{gnatmake} compiles the main program to build a new ALI file that
9773 reflects the latest sources. Then the ALI file of the main unit is
9774 examined to find all the source files on which the main program depends,
9775 and @command{gnatmake} recursively applies the above procedure on all these
9776 files.
9777
9778 This process ensures that @command{gnatmake} only trusts the dependencies
9779 in an existing ALI file if they are known to be correct. Otherwise it
9780 always recompiles to determine a new, guaranteed accurate set of
9781 dependencies. As a result the program is compiled ``upside down'' from what may
9782 be more familiar as the required order of compilation in some other Ada
9783 systems. In particular, clients are compiled before the units on which
9784 they depend. The ability of GNAT to compile in any order is critical in
9785 allowing an order of compilation to be chosen that guarantees that
9786 @command{gnatmake} will recompute a correct set of new dependencies if
9787 necessary.
9788
9789 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9790 imported by several of the executables, it will be recompiled at most once.
9791
9792 Note: when using non-standard naming conventions
9793 (@pxref{Using Other File Names}), changing through a configuration pragmas
9794 file the version of a source and invoking @command{gnatmake} to recompile may
9795 have no effect, if the previous version of the source is still accessible
9796 by @command{gnatmake}. It may be necessary to use the switch
9797 ^-f^/FORCE_COMPILE^.
9798
9799 @node Examples of gnatmake Usage
9800 @section Examples of @command{gnatmake} Usage
9801
9802 @table @code
9803 @item gnatmake hello.adb
9804 Compile all files necessary to bind and link the main program
9805 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9806 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9807
9808 @item gnatmake main1 main2 main3
9809 Compile all files necessary to bind and link the main programs
9810 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9811 (containing unit @code{Main2}) and @file{main3.adb}
9812 (containing unit @code{Main3}) and bind and link the resulting object files
9813 to generate three executable files @file{^main1^MAIN1.EXE^},
9814 @file{^main2^MAIN2.EXE^}
9815 and @file{^main3^MAIN3.EXE^}.
9816
9817 @ifclear vms
9818 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9819 @end ifclear
9820
9821 @ifset vms
9822 @item gnatmake Main_Unit /QUIET
9823 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9824 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9825 @end ifset
9826 Compile all files necessary to bind and link the main program unit
9827 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9828 be done with optimization level 2 and the order of elaboration will be
9829 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9830 displaying commands it is executing.
9831 @end table
9832
9833 @c *************************
9834 @node Improving Performance
9835 @chapter Improving Performance
9836 @cindex Improving performance
9837
9838 @noindent
9839 This chapter presents several topics related to program performance.
9840 It first describes some of the tradeoffs that need to be considered
9841 and some of the techniques for making your program run faster.
9842 It then documents the @command{gnatelim} tool and unused subprogram/data
9843 elimination feature, which can reduce the size of program executables.
9844
9845 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9846 driver (see @ref{The GNAT Driver and Project Files}).
9847
9848 @ifnottex
9849 @menu
9850 * Performance Considerations::
9851 * Text_IO Suggestions::
9852 * Reducing Size of Ada Executables with gnatelim::
9853 * Reducing Size of Executables with unused subprogram/data elimination::
9854 @end menu
9855 @end ifnottex
9856
9857 @c *****************************
9858 @node Performance Considerations
9859 @section Performance Considerations
9860
9861 @noindent
9862 The GNAT system provides a number of options that allow a trade-off
9863 between
9864
9865 @itemize @bullet
9866 @item
9867 performance of the generated code
9868
9869 @item
9870 speed of compilation
9871
9872 @item
9873 minimization of dependences and recompilation
9874
9875 @item
9876 the degree of run-time checking.
9877 @end itemize
9878
9879 @noindent
9880 The defaults (if no options are selected) aim at improving the speed
9881 of compilation and minimizing dependences, at the expense of performance
9882 of the generated code:
9883
9884 @itemize @bullet
9885 @item
9886 no optimization
9887
9888 @item
9889 no inlining of subprogram calls
9890
9891 @item
9892 all run-time checks enabled except overflow and elaboration checks
9893 @end itemize
9894
9895 @noindent
9896 These options are suitable for most program development purposes. This
9897 chapter describes how you can modify these choices, and also provides
9898 some guidelines on debugging optimized code.
9899
9900 @menu
9901 * Controlling Run-Time Checks::
9902 * Use of Restrictions::
9903 * Optimization Levels::
9904 * Debugging Optimized Code::
9905 * Inlining of Subprograms::
9906 * Other Optimization Switches::
9907 * Optimization and Strict Aliasing::
9908
9909 @ifset vms
9910 * Coverage Analysis::
9911 @end ifset
9912 @end menu
9913
9914 @node Controlling Run-Time Checks
9915 @subsection Controlling Run-Time Checks
9916
9917 @noindent
9918 By default, GNAT generates all run-time checks, except integer overflow
9919 checks, stack overflow checks, and checks for access before elaboration on
9920 subprogram calls. The latter are not required in default mode, because all
9921 necessary checking is done at compile time.
9922 @cindex @option{-gnatp} (@command{gcc})
9923 @cindex @option{-gnato} (@command{gcc})
9924 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9925 be modified. @xref{Run-Time Checks}.
9926
9927 Our experience is that the default is suitable for most development
9928 purposes.
9929
9930 We treat integer overflow specially because these
9931 are quite expensive and in our experience are not as important as other
9932 run-time checks in the development process. Note that division by zero
9933 is not considered an overflow check, and divide by zero checks are
9934 generated where required by default.
9935
9936 Elaboration checks are off by default, and also not needed by default, since
9937 GNAT uses a static elaboration analysis approach that avoids the need for
9938 run-time checking. This manual contains a full chapter discussing the issue
9939 of elaboration checks, and if the default is not satisfactory for your use,
9940 you should read this chapter.
9941
9942 For validity checks, the minimal checks required by the Ada Reference
9943 Manual (for case statements and assignments to array elements) are on
9944 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9945 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9946 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9947 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9948 are also suppressed entirely if @option{-gnatp} is used.
9949
9950 @cindex Overflow checks
9951 @cindex Checks, overflow
9952 @findex Suppress
9953 @findex Unsuppress
9954 @cindex pragma Suppress
9955 @cindex pragma Unsuppress
9956 Note that the setting of the switches controls the default setting of
9957 the checks. They may be modified using either @code{pragma Suppress} (to
9958 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9959 checks) in the program source.
9960
9961 @node Use of Restrictions
9962 @subsection Use of Restrictions
9963
9964 @noindent
9965 The use of pragma Restrictions allows you to control which features are
9966 permitted in your program. Apart from the obvious point that if you avoid
9967 relatively expensive features like finalization (enforceable by the use
9968 of pragma Restrictions (No_Finalization), the use of this pragma does not
9969 affect the generated code in most cases.
9970
9971 One notable exception to this rule is that the possibility of task abort
9972 results in some distributed overhead, particularly if finalization or
9973 exception handlers are used. The reason is that certain sections of code
9974 have to be marked as non-abortable.
9975
9976 If you use neither the @code{abort} statement, nor asynchronous transfer
9977 of control (@code{select @dots{} then abort}), then this distributed overhead
9978 is removed, which may have a general positive effect in improving
9979 overall performance.  Especially code involving frequent use of tasking
9980 constructs and controlled types will show much improved performance.
9981 The relevant restrictions pragmas are
9982
9983 @smallexample @c ada
9984    pragma Restrictions (No_Abort_Statements);
9985    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9986 @end smallexample
9987
9988 @noindent
9989 It is recommended that these restriction pragmas be used if possible. Note
9990 that this also means that you can write code without worrying about the
9991 possibility of an immediate abort at any point.
9992
9993 @node Optimization Levels
9994 @subsection Optimization Levels
9995 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9996
9997 @noindent
9998 Without any optimization ^option,^qualifier,^
9999 the compiler's goal is to reduce the cost of
10000 compilation and to make debugging produce the expected results.
10001 Statements are independent: if you stop the program with a breakpoint between
10002 statements, you can then assign a new value to any variable or change
10003 the program counter to any other statement in the subprogram and get exactly
10004 the results you would expect from the source code.
10005
10006 Turning on optimization makes the compiler attempt to improve the
10007 performance and/or code size at the expense of compilation time and
10008 possibly the ability to debug the program.
10009
10010 If you use multiple
10011 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10012 the last such option is the one that is effective.
10013
10014 @noindent
10015 The default is optimization off. This results in the fastest compile
10016 times, but GNAT makes absolutely no attempt to optimize, and the
10017 generated programs are considerably larger and slower than when
10018 optimization is enabled. You can use the
10019 @ifclear vms
10020 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10021 @option{-O2}, @option{-O3}, and @option{-Os})
10022 @end ifclear
10023 @ifset vms
10024 @code{OPTIMIZE} qualifier
10025 @end ifset
10026 to @command{gcc} to control the optimization level:
10027
10028 @table @option
10029 @item ^-O0^/OPTIMIZE=NONE^
10030 No optimization (the default);
10031 generates unoptimized code but has
10032 the fastest compilation time.
10033
10034 Note that many other compilers do fairly extensive optimization
10035 even if ``no optimization'' is specified. With gcc, it is
10036 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10037 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10038 really does mean no optimization at all. This difference between
10039 gcc and other compilers should be kept in mind when doing
10040 performance comparisons.
10041
10042 @item ^-O1^/OPTIMIZE=SOME^
10043 Moderate optimization;
10044 optimizes reasonably well but does not
10045 degrade compilation time significantly.
10046
10047 @item ^-O2^/OPTIMIZE=ALL^
10048 @ifset vms
10049 @itemx /OPTIMIZE=DEVELOPMENT
10050 @end ifset
10051 Full optimization;
10052 generates highly optimized code and has
10053 the slowest compilation time.
10054
10055 @item ^-O3^/OPTIMIZE=INLINING^
10056 Full optimization as in @option{-O2},
10057 and also attempts automatic inlining of small
10058 subprograms within a unit (@pxref{Inlining of Subprograms}).
10059
10060 @item ^-Os^/OPTIMIZE=SPACE^
10061 Optimize space usage of resulting program.
10062 @end table
10063
10064 @noindent
10065 Higher optimization levels perform more global transformations on the
10066 program and apply more expensive analysis algorithms in order to generate
10067 faster and more compact code. The price in compilation time, and the
10068 resulting improvement in execution time,
10069 both depend on the particular application and the hardware environment.
10070 You should experiment to find the best level for your application.
10071
10072 Since the precise set of optimizations done at each level will vary from
10073 release to release (and sometime from target to target), it is best to think
10074 of the optimization settings in general terms.
10075 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10076 the GNU Compiler Collection (GCC)}, for details about
10077 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10078 individually enable or disable specific optimizations.
10079
10080 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10081 been tested extensively at all optimization levels. There are some bugs
10082 which appear only with optimization turned on, but there have also been
10083 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10084 level of optimization does not improve the reliability of the code
10085 generator, which in practice is highly reliable at all optimization
10086 levels.
10087
10088 Note regarding the use of @option{-O3}: The use of this optimization level
10089 is generally discouraged with GNAT, since it often results in larger
10090 executables which run more slowly. See further discussion of this point
10091 in @ref{Inlining of Subprograms}.
10092
10093 @node Debugging Optimized Code
10094 @subsection Debugging Optimized Code
10095 @cindex Debugging optimized code
10096 @cindex Optimization and debugging
10097
10098 @noindent
10099 Although it is possible to do a reasonable amount of debugging at
10100 @ifclear vms
10101 nonzero optimization levels,
10102 the higher the level the more likely that
10103 @end ifclear
10104 @ifset vms
10105 @option{/OPTIMIZE} settings other than @code{NONE},
10106 such settings will make it more likely that
10107 @end ifset
10108 source-level constructs will have been eliminated by optimization.
10109 For example, if a loop is strength-reduced, the loop
10110 control variable may be completely eliminated and thus cannot be
10111 displayed in the debugger.
10112 This can only happen at @option{-O2} or @option{-O3}.
10113 Explicit temporary variables that you code might be eliminated at
10114 ^level^setting^ @option{-O1} or higher.
10115
10116 The use of the @option{^-g^/DEBUG^} switch,
10117 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10118 which is needed for source-level debugging,
10119 affects the size of the program executable on disk,
10120 and indeed the debugging information can be quite large.
10121 However, it has no effect on the generated code (and thus does not
10122 degrade performance)
10123
10124 Since the compiler generates debugging tables for a compilation unit before
10125 it performs optimizations, the optimizing transformations may invalidate some
10126 of the debugging data.  You therefore need to anticipate certain
10127 anomalous situations that may arise while debugging optimized code.
10128 These are the most common cases:
10129
10130 @enumerate
10131 @item
10132 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10133 commands show
10134 the PC bouncing back and forth in the code.  This may result from any of
10135 the following optimizations:
10136
10137 @itemize @bullet
10138 @item
10139 @i{Common subexpression elimination:} using a single instance of code for a
10140 quantity that the source computes several times.  As a result you
10141 may not be able to stop on what looks like a statement.
10142
10143 @item
10144 @i{Invariant code motion:} moving an expression that does not change within a
10145 loop, to the beginning of the loop.
10146
10147 @item
10148 @i{Instruction scheduling:} moving instructions so as to
10149 overlap loads and stores (typically) with other code, or in
10150 general to move computations of values closer to their uses. Often
10151 this causes you to pass an assignment statement without the assignment
10152 happening and then later bounce back to the statement when the
10153 value is actually needed.  Placing a breakpoint on a line of code
10154 and then stepping over it may, therefore, not always cause all the
10155 expected side-effects.
10156 @end itemize
10157
10158 @item
10159 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10160 two identical pieces of code are merged and the program counter suddenly
10161 jumps to a statement that is not supposed to be executed, simply because
10162 it (and the code following) translates to the same thing as the code
10163 that @emph{was} supposed to be executed.  This effect is typically seen in
10164 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10165 a @code{break} in a C @code{^switch^switch^} statement.
10166
10167 @item
10168 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10169 There are various reasons for this effect:
10170
10171 @itemize @bullet
10172 @item
10173 In a subprogram prologue, a parameter may not yet have been moved to its
10174 ``home''.
10175
10176 @item
10177 A variable may be dead, and its register re-used.  This is
10178 probably the most common cause.
10179
10180 @item
10181 As mentioned above, the assignment of a value to a variable may
10182 have been moved.
10183
10184 @item
10185 A variable may be eliminated entirely by value propagation or
10186 other means.  In this case, GCC may incorrectly generate debugging
10187 information for the variable
10188 @end itemize
10189
10190 @noindent
10191 In general, when an unexpected value appears for a local variable or parameter
10192 you should first ascertain if that value was actually computed by
10193 your program, as opposed to being incorrectly reported by the debugger.
10194 Record fields or
10195 array elements in an object designated by an access value
10196 are generally less of a problem, once you have ascertained that the access
10197 value is sensible.
10198 Typically, this means checking variables in the preceding code and in the
10199 calling subprogram to verify that the value observed is explainable from other
10200 values (one must apply the procedure recursively to those
10201 other values); or re-running the code and stopping a little earlier
10202 (perhaps before the call) and stepping to better see how the variable obtained
10203 the value in question; or continuing to step @emph{from} the point of the
10204 strange value to see if code motion had simply moved the variable's
10205 assignments later.
10206 @end enumerate
10207
10208 @noindent
10209 In light of such anomalies, a recommended technique is to use @option{-O0}
10210 early in the software development cycle, when extensive debugging capabilities
10211 are most needed, and then move to @option{-O1} and later @option{-O2} as
10212 the debugger becomes less critical.
10213 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10214 a release management issue.
10215 @ifclear vms
10216 Note that if you use @option{-g} you can then use the @command{strip} program
10217 on the resulting executable,
10218 which removes both debugging information and global symbols.
10219 @end ifclear
10220
10221 @node Inlining of Subprograms
10222 @subsection Inlining of Subprograms
10223
10224 @noindent
10225 A call to a subprogram in the current unit is inlined if all the
10226 following conditions are met:
10227
10228 @itemize @bullet
10229 @item
10230 The optimization level is at least @option{-O1}.
10231
10232 @item
10233 The called subprogram is suitable for inlining: It must be small enough
10234 and not contain something that @command{gcc} cannot support in inlined
10235 subprograms.
10236
10237 @item
10238 @cindex pragma Inline
10239 @findex Inline
10240 Either @code{pragma Inline} applies to the subprogram, or it is local
10241 to the unit and called once from within it, or it is small and automatic
10242 inlining (optimization level @option{-O3}) is specified.
10243 @end itemize
10244
10245 @noindent
10246 Calls to subprograms in @code{with}'ed units are normally not inlined.
10247 To achieve actual inlining (that is, replacement of the call by the code
10248 in the body of the subprogram), the following conditions must all be true.
10249
10250 @itemize @bullet
10251 @item
10252 The optimization level is at least @option{-O1}.
10253
10254 @item
10255 The called subprogram is suitable for inlining: It must be small enough
10256 and not contain something that @command{gcc} cannot support in inlined
10257 subprograms.
10258
10259 @item
10260 The call appears in a body (not in a package spec).
10261
10262 @item
10263 There is a @code{pragma Inline} for the subprogram.
10264
10265 @item
10266 @cindex @option{-gnatn} (@command{gcc})
10267 The @option{^-gnatn^/INLINE^} switch
10268 is used in the @command{gcc} command line
10269 @end itemize
10270
10271 Even if all these conditions are met, it may not be possible for
10272 the compiler to inline the call, due to the length of the body,
10273 or features in the body that make it impossible for the compiler
10274 to do the inlining.
10275
10276 Note that specifying the @option{-gnatn} switch causes additional
10277 compilation dependencies. Consider the following:
10278
10279 @smallexample @c ada
10280 @cartouche
10281 package R is
10282    procedure Q;
10283    pragma Inline (Q);
10284 end R;
10285 package body R is
10286    @dots{}
10287 end R;
10288
10289 with R;
10290 procedure Main is
10291 begin
10292    @dots{}
10293    R.Q;
10294 end Main;
10295 @end cartouche
10296 @end smallexample
10297
10298 @noindent
10299 With the default behavior (no @option{-gnatn} switch specified), the
10300 compilation of the @code{Main} procedure depends only on its own source,
10301 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10302 means that editing the body of @code{R} does not require recompiling
10303 @code{Main}.
10304
10305 On the other hand, the call @code{R.Q} is not inlined under these
10306 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10307 is compiled, the call will be inlined if the body of @code{Q} is small
10308 enough, but now @code{Main} depends on the body of @code{R} in
10309 @file{r.adb} as well as on the spec. This means that if this body is edited,
10310 the main program must be recompiled. Note that this extra dependency
10311 occurs whether or not the call is in fact inlined by @command{gcc}.
10312
10313 The use of front end inlining with @option{-gnatN} generates similar
10314 additional dependencies.
10315
10316 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10317 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10318 can be used to prevent
10319 all inlining. This switch overrides all other conditions and ensures
10320 that no inlining occurs. The extra dependences resulting from
10321 @option{-gnatn} will still be active, even if
10322 this switch is used to suppress the resulting inlining actions.
10323
10324 @cindex @option{-fno-inline-functions} (@command{gcc})
10325 Note: The @option{-fno-inline-functions} switch can be used to prevent
10326 automatic inlining of small subprograms if @option{-O3} is used.
10327
10328 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10329 Note: The @option{-fno-inline-functions-called-once} switch
10330 can be used to prevent inlining of subprograms local to the unit
10331 and called once from within it if @option{-O1} is used.
10332
10333 Note regarding the use of @option{-O3}: There is no difference in inlining
10334 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10335 pragma @code{Inline} assuming the use of @option{-gnatn}
10336 or @option{-gnatN} (the switches that activate inlining). If you have used
10337 pragma @code{Inline} in appropriate cases, then it is usually much better
10338 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10339 in this case only has the effect of inlining subprograms you did not
10340 think should be inlined. We often find that the use of @option{-O3} slows
10341 down code by performing excessive inlining, leading to increased instruction
10342 cache pressure from the increased code size. So the bottom line here is
10343 that you should not automatically assume that @option{-O3} is better than
10344 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10345 it actually improves performance.
10346
10347 @node Other Optimization Switches
10348 @subsection Other Optimization Switches
10349 @cindex Optimization Switches
10350
10351 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10352 @command{gcc} optimization switches are potentially usable. These switches
10353 have not been extensively tested with GNAT but can generally be expected
10354 to work. Examples of switches in this category are
10355 @option{-funroll-loops} and
10356 the various target-specific @option{-m} options (in particular, it has been
10357 observed that @option{-march=pentium4} can significantly improve performance
10358 on appropriate machines). For full details of these switches, see
10359 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10360 the GNU Compiler Collection (GCC)}.
10361
10362 @node Optimization and Strict Aliasing
10363 @subsection Optimization and Strict Aliasing
10364 @cindex Aliasing
10365 @cindex Strict Aliasing
10366 @cindex No_Strict_Aliasing
10367
10368 @noindent
10369 The strong typing capabilities of Ada allow an optimizer to generate
10370 efficient code in situations where other languages would be forced to
10371 make worst case assumptions preventing such optimizations. Consider
10372 the following example:
10373
10374 @smallexample @c ada
10375 @cartouche
10376 procedure R is
10377    type Int1 is new Integer;
10378    type Int2 is new Integer;
10379    type Int1A is access Int1;
10380    type Int2A is access Int2;
10381    Int1V : Int1A;
10382    Int2V : Int2A;
10383    @dots{}
10384
10385 begin
10386    @dots{}
10387    for J in Data'Range loop
10388       if Data (J) = Int1V.all then
10389          Int2V.all := Int2V.all + 1;
10390       end if;
10391    end loop;
10392    @dots{}
10393 end R;
10394 @end cartouche
10395 @end smallexample
10396
10397 @noindent
10398 In this example, since the variable @code{Int1V} can only access objects
10399 of type @code{Int1}, and @code{Int2V} can only access objects of type
10400 @code{Int2}, there is no possibility that the assignment to
10401 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10402 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10403 for all iterations of the loop and avoid the extra memory reference
10404 required to dereference it each time through the loop.
10405
10406 This kind of optimization, called strict aliasing analysis, is
10407 triggered by specifying an optimization level of @option{-O2} or
10408 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10409 when access values are involved.
10410
10411 However, although this optimization is always correct in terms of
10412 the formal semantics of the Ada Reference Manual, difficulties can
10413 arise if features like @code{Unchecked_Conversion} are used to break
10414 the typing system. Consider the following complete program example:
10415
10416 @smallexample @c ada
10417 @cartouche
10418 package p1 is
10419    type int1 is new integer;
10420    type int2 is new integer;
10421    type a1 is access int1;
10422    type a2 is access int2;
10423 end p1;
10424
10425 with p1; use p1;
10426 package p2 is
10427    function to_a2 (Input : a1) return a2;
10428 end p2;
10429
10430 with Unchecked_Conversion;
10431 package body p2 is
10432    function to_a2 (Input : a1) return a2 is
10433       function to_a2u is
10434         new Unchecked_Conversion (a1, a2);
10435    begin
10436       return to_a2u (Input);
10437    end to_a2;
10438 end p2;
10439
10440 with p2; use p2;
10441 with p1; use p1;
10442 with Text_IO; use Text_IO;
10443 procedure m is
10444    v1 : a1 := new int1;
10445    v2 : a2 := to_a2 (v1);
10446 begin
10447    v1.all := 1;
10448    v2.all := 0;
10449    put_line (int1'image (v1.all));
10450 end;
10451 @end cartouche
10452 @end smallexample
10453
10454 @noindent
10455 This program prints out 0 in @option{-O0} or @option{-O1}
10456 mode, but it prints out 1 in @option{-O2} mode. That's
10457 because in strict aliasing mode, the compiler can and
10458 does assume that the assignment to @code{v2.all} could not
10459 affect the value of @code{v1.all}, since different types
10460 are involved.
10461
10462 This behavior is not a case of non-conformance with the standard, since
10463 the Ada RM specifies that an unchecked conversion where the resulting
10464 bit pattern is not a correct value of the target type can result in an
10465 abnormal value and attempting to reference an abnormal value makes the
10466 execution of a program erroneous.  That's the case here since the result
10467 does not point to an object of type @code{int2}.  This means that the
10468 effect is entirely unpredictable.
10469
10470 However, although that explanation may satisfy a language
10471 lawyer, in practice an applications programmer expects an
10472 unchecked conversion involving pointers to create true
10473 aliases and the behavior of printing 1 seems plain wrong.
10474 In this case, the strict aliasing optimization is unwelcome.
10475
10476 Indeed the compiler recognizes this possibility, and the
10477 unchecked conversion generates a warning:
10478
10479 @smallexample
10480 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10481 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10482 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10483 @end smallexample
10484
10485 @noindent
10486 Unfortunately the problem is recognized when compiling the body of
10487 package @code{p2}, but the actual "bad" code is generated while
10488 compiling the body of @code{m} and this latter compilation does not see
10489 the suspicious @code{Unchecked_Conversion}.
10490
10491 As implied by the warning message, there are approaches you can use to
10492 avoid the unwanted strict aliasing optimization in a case like this.
10493
10494 One possibility is to simply avoid the use of @option{-O2}, but
10495 that is a bit drastic, since it throws away a number of useful
10496 optimizations that do not involve strict aliasing assumptions.
10497
10498 A less drastic approach is to compile the program using the
10499 option @option{-fno-strict-aliasing}. Actually it is only the
10500 unit containing the dereferencing of the suspicious pointer
10501 that needs to be compiled. So in this case, if we compile
10502 unit @code{m} with this switch, then we get the expected
10503 value of zero printed. Analyzing which units might need
10504 the switch can be painful, so a more reasonable approach
10505 is to compile the entire program with options @option{-O2}
10506 and @option{-fno-strict-aliasing}. If the performance is
10507 satisfactory with this combination of options, then the
10508 advantage is that the entire issue of possible "wrong"
10509 optimization due to strict aliasing is avoided.
10510
10511 To avoid the use of compiler switches, the configuration
10512 pragma @code{No_Strict_Aliasing} with no parameters may be
10513 used to specify that for all access types, the strict
10514 aliasing optimization should be suppressed.
10515
10516 However, these approaches are still overkill, in that they causes
10517 all manipulations of all access values to be deoptimized. A more
10518 refined approach is to concentrate attention on the specific
10519 access type identified as problematic.
10520
10521 First, if a careful analysis of uses of the pointer shows
10522 that there are no possible problematic references, then
10523 the warning can be suppressed by bracketing the
10524 instantiation of @code{Unchecked_Conversion} to turn
10525 the warning off:
10526
10527 @smallexample @c ada
10528    pragma Warnings (Off);
10529    function to_a2u is
10530      new Unchecked_Conversion (a1, a2);
10531    pragma Warnings (On);
10532 @end smallexample
10533
10534 @noindent
10535 Of course that approach is not appropriate for this particular
10536 example, since indeed there is a problematic reference. In this
10537 case we can take one of two other approaches.
10538
10539 The first possibility is to move the instantiation of unchecked
10540 conversion to the unit in which the type is declared. In
10541 this example, we would move the instantiation of
10542 @code{Unchecked_Conversion} from the body of package
10543 @code{p2} to the spec of package @code{p1}. Now the
10544 warning disappears. That's because any use of the
10545 access type knows there is a suspicious unchecked
10546 conversion, and the strict aliasing optimization
10547 is automatically suppressed for the type.
10548
10549 If it is not practical to move the unchecked conversion to the same unit
10550 in which the destination access type is declared (perhaps because the
10551 source type is not visible in that unit), you may use pragma
10552 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10553 same declarative sequence as the declaration of the access type:
10554
10555 @smallexample @c ada
10556    type a2 is access int2;
10557    pragma No_Strict_Aliasing (a2);
10558 @end smallexample
10559
10560 @noindent
10561 Here again, the compiler now knows that the strict aliasing optimization
10562 should be suppressed for any reference to type @code{a2} and the
10563 expected behavior is obtained.
10564
10565 Finally, note that although the compiler can generate warnings for
10566 simple cases of unchecked conversions, there are tricker and more
10567 indirect ways of creating type incorrect aliases which the compiler
10568 cannot detect. Examples are the use of address overlays and unchecked
10569 conversions involving composite types containing access types as
10570 components. In such cases, no warnings are generated, but there can
10571 still be aliasing problems. One safe coding practice is to forbid the
10572 use of address clauses for type overlaying, and to allow unchecked
10573 conversion only for primitive types. This is not really a significant
10574 restriction since any possible desired effect can be achieved by
10575 unchecked conversion of access values.
10576
10577 The aliasing analysis done in strict aliasing mode can certainly
10578 have significant benefits. We have seen cases of large scale
10579 application code where the time is increased by up to 5% by turning
10580 this optimization off. If you have code that includes significant
10581 usage of unchecked conversion, you might want to just stick with
10582 @option{-O1} and avoid the entire issue. If you get adequate
10583 performance at this level of optimization level, that's probably
10584 the safest approach. If tests show that you really need higher
10585 levels of optimization, then you can experiment with @option{-O2}
10586 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10587 has on size and speed of the code. If you really need to use
10588 @option{-O2} with strict aliasing in effect, then you should
10589 review any uses of unchecked conversion of access types,
10590 particularly if you are getting the warnings described above.
10591
10592 @ifset vms
10593 @node Coverage Analysis
10594 @subsection Coverage Analysis
10595
10596 @noindent
10597 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10598 the user to determine the distribution of execution time across a program,
10599 @pxref{Profiling} for details of usage.
10600 @end ifset
10601
10602
10603 @node Text_IO Suggestions
10604 @section @code{Text_IO} Suggestions
10605 @cindex @code{Text_IO} and performance
10606
10607 @noindent
10608 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10609 the requirement of maintaining page and line counts. If performance
10610 is critical, a recommendation is to use @code{Stream_IO} instead of
10611 @code{Text_IO} for volume output, since this package has less overhead.
10612
10613 If @code{Text_IO} must be used, note that by default output to the standard
10614 output and standard error files is unbuffered (this provides better
10615 behavior when output statements are used for debugging, or if the
10616 progress of a program is observed by tracking the output, e.g. by
10617 using the Unix @command{tail -f} command to watch redirected output.
10618
10619 If you are generating large volumes of output with @code{Text_IO} and
10620 performance is an important factor, use a designated file instead
10621 of the standard output file, or change the standard output file to
10622 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10623
10624
10625
10626 @node Reducing Size of Ada Executables with gnatelim
10627 @section Reducing Size of Ada Executables with @code{gnatelim}
10628 @findex gnatelim
10629
10630 @noindent
10631 This section describes @command{gnatelim}, a tool which detects unused
10632 subprograms and helps the compiler to create a smaller executable for your
10633 program.
10634
10635 @menu
10636 * About gnatelim::
10637 * Running gnatelim::
10638 * Correcting the List of Eliminate Pragmas::
10639 * Making Your Executables Smaller::
10640 * Summary of the gnatelim Usage Cycle::
10641 @end menu
10642
10643 @node About gnatelim
10644 @subsection About @code{gnatelim}
10645
10646 @noindent
10647 When a program shares a set of Ada
10648 packages with other programs, it may happen that this program uses
10649 only a fraction of the subprograms defined in these packages. The code
10650 created for these unused subprograms increases the size of the executable.
10651
10652 @code{gnatelim} tracks unused subprograms in an Ada program and
10653 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10654 subprograms that are declared but never called. By placing the list of
10655 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10656 recompiling your program, you may decrease the size of its executable,
10657 because the compiler will not generate the code for 'eliminated' subprograms.
10658 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10659 information about this pragma.
10660
10661 @code{gnatelim} needs as its input data the name of the main subprogram
10662 and a bind file for a main subprogram.
10663
10664 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10665 the main subprogram. @code{gnatelim} can work with both Ada and C
10666 bind files; when both are present, it uses the Ada bind file.
10667 The following commands will build the program and create the bind file:
10668
10669 @smallexample
10670 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10671 $ gnatbind main_prog
10672 @end smallexample
10673
10674 Note that @code{gnatelim} needs neither object nor ALI files.
10675
10676 @node Running gnatelim
10677 @subsection Running @code{gnatelim}
10678
10679 @noindent
10680 @code{gnatelim} has the following command-line interface:
10681
10682 @smallexample
10683 $ gnatelim @ovar{options} name
10684 @end smallexample
10685
10686 @noindent
10687 @code{name} should be a name of a source file that contains the main subprogram
10688 of a program (partition).
10689
10690 @code{gnatelim} has the following switches:
10691
10692 @table @option
10693 @c !sort!
10694 @item ^-q^/QUIET^
10695 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10696 Quiet mode: by default @code{gnatelim} outputs to the standard error
10697 stream the number of program units left to be processed. This option turns
10698 this trace off.
10699
10700 @item ^-v^/VERBOSE^
10701 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10702 Verbose mode: @code{gnatelim} version information is printed as Ada
10703 comments to the standard output stream. Also, in addition to the number of
10704 program units left @code{gnatelim} will output the name of the current unit
10705 being processed.
10706
10707 @item ^-a^/ALL^
10708 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10709 Also look for subprograms from the GNAT run time that can be eliminated. Note
10710 that when @file{gnat.adc} is produced using this switch, the entire program
10711 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10712
10713 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10714 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10715 When looking for source files also look in directory @var{dir}. Specifying
10716 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10717 sources in the current directory.
10718
10719 @item ^-b^/BIND_FILE=^@var{bind_file}
10720 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10721 Specifies @var{bind_file} as the bind file to process. If not set, the name
10722 of the bind file is computed from the full expanded Ada name
10723 of a main subprogram.
10724
10725 @item ^-C^/CONFIG_FILE=^@var{config_file}
10726 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10727 Specifies a file @var{config_file} that contains configuration pragmas. The
10728 file must be specified with full path.
10729
10730 @item ^--GCC^/COMPILER^=@var{compiler_name}
10731 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10732 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10733 available on the path.
10734
10735 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10736 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10737 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10738 available on the path.
10739 @end table
10740
10741 @noindent
10742 @code{gnatelim} sends its output to the standard output stream, and all the
10743 tracing and debug information is sent to the standard error stream.
10744 In order to produce a proper GNAT configuration file
10745 @file{gnat.adc}, redirection must be used:
10746
10747 @smallexample
10748 @ifset vms
10749 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10750 @end ifset
10751 @ifclear vms
10752 $ gnatelim main_prog.adb > gnat.adc
10753 @end ifclear
10754 @end smallexample
10755
10756 @ifclear vms
10757 @noindent
10758 or
10759
10760 @smallexample
10761 $ gnatelim main_prog.adb >> gnat.adc
10762 @end smallexample
10763
10764 @noindent
10765 in order to append the @code{gnatelim} output to the existing contents of
10766 @file{gnat.adc}.
10767 @end ifclear
10768
10769 @node Correcting the List of Eliminate Pragmas
10770 @subsection Correcting the List of Eliminate Pragmas
10771
10772 @noindent
10773 In some rare cases @code{gnatelim} may try to eliminate
10774 subprograms that are actually called in the program. In this case, the
10775 compiler will generate an error message of the form:
10776
10777 @smallexample
10778 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10779 @end smallexample
10780
10781 @noindent
10782 You will need to manually remove the wrong @code{Eliminate} pragmas from
10783 the @file{gnat.adc} file. You should recompile your program
10784 from scratch after that, because you need a consistent @file{gnat.adc} file
10785 during the entire compilation.
10786
10787 @node Making Your Executables Smaller
10788 @subsection Making Your Executables Smaller
10789
10790 @noindent
10791 In order to get a smaller executable for your program you now have to
10792 recompile the program completely with the new @file{gnat.adc} file
10793 created by @code{gnatelim} in your current directory:
10794
10795 @smallexample
10796 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10797 @end smallexample
10798
10799 @noindent
10800 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10801 recompile everything
10802 with the set of pragmas @code{Eliminate} that you have obtained with
10803 @command{gnatelim}).
10804
10805 Be aware that the set of @code{Eliminate} pragmas is specific to each
10806 program. It is not recommended to merge sets of @code{Eliminate}
10807 pragmas created for different programs in one @file{gnat.adc} file.
10808
10809 @node Summary of the gnatelim Usage Cycle
10810 @subsection Summary of the gnatelim Usage Cycle
10811
10812 @noindent
10813 Here is a quick summary of the steps to be taken in order to reduce
10814 the size of your executables with @code{gnatelim}. You may use
10815 other GNAT options to control the optimization level,
10816 to produce the debugging information, to set search path, etc.
10817
10818 @enumerate
10819 @item
10820 Produce a bind file
10821
10822 @smallexample
10823 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10824 $ gnatbind main_prog
10825 @end smallexample
10826
10827 @item
10828 Generate a list of @code{Eliminate} pragmas
10829 @smallexample
10830 @ifset vms
10831 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10832 @end ifset
10833 @ifclear vms
10834 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10835 @end ifclear
10836 @end smallexample
10837
10838 @item
10839 Recompile the application
10840
10841 @smallexample
10842 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10843 @end smallexample
10844
10845 @end enumerate
10846
10847 @node Reducing Size of Executables with unused subprogram/data elimination
10848 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10849 @findex unused subprogram/data elimination
10850
10851 @noindent
10852 This section describes how you can eliminate unused subprograms and data from
10853 your executable just by setting options at compilation time.
10854
10855 @menu
10856 * About unused subprogram/data elimination::
10857 * Compilation options::
10858 * Example of unused subprogram/data elimination::
10859 @end menu
10860
10861 @node About unused subprogram/data elimination
10862 @subsection About unused subprogram/data elimination
10863
10864 @noindent
10865 By default, an executable contains all code and data of its composing objects
10866 (directly linked or coming from statically linked libraries), even data or code
10867 never used by this executable.
10868
10869 This feature will allow you to eliminate such unused code from your
10870 executable, making it smaller (in disk and in memory).
10871
10872 This functionality is available on all Linux platforms except for the IA-64
10873 architecture and on all cross platforms using the ELF binary file format.
10874 In both cases GNU binutils version 2.16 or later are required to enable it.
10875
10876 @node Compilation options
10877 @subsection Compilation options
10878
10879 @noindent
10880 The operation of eliminating the unused code and data from the final executable
10881 is directly performed by the linker.
10882
10883 In order to do this, it has to work with objects compiled with the
10884 following options:
10885 @option{-ffunction-sections} @option{-fdata-sections}.
10886 @cindex @option{-ffunction-sections} (@command{gcc})
10887 @cindex @option{-fdata-sections} (@command{gcc})
10888 These options are usable with C and Ada files.
10889 They will place respectively each
10890 function or data in a separate section in the resulting object file.
10891
10892 Once the objects and static libraries are created with these options, the
10893 linker can perform the dead code elimination. You can do this by setting
10894 the @option{-Wl,--gc-sections} option to gcc command or in the
10895 @option{-largs} section of @command{gnatmake}. This will perform a
10896 garbage collection of code and data never referenced.
10897
10898 If the linker performs a partial link (@option{-r} ld linker option), then you
10899 will need to provide one or several entry point using the
10900 @option{-e} / @option{--entry} ld option.
10901
10902 Note that objects compiled without the @option{-ffunction-sections} and
10903 @option{-fdata-sections} options can still be linked with the executable.
10904 However, no dead code elimination will be performed on those objects (they will
10905 be linked as is).
10906
10907 The GNAT static library is now compiled with -ffunction-sections and
10908 -fdata-sections on some platforms. This allows you to eliminate the unused code
10909 and data of the GNAT library from your executable.
10910
10911 @node Example of unused subprogram/data elimination
10912 @subsection Example of unused subprogram/data elimination
10913
10914 @noindent
10915 Here is a simple example:
10916
10917 @smallexample @c ada
10918 with Aux;
10919
10920 procedure Test is
10921 begin
10922    Aux.Used (10);
10923 end Test;
10924
10925 package Aux is
10926    Used_Data   : Integer;
10927    Unused_Data : Integer;
10928
10929    procedure Used   (Data : Integer);
10930    procedure Unused (Data : Integer);
10931 end Aux;
10932
10933 package body Aux is
10934    procedure Used (Data : Integer) is
10935    begin
10936       Used_Data := Data;
10937    end Used;
10938
10939    procedure Unused (Data : Integer) is
10940    begin
10941       Unused_Data := Data;
10942    end Unused;
10943 end Aux;
10944 @end smallexample
10945
10946 @noindent
10947 @code{Unused} and @code{Unused_Data} are never referenced in this code
10948 excerpt, and hence they may be safely removed from the final executable.
10949
10950 @smallexample
10951 $ gnatmake test
10952
10953 $ nm test | grep used
10954 020015f0 T aux__unused
10955 02005d88 B aux__unused_data
10956 020015cc T aux__used
10957 02005d84 B aux__used_data
10958
10959 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10960      -largs -Wl,--gc-sections
10961
10962 $ nm test | grep used
10963 02005350 T aux__used
10964 0201ffe0 B aux__used_data
10965 @end smallexample
10966
10967 @noindent
10968 It can be observed that the procedure @code{Unused} and the object
10969 @code{Unused_Data} are removed by the linker when using the
10970 appropriate options.
10971
10972 @c ********************************
10973 @node Renaming Files Using gnatchop
10974 @chapter Renaming Files Using @code{gnatchop}
10975 @findex gnatchop
10976
10977 @noindent
10978 This chapter discusses how to handle files with multiple units by using
10979 the @code{gnatchop} utility. This utility is also useful in renaming
10980 files to meet the standard GNAT default file naming conventions.
10981
10982 @menu
10983 * Handling Files with Multiple Units::
10984 * Operating gnatchop in Compilation Mode::
10985 * Command Line for gnatchop::
10986 * Switches for gnatchop::
10987 * Examples of gnatchop Usage::
10988 @end menu
10989
10990 @node Handling Files with Multiple Units
10991 @section Handling Files with Multiple Units
10992
10993 @noindent
10994 The basic compilation model of GNAT requires that a file submitted to the
10995 compiler have only one unit and there be a strict correspondence
10996 between the file name and the unit name.
10997
10998 The @code{gnatchop} utility allows both of these rules to be relaxed,
10999 allowing GNAT to process files which contain multiple compilation units
11000 and files with arbitrary file names. @code{gnatchop}
11001 reads the specified file and generates one or more output files,
11002 containing one unit per file. The unit and the file name correspond,
11003 as required by GNAT.
11004
11005 If you want to permanently restructure a set of ``foreign'' files so that
11006 they match the GNAT rules, and do the remaining development using the
11007 GNAT structure, you can simply use @command{gnatchop} once, generate the
11008 new set of files and work with them from that point on.
11009
11010 Alternatively, if you want to keep your files in the ``foreign'' format,
11011 perhaps to maintain compatibility with some other Ada compilation
11012 system, you can set up a procedure where you use @command{gnatchop} each
11013 time you compile, regarding the source files that it writes as temporary
11014 files that you throw away.
11015
11016 Note that if your file containing multiple units starts with a byte order
11017 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11018 will each start with a copy of this BOM, meaning that they can be compiled
11019 automatically in UTF-8 mode without needing to specify an explicit encoding.
11020
11021 @node Operating gnatchop in Compilation Mode
11022 @section Operating gnatchop in Compilation Mode
11023
11024 @noindent
11025 The basic function of @code{gnatchop} is to take a file with multiple units
11026 and split it into separate files. The boundary between files is reasonably
11027 clear, except for the issue of comments and pragmas. In default mode, the
11028 rule is that any pragmas between units belong to the previous unit, except
11029 that configuration pragmas always belong to the following unit. Any comments
11030 belong to the following unit. These rules
11031 almost always result in the right choice of
11032 the split point without needing to mark it explicitly and most users will
11033 find this default to be what they want. In this default mode it is incorrect to
11034 submit a file containing only configuration pragmas, or one that ends in
11035 configuration pragmas, to @code{gnatchop}.
11036
11037 However, using a special option to activate ``compilation mode'',
11038 @code{gnatchop}
11039 can perform another function, which is to provide exactly the semantics
11040 required by the RM for handling of configuration pragmas in a compilation.
11041 In the absence of configuration pragmas (at the main file level), this
11042 option has no effect, but it causes such configuration pragmas to be handled
11043 in a quite different manner.
11044
11045 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11046 only configuration pragmas, then this file is appended to the
11047 @file{gnat.adc} file in the current directory. This behavior provides
11048 the required behavior described in the RM for the actions to be taken
11049 on submitting such a file to the compiler, namely that these pragmas
11050 should apply to all subsequent compilations in the same compilation
11051 environment. Using GNAT, the current directory, possibly containing a
11052 @file{gnat.adc} file is the representation
11053 of a compilation environment. For more information on the
11054 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11055
11056 Second, in compilation mode, if @code{gnatchop}
11057 is given a file that starts with
11058 configuration pragmas, and contains one or more units, then these
11059 configuration pragmas are prepended to each of the chopped files. This
11060 behavior provides the required behavior described in the RM for the
11061 actions to be taken on compiling such a file, namely that the pragmas
11062 apply to all units in the compilation, but not to subsequently compiled
11063 units.
11064
11065 Finally, if configuration pragmas appear between units, they are appended
11066 to the previous unit. This results in the previous unit being illegal,
11067 since the compiler does not accept configuration pragmas that follow
11068 a unit. This provides the required RM behavior that forbids configuration
11069 pragmas other than those preceding the first compilation unit of a
11070 compilation.
11071
11072 For most purposes, @code{gnatchop} will be used in default mode. The
11073 compilation mode described above is used only if you need exactly
11074 accurate behavior with respect to compilations, and you have files
11075 that contain multiple units and configuration pragmas. In this
11076 circumstance the use of @code{gnatchop} with the compilation mode
11077 switch provides the required behavior, and is for example the mode
11078 in which GNAT processes the ACVC tests.
11079
11080 @node Command Line for gnatchop
11081 @section Command Line for @code{gnatchop}
11082
11083 @noindent
11084 The @code{gnatchop} command has the form:
11085
11086 @smallexample
11087 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11088       @ovar{directory}
11089 @end smallexample
11090
11091 @noindent
11092 The only required argument is the file name of the file to be chopped.
11093 There are no restrictions on the form of this file name. The file itself
11094 contains one or more Ada units, in normal GNAT format, concatenated
11095 together. As shown, more than one file may be presented to be chopped.
11096
11097 When run in default mode, @code{gnatchop} generates one output file in
11098 the current directory for each unit in each of the files.
11099
11100 @var{directory}, if specified, gives the name of the directory to which
11101 the output files will be written. If it is not specified, all files are
11102 written to the current directory.
11103
11104 For example, given a
11105 file called @file{hellofiles} containing
11106
11107 @smallexample @c ada
11108 @group
11109 @cartouche
11110 procedure hello;
11111
11112 with Text_IO; use Text_IO;
11113 procedure hello is
11114 begin
11115    Put_Line ("Hello");
11116 end hello;
11117 @end cartouche
11118 @end group
11119 @end smallexample
11120
11121 @noindent
11122 the command
11123
11124 @smallexample
11125 $ gnatchop ^hellofiles^HELLOFILES.^
11126 @end smallexample
11127
11128 @noindent
11129 generates two files in the current directory, one called
11130 @file{hello.ads} containing the single line that is the procedure spec,
11131 and the other called @file{hello.adb} containing the remaining text. The
11132 original file is not affected. The generated files can be compiled in
11133 the normal manner.
11134
11135 @noindent
11136 When gnatchop is invoked on a file that is empty or that contains only empty
11137 lines and/or comments, gnatchop will not fail, but will not produce any
11138 new sources.
11139
11140 For example, given a
11141 file called @file{toto.txt} containing
11142
11143 @smallexample @c ada
11144 @group
11145 @cartouche
11146 --  Just a comment
11147 @end cartouche
11148 @end group
11149 @end smallexample
11150
11151 @noindent
11152 the command
11153
11154 @smallexample
11155 $ gnatchop ^toto.txt^TOT.TXT^
11156 @end smallexample
11157
11158 @noindent
11159 will not produce any new file and will result in the following warnings:
11160
11161 @smallexample
11162 toto.txt:1:01: warning: empty file, contains no compilation units
11163 no compilation units found
11164 no source files written
11165 @end smallexample
11166
11167 @node Switches for gnatchop
11168 @section Switches for @code{gnatchop}
11169
11170 @noindent
11171 @command{gnatchop} recognizes the following switches:
11172
11173 @table @option
11174 @c !sort!
11175
11176 @item --version
11177 @cindex @option{--version} @command{gnatchop}
11178 Display Copyright and version, then exit disregarding all other options.
11179
11180 @item --help
11181 @cindex @option{--help} @command{gnatchop}
11182 If @option{--version} was not used, display usage, then exit disregarding
11183 all other options.
11184
11185 @item ^-c^/COMPILATION^
11186 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11187 Causes @code{gnatchop} to operate in compilation mode, in which
11188 configuration pragmas are handled according to strict RM rules. See
11189 previous section for a full description of this mode.
11190
11191 @ifclear vms
11192 @item -gnat@var{xxx}
11193 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11194 used to parse the given file. Not all @var{xxx} options make sense,
11195 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11196 process a source file that uses Latin-2 coding for identifiers.
11197 @end ifclear
11198
11199 @item ^-h^/HELP^
11200 Causes @code{gnatchop} to generate a brief help summary to the standard
11201 output file showing usage information.
11202
11203 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11204 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11205 Limit generated file names to the specified number @code{mm}
11206 of characters.
11207 This is useful if the
11208 resulting set of files is required to be interoperable with systems
11209 which limit the length of file names.
11210 @ifset vms
11211 If no value is given, or
11212 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11213 a default of 39, suitable for OpenVMS Alpha
11214 Systems, is assumed
11215 @end ifset
11216 @ifclear vms
11217 No space is allowed between the @option{-k} and the numeric value. The numeric
11218 value may be omitted in which case a default of @option{-k8},
11219 suitable for use
11220 with DOS-like file systems, is used. If no @option{-k} switch
11221 is present then
11222 there is no limit on the length of file names.
11223 @end ifclear
11224
11225 @item ^-p^/PRESERVE^
11226 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11227 Causes the file ^modification^creation^ time stamp of the input file to be
11228 preserved and used for the time stamp of the output file(s). This may be
11229 useful for preserving coherency of time stamps in an environment where
11230 @code{gnatchop} is used as part of a standard build process.
11231
11232 @item ^-q^/QUIET^
11233 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11234 Causes output of informational messages indicating the set of generated
11235 files to be suppressed. Warnings and error messages are unaffected.
11236
11237 @item ^-r^/REFERENCE^
11238 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11239 @findex Source_Reference
11240 Generate @code{Source_Reference} pragmas. Use this switch if the output
11241 files are regarded as temporary and development is to be done in terms
11242 of the original unchopped file. This switch causes
11243 @code{Source_Reference} pragmas to be inserted into each of the
11244 generated files to refers back to the original file name and line number.
11245 The result is that all error messages refer back to the original
11246 unchopped file.
11247 In addition, the debugging information placed into the object file (when
11248 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11249 specified)
11250 also refers back to this original file so that tools like profilers and
11251 debuggers will give information in terms of the original unchopped file.
11252
11253 If the original file to be chopped itself contains
11254 a @code{Source_Reference}
11255 pragma referencing a third file, then gnatchop respects
11256 this pragma, and the generated @code{Source_Reference} pragmas
11257 in the chopped file refer to the original file, with appropriate
11258 line numbers. This is particularly useful when @code{gnatchop}
11259 is used in conjunction with @code{gnatprep} to compile files that
11260 contain preprocessing statements and multiple units.
11261
11262 @item ^-v^/VERBOSE^
11263 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11264 Causes @code{gnatchop} to operate in verbose mode. The version
11265 number and copyright notice are output, as well as exact copies of
11266 the gnat1 commands spawned to obtain the chop control information.
11267
11268 @item ^-w^/OVERWRITE^
11269 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11270 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11271 fatal error if there is already a file with the same name as a
11272 file it would otherwise output, in other words if the files to be
11273 chopped contain duplicated units. This switch bypasses this
11274 check, and causes all but the last instance of such duplicated
11275 units to be skipped.
11276
11277 @ifclear vms
11278 @item --GCC=@var{xxxx}
11279 @cindex @option{--GCC=} (@code{gnatchop})
11280 Specify the path of the GNAT parser to be used. When this switch is used,
11281 no attempt is made to add the prefix to the GNAT parser executable.
11282 @end ifclear
11283 @end table
11284
11285 @node Examples of gnatchop Usage
11286 @section Examples of @code{gnatchop} Usage
11287
11288 @table @code
11289 @ifset vms
11290 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11291 @end ifset
11292 @ifclear vms
11293 @item gnatchop -w hello_s.ada prerelease/files
11294 @end ifclear
11295
11296 Chops the source file @file{hello_s.ada}. The output files will be
11297 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11298 overwriting any
11299 files with matching names in that directory (no files in the current
11300 directory are modified).
11301
11302 @item gnatchop ^archive^ARCHIVE.^
11303 Chops the source file @file{^archive^ARCHIVE.^}
11304 into the current directory. One
11305 useful application of @code{gnatchop} is in sending sets of sources
11306 around, for example in email messages. The required sources are simply
11307 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11308 command), and then
11309 @command{gnatchop} is used at the other end to reconstitute the original
11310 file names.
11311
11312 @item gnatchop file1 file2 file3 direc
11313 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11314 the resulting files in the directory @file{direc}. Note that if any units
11315 occur more than once anywhere within this set of files, an error message
11316 is generated, and no files are written. To override this check, use the
11317 @option{^-w^/OVERWRITE^} switch,
11318 in which case the last occurrence in the last file will
11319 be the one that is output, and earlier duplicate occurrences for a given
11320 unit will be skipped.
11321 @end table
11322
11323 @node Configuration Pragmas
11324 @chapter Configuration Pragmas
11325 @cindex Configuration pragmas
11326 @cindex Pragmas, configuration
11327
11328 @noindent
11329 Configuration pragmas include those pragmas described as
11330 such in the Ada Reference Manual, as well as
11331 implementation-dependent pragmas that are configuration pragmas.
11332 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11333 for details on these additional GNAT-specific configuration pragmas.
11334 Most notably, the pragma @code{Source_File_Name}, which allows
11335 specifying non-default names for source files, is a configuration
11336 pragma. The following is a complete list of configuration pragmas
11337 recognized by GNAT:
11338
11339 @smallexample
11340    Ada_83
11341    Ada_95
11342    Ada_05
11343    Ada_2005
11344    Assertion_Policy
11345    Assume_No_Invalid_Values
11346    C_Pass_By_Copy
11347    Check_Name
11348    Check_Policy
11349    Compile_Time_Error
11350    Compile_Time_Warning
11351    Compiler_Unit
11352    Component_Alignment
11353    Convention_Identifier
11354    Debug_Policy
11355    Detect_Blocking
11356    Discard_Names
11357    Elaboration_Checks
11358    Eliminate
11359    Extend_System
11360    Extensions_Allowed
11361    External_Name_Casing
11362    Fast_Math
11363    Favor_Top_Level
11364    Float_Representation
11365    Implicit_Packing
11366    Initialize_Scalars
11367    Interrupt_State
11368    License
11369    Locking_Policy
11370    Long_Float
11371    No_Run_Time
11372    No_Strict_Aliasing
11373    Normalize_Scalars
11374    Optimize_Alignment
11375    Persistent_BSS
11376    Polling
11377    Priority_Specific_Dispatching
11378    Profile
11379    Profile_Warnings
11380    Propagate_Exceptions
11381    Queuing_Policy
11382    Ravenscar
11383    Restricted_Run_Time
11384    Restrictions
11385    Restrictions_Warnings
11386    Reviewable
11387    Source_File_Name
11388    Source_File_Name_Project
11389    Style_Checks
11390    Suppress
11391    Suppress_Exception_Locations
11392    Task_Dispatching_Policy
11393    Universal_Data
11394    Unsuppress
11395    Use_VADS_Size
11396    Validity_Checks
11397    Warnings
11398    Wide_Character_Encoding
11399
11400 @end smallexample
11401
11402 @menu
11403 * Handling of Configuration Pragmas::
11404 * The Configuration Pragmas Files::
11405 @end menu
11406
11407 @node Handling of Configuration Pragmas
11408 @section Handling of Configuration Pragmas
11409
11410 Configuration pragmas may either appear at the start of a compilation
11411 unit, in which case they apply only to that unit, or they may apply to
11412 all compilations performed in a given compilation environment.
11413
11414 GNAT also provides the @code{gnatchop} utility to provide an automatic
11415 way to handle configuration pragmas following the semantics for
11416 compilations (that is, files with multiple units), described in the RM.
11417 See @ref{Operating gnatchop in Compilation Mode} for details.
11418 However, for most purposes, it will be more convenient to edit the
11419 @file{gnat.adc} file that contains configuration pragmas directly,
11420 as described in the following section.
11421
11422 @node The Configuration Pragmas Files
11423 @section The Configuration Pragmas Files
11424 @cindex @file{gnat.adc}
11425
11426 @noindent
11427 In GNAT a compilation environment is defined by the current
11428 directory at the time that a compile command is given. This current
11429 directory is searched for a file whose name is @file{gnat.adc}. If
11430 this file is present, it is expected to contain one or more
11431 configuration pragmas that will be applied to the current compilation.
11432 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11433 considered.
11434
11435 Configuration pragmas may be entered into the @file{gnat.adc} file
11436 either by running @code{gnatchop} on a source file that consists only of
11437 configuration pragmas, or more conveniently  by
11438 direct editing of the @file{gnat.adc} file, which is a standard format
11439 source file.
11440
11441 In addition to @file{gnat.adc}, additional files containing configuration
11442 pragmas may be applied to the current compilation using the switch
11443 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11444 contains only configuration pragmas. These configuration pragmas are
11445 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11446 is present and switch @option{-gnatA} is not used).
11447
11448 It is allowed to specify several switches @option{-gnatec}, all of which
11449 will be taken into account.
11450
11451 If you are using project file, a separate mechanism is provided using
11452 project attributes, see @ref{Specifying Configuration Pragmas} for more
11453 details.
11454
11455 @ifset vms
11456 Of special interest to GNAT OpenVMS Alpha is the following
11457 configuration pragma:
11458
11459 @smallexample @c ada
11460 @cartouche
11461 pragma Extend_System (Aux_DEC);
11462 @end cartouche
11463 @end smallexample
11464
11465 @noindent
11466 In the presence of this pragma, GNAT adds to the definition of the
11467 predefined package SYSTEM all the additional types and subprograms that are
11468 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11469 @end ifset
11470
11471 @node Handling Arbitrary File Naming Conventions Using gnatname
11472 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11473 @cindex Arbitrary File Naming Conventions
11474
11475 @menu
11476 * Arbitrary File Naming Conventions::
11477 * Running gnatname::
11478 * Switches for gnatname::
11479 * Examples of gnatname Usage::
11480 @end menu
11481
11482 @node Arbitrary File Naming Conventions
11483 @section Arbitrary File Naming Conventions
11484
11485 @noindent
11486 The GNAT compiler must be able to know the source file name of a compilation
11487 unit.  When using the standard GNAT default file naming conventions
11488 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11489 does not need additional information.
11490
11491 @noindent
11492 When the source file names do not follow the standard GNAT default file naming
11493 conventions, the GNAT compiler must be given additional information through
11494 a configuration pragmas file (@pxref{Configuration Pragmas})
11495 or a project file.
11496 When the non-standard file naming conventions are well-defined,
11497 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11498 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11499 if the file naming conventions are irregular or arbitrary, a number
11500 of pragma @code{Source_File_Name} for individual compilation units
11501 must be defined.
11502 To help maintain the correspondence between compilation unit names and
11503 source file names within the compiler,
11504 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11505 set of files.
11506
11507 @node Running gnatname
11508 @section Running @code{gnatname}
11509
11510 @noindent
11511 The usual form of the @code{gnatname} command is
11512
11513 @smallexample
11514 $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11515       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11516 @end smallexample
11517
11518 @noindent
11519 All of the arguments are optional. If invoked without any argument,
11520 @code{gnatname} will display its usage.
11521
11522 @noindent
11523 When used with at least one naming pattern, @code{gnatname} will attempt to
11524 find all the compilation units in files that follow at least one of the
11525 naming patterns. To find these compilation units,
11526 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11527 regular files.
11528
11529 @noindent
11530 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11531 Each Naming Pattern is enclosed between double quotes.
11532 A Naming Pattern is a regular expression similar to the wildcard patterns
11533 used in file names by the Unix shells or the DOS prompt.
11534
11535 @noindent
11536 @code{gnatname} may be called with several sections of directories/patterns.
11537 Sections are separated by switch @code{--and}. In each section, there must be
11538 at least one pattern. If no directory is specified in a section, the current
11539 directory (or the project directory is @code{-P} is used) is implied.
11540 The options other that the directory switches and the patterns apply globally
11541 even if they are in different sections.
11542
11543 @noindent
11544 Examples of Naming Patterns are
11545
11546 @smallexample
11547    "*.[12].ada"
11548    "*.ad[sb]*"
11549    "body_*"    "spec_*"
11550 @end smallexample
11551
11552 @noindent
11553 For a more complete description of the syntax of Naming Patterns,
11554 see the second kind of regular expressions described in @file{g-regexp.ads}
11555 (the ``Glob'' regular expressions).
11556
11557 @noindent
11558 When invoked with no switch @code{-P}, @code{gnatname} will create a
11559 configuration pragmas file @file{gnat.adc} in the current working directory,
11560 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11561 unit.
11562
11563 @node Switches for gnatname
11564 @section Switches for @code{gnatname}
11565
11566 @noindent
11567 Switches for @code{gnatname} must precede any specified Naming Pattern.
11568
11569 @noindent
11570 You may specify any of the following switches to @code{gnatname}:
11571
11572 @table @option
11573 @c !sort!
11574
11575 @item --version
11576 @cindex @option{--version} @command{gnatname}
11577 Display Copyright and version, then exit disregarding all other options.
11578
11579 @item --help
11580 @cindex @option{--help} @command{gnatname}
11581 If @option{--version} was not used, display usage, then exit disregarding
11582 all other options.
11583
11584 @item --and
11585 Start another section of directories/patterns.
11586
11587 @item ^-c^/CONFIG_FILE=^@file{file}
11588 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11589 Create a configuration pragmas file @file{file} (instead of the default
11590 @file{gnat.adc}).
11591 @ifclear vms
11592 There may be zero, one or more space between @option{-c} and
11593 @file{file}.
11594 @end ifclear
11595 @file{file} may include directory information. @file{file} must be
11596 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11597 When a switch @option{^-c^/CONFIG_FILE^} is
11598 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11599
11600 @item ^-d^/SOURCE_DIRS=^@file{dir}
11601 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11602 Look for source files in directory @file{dir}. There may be zero, one or more
11603 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11604 When a switch @option{^-d^/SOURCE_DIRS^}
11605 is specified, the current working directory will not be searched for source
11606 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11607 or @option{^-D^/DIR_FILES^} switch.
11608 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11609 If @file{dir} is a relative path, it is relative to the directory of
11610 the configuration pragmas file specified with switch
11611 @option{^-c^/CONFIG_FILE^},
11612 or to the directory of the project file specified with switch
11613 @option{^-P^/PROJECT_FILE^} or,
11614 if neither switch @option{^-c^/CONFIG_FILE^}
11615 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11616 current working directory. The directory
11617 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11618
11619 @item ^-D^/DIRS_FILE=^@file{file}
11620 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11621 Look for source files in all directories listed in text file @file{file}.
11622 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11623 and @file{file}.
11624 @file{file} must be an existing, readable text file.
11625 Each nonempty line in @file{file} must be a directory.
11626 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11627 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11628 @file{file}.
11629
11630 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11631 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11632 Foreign patterns. Using this switch, it is possible to add sources of languages
11633 other than Ada to the list of sources of a project file.
11634 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11635 For example,
11636 @smallexample
11637 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11638 @end smallexample
11639 @noindent
11640 will look for Ada units in all files with the @file{.ada} extension,
11641 and will add to the list of file for project @file{prj.gpr} the C files
11642 with extension @file{.^c^C^}.
11643
11644 @item ^-h^/HELP^
11645 @cindex @option{^-h^/HELP^} (@code{gnatname})
11646 Output usage (help) information. The output is written to @file{stdout}.
11647
11648 @item ^-P^/PROJECT_FILE=^@file{proj}
11649 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11650 Create or update project file @file{proj}. There may be zero, one or more space
11651 between @option{-P} and @file{proj}. @file{proj} may include directory
11652 information. @file{proj} must be writable.
11653 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11654 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11655 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11656
11657 @item ^-v^/VERBOSE^
11658 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11659 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11660 This includes name of the file written, the name of the directories to search
11661 and, for each file in those directories whose name matches at least one of
11662 the Naming Patterns, an indication of whether the file contains a unit,
11663 and if so the name of the unit.
11664
11665 @item ^-v -v^/VERBOSE /VERBOSE^
11666 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11667 Very Verbose mode. In addition to the output produced in verbose mode,
11668 for each file in the searched directories whose name matches none of
11669 the Naming Patterns, an indication is given that there is no match.
11670
11671 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11672 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11673 Excluded patterns. Using this switch, it is possible to exclude some files
11674 that would match the name patterns. For example,
11675 @smallexample
11676 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11677 @end smallexample
11678 @noindent
11679 will look for Ada units in all files with the @file{.ada} extension,
11680 except those whose names end with @file{_nt.ada}.
11681
11682 @end table
11683
11684 @node Examples of gnatname Usage
11685 @section Examples of @code{gnatname} Usage
11686
11687 @ifset vms
11688 @smallexample
11689 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11690 @end smallexample
11691 @end ifset
11692
11693 @ifclear vms
11694 @smallexample
11695 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11696 @end smallexample
11697 @end ifclear
11698
11699 @noindent
11700 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11701 and be writable. In addition, the directory
11702 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11703 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11704
11705 @ifclear vms
11706 Note the optional spaces after @option{-c} and @option{-d}.
11707 @end ifclear
11708
11709 @smallexample
11710 @ifclear vms
11711 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11712   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11713 @end ifclear
11714 @ifset vms
11715 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11716   /EXCLUDED_PATTERN=*_nt_body.ada
11717   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11718   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11719 @end ifset
11720 @end smallexample
11721
11722 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11723 even in conjunction with one or several switches
11724 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11725 are used in this example.
11726
11727 @c *****************************************
11728 @c * G N A T  P r o j e c t  M a n a g e r *
11729 @c *****************************************
11730 @node GNAT Project Manager
11731 @chapter GNAT Project Manager
11732
11733 @menu
11734 * Introduction::
11735 * Examples of Project Files::
11736 * Project File Syntax::
11737 * Objects and Sources in Project Files::
11738 * Importing Projects::
11739 * Project Extension::
11740 * Project Hierarchy Extension::
11741 * External References in Project Files::
11742 * Packages in Project Files::
11743 * Variables from Imported Projects::
11744 * Naming Schemes::
11745 * Library Projects::
11746 * Stand-alone Library Projects::
11747 * Switches Related to Project Files::
11748 * Tools Supporting Project Files::
11749 * An Extended Example::
11750 * Project File Complete Syntax::
11751 @end menu
11752
11753 @c ****************
11754 @c * Introduction *
11755 @c ****************
11756
11757 @node Introduction
11758 @section Introduction
11759
11760 @noindent
11761 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11762 you to manage complex builds involving a number of source files, directories,
11763 and compilation options for different system configurations. In particular,
11764 project files allow you to specify:
11765 @itemize @bullet
11766 @item
11767 The directory or set of directories containing the source files, and/or the
11768 names of the specific source files themselves
11769 @item
11770 The directory in which the compiler's output
11771 (@file{ALI} files, object files, tree files) is to be placed
11772 @item
11773 The directory in which the executable programs is to be placed
11774 @item
11775 ^Switch^Switch^ settings for any of the project-enabled tools
11776 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11777 @code{gnatfind}); you can apply these settings either globally or to individual
11778 compilation units.
11779 @item
11780 The source files containing the main subprogram(s) to be built
11781 @item
11782 The source programming language(s) (currently Ada and/or C)
11783 @item
11784 Source file naming conventions; you can specify these either globally or for
11785 individual compilation units
11786 @end itemize
11787
11788 @menu
11789 * Project Files::
11790 @end menu
11791
11792 @node Project Files
11793 @subsection Project Files
11794
11795 @noindent
11796 Project files are written in a syntax close to that of Ada, using  familiar
11797 notions such as packages, context clauses, declarations, default values,
11798 assignments, and inheritance. Finally, project files can be built
11799 hierarchically from other project files, simplifying complex system
11800 integration and project reuse.
11801
11802 A @dfn{project} is a specific set of values for various compilation properties.
11803 The settings for a given project are described by means of
11804 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11805 Property values in project files are either strings or lists of strings.
11806 Properties that are not explicitly set receive default values.  A project
11807 file may interrogate the values of @dfn{external variables} (user-defined
11808 command-line switches or environment variables), and it may specify property
11809 settings conditionally, based on the value of such variables.
11810
11811 In simple cases, a project's source files depend only on other source files
11812 in the same project, or on the predefined libraries.  (@emph{Dependence} is
11813 used in
11814 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
11815 the Project Manager also allows more sophisticated arrangements,
11816 where the source files in one project depend on source files in other
11817 projects:
11818 @itemize @bullet
11819 @item
11820 One project can @emph{import} other projects containing needed source files.
11821 @item
11822 You can organize GNAT projects in a hierarchy: a @emph{child} project
11823 can extend a @emph{parent} project, inheriting the parent's source files and
11824 optionally overriding any of them with alternative versions
11825 @end itemize
11826
11827 @noindent
11828 More generally, the Project Manager lets you structure large development
11829 efforts into hierarchical subsystems, where build decisions are delegated
11830 to the subsystem level, and thus different compilation environments
11831 (^switch^switch^ settings) used for different subsystems.
11832
11833 The Project Manager is invoked through the
11834 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11835 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11836 @ifclear vms
11837 There may be zero, one or more spaces between @option{-P} and
11838 @option{@emph{projectfile}}.
11839 @end ifclear
11840 If you want to define (on the command line) an external variable that is
11841 queried by the project file, you must use the
11842 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11843 The Project Manager parses and interprets the project file, and drives the
11844 invoked tool based on the project settings.
11845
11846 The Project Manager supports a wide range of development strategies,
11847 for systems of all sizes.  Here are some typical practices that are
11848 easily handled:
11849 @itemize @bullet
11850 @item
11851 Using a common set of source files, but generating object files in different
11852 directories via different ^switch^switch^ settings
11853 @item
11854 Using a mostly-shared set of source files, but with different versions of
11855 some unit or units
11856 @end itemize
11857
11858 @noindent
11859 The destination of an executable can be controlled inside a project file
11860 using the @option{^-o^-o^}
11861 ^switch^switch^.
11862 In the absence of such a ^switch^switch^ either inside
11863 the project file or on the command line, any executable files generated by
11864 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11865 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11866 in the object directory of the project.
11867
11868 You can use project files to achieve some of the effects of a source
11869 versioning system (for example, defining separate projects for
11870 the different sets of sources that comprise different releases) but the
11871 Project Manager is independent of any source configuration management tools
11872 that might be used by the developers.
11873
11874 The next section introduces the main features of GNAT's project facility
11875 through a sequence of examples; subsequent sections will present the syntax
11876 and semantics in more detail. A more formal description of the project
11877 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11878 Reference Manual}.
11879
11880 @c *****************************
11881 @c * Examples of Project Files *
11882 @c *****************************
11883
11884 @node Examples of Project Files
11885 @section Examples of Project Files
11886 @noindent
11887 This section illustrates some of the typical uses of project files and
11888 explains their basic structure and behavior.
11889
11890 @menu
11891 * Common Sources with Different ^Switches^Switches^ and Directories::
11892 * Using External Variables::
11893 * Importing Other Projects::
11894 * Extending a Project::
11895 @end menu
11896
11897 @node Common Sources with Different ^Switches^Switches^ and Directories
11898 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11899
11900 @menu
11901 * Source Files::
11902 * Specifying the Object Directory::
11903 * Specifying the Exec Directory::
11904 * Project File Packages::
11905 * Specifying ^Switch^Switch^ Settings::
11906 * Main Subprograms::
11907 * Executable File Names::
11908 * Source File Naming Conventions::
11909 * Source Language(s)::
11910 @end menu
11911
11912 @noindent
11913 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11914 @file{proc.adb} are in the @file{/common} directory.  The file
11915 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11916 package @code{Pack}.  We want to compile these source files under two sets
11917 of ^switches^switches^:
11918 @itemize @bullet
11919 @item
11920 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11921 and the @option{^-gnata^-gnata^},
11922 @option{^-gnato^-gnato^},
11923 and @option{^-gnatE^-gnatE^} switches to the
11924 compiler; the compiler's output is to appear in @file{/common/debug}
11925 @item
11926 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11927 to the compiler; the compiler's output is to appear in @file{/common/release}
11928 @end itemize
11929
11930 @noindent
11931 The GNAT project files shown below, respectively @file{debug.gpr} and
11932 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11933
11934 Schematically:
11935 @smallexample
11936 @group
11937 ^/common^[COMMON]^
11938   debug.gpr
11939   release.gpr
11940   pack.ads
11941   pack.adb
11942   proc.adb
11943 @end group
11944 @group
11945 ^/common/debug^[COMMON.DEBUG]^
11946   proc.ali, proc.o
11947   pack.ali, pack.o
11948 @end group
11949 @group
11950 ^/common/release^[COMMON.RELEASE]^
11951   proc.ali, proc.o
11952   pack.ali, pack.o
11953 @end group
11954 @end smallexample
11955 Here are the corresponding project files:
11956
11957 @smallexample @c projectfile
11958 @group
11959 project Debug is
11960   for Object_Dir use "debug";
11961   for Main use ("proc");
11962
11963   package Builder is
11964     for ^Default_Switches^Default_Switches^ ("Ada")
11965         use ("^-g^-g^");
11966     for Executable ("proc.adb") use "proc1";
11967   end Builder;
11968 @end group
11969
11970 @group
11971   package Compiler is
11972     for ^Default_Switches^Default_Switches^ ("Ada")
11973        use ("-fstack-check",
11974             "^-gnata^-gnata^",
11975             "^-gnato^-gnato^",
11976             "^-gnatE^-gnatE^");
11977   end Compiler;
11978 end Debug;
11979 @end group
11980 @end smallexample
11981
11982 @smallexample @c projectfile
11983 @group
11984 project Release is
11985   for Object_Dir use "release";
11986   for Exec_Dir use ".";
11987   for Main use ("proc");
11988
11989   package Compiler is
11990     for ^Default_Switches^Default_Switches^ ("Ada")
11991         use ("^-O2^-O2^");
11992   end Compiler;
11993 end Release;
11994 @end group
11995 @end smallexample
11996
11997 @noindent
11998 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11999 insensitive), and analogously the project defined by @file{release.gpr} is
12000 @code{"Release"}.  For consistency the file should have the same name as the
12001 project, and the project file's extension should be @code{"gpr"}. These
12002 conventions are not required, but a warning is issued if they are not followed.
12003
12004 If the current directory is @file{^/temp^[TEMP]^}, then the command
12005 @smallexample
12006 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
12007 @end smallexample
12008
12009 @noindent
12010 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
12011 as well as the @code{^proc1^PROC1.EXE^} executable,
12012 using the ^switch^switch^ settings defined in the project file.
12013
12014 Likewise, the command
12015 @smallexample
12016 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
12017 @end smallexample
12018
12019 @noindent
12020 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
12021 and the @code{^proc^PROC.EXE^}
12022 executable in @file{^/common^[COMMON]^},
12023 using the ^switch^switch^ settings from the project file.
12024
12025 @node Source Files
12026 @unnumberedsubsubsec Source Files
12027
12028 @noindent
12029 If a project file does not explicitly specify a set of source directories or
12030 a set of source files, then by default the project's source files are the
12031 Ada source files in the project file directory.  Thus @file{pack.ads},
12032 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
12033
12034 @node Specifying the Object Directory
12035 @unnumberedsubsubsec Specifying the Object Directory
12036
12037 @noindent
12038 Several project properties are modeled by Ada-style @emph{attributes};
12039 a property is defined by supplying the equivalent of an Ada attribute
12040 definition clause in the project file.
12041 A project's object directory is another such a property; the corresponding
12042 attribute is @code{Object_Dir}, and its value is also a string expression,
12043 specified either as absolute or relative. In the later case,
12044 it is relative to the project file directory. Thus the compiler's
12045 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
12046 (for the @code{Debug} project)
12047 and to @file{^/common/release^[COMMON.RELEASE]^}
12048 (for the @code{Release} project).
12049 If @code{Object_Dir} is not specified, then the default is the project file
12050 directory itself.
12051
12052 @node Specifying the Exec Directory
12053 @unnumberedsubsubsec Specifying the Exec Directory
12054
12055 @noindent
12056 A project's exec directory is another property; the corresponding
12057 attribute is @code{Exec_Dir}, and its value is also a string expression,
12058 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
12059 then the default is the object directory (which may also be the project file
12060 directory if attribute @code{Object_Dir} is not specified). Thus the executable
12061 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
12062 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
12063 and in @file{^/common^[COMMON]^} for the @code{Release} project.
12064
12065 @node Project File Packages
12066 @unnumberedsubsubsec Project File Packages
12067
12068 @noindent
12069 A GNAT tool that is integrated with the Project Manager is modeled by a
12070 corresponding package in the project file. In the example above,
12071 The @code{Debug} project defines the packages @code{Builder}
12072 (for @command{gnatmake}) and @code{Compiler};
12073 the @code{Release} project defines only the @code{Compiler} package.
12074
12075 The Ada-like package syntax is not to be taken literally.  Although packages in
12076 project files bear a surface resemblance to packages in Ada source code, the
12077 notation is simply a way to convey a grouping of properties for a named
12078 entity.  Indeed, the package names permitted in project files are restricted
12079 to a predefined set, corresponding to the project-aware tools, and the contents
12080 of packages are limited to a small set of constructs.
12081 The packages in the example above contain attribute definitions.
12082
12083 @node Specifying ^Switch^Switch^ Settings
12084 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
12085
12086 @noindent
12087 ^Switch^Switch^ settings for a project-aware tool can be specified through
12088 attributes in the package that corresponds to the tool.
12089 The example above illustrates one of the relevant attributes,
12090 @code{^Default_Switches^Default_Switches^}, which is defined in packages
12091 in both project files.
12092 Unlike simple attributes like @code{Source_Dirs},
12093 @code{^Default_Switches^Default_Switches^} is
12094 known as an @emph{associative array}.  When you define this attribute, you must
12095 supply an ``index'' (a literal string), and the effect of the attribute
12096 definition is to set the value of the array at the specified index.
12097 For the @code{^Default_Switches^Default_Switches^} attribute,
12098 the index is a programming language (in our case, Ada),
12099 and the value specified (after @code{use}) must be a list
12100 of string expressions.
12101
12102 The attributes permitted in project files are restricted to a predefined set.
12103 Some may appear at project level, others in packages.
12104 For any attribute that is an associative array, the index must always be a
12105 literal string, but the restrictions on this string (e.g., a file name or a
12106 language name) depend on the individual attribute.
12107 Also depending on the attribute, its specified value will need to be either a
12108 string or a string list.
12109
12110 In the @code{Debug} project, we set the switches for two tools,
12111 @command{gnatmake} and the compiler, and thus we include the two corresponding
12112 packages; each package defines the @code{^Default_Switches^Default_Switches^}
12113 attribute with index @code{"Ada"}.
12114 Note that the package corresponding to
12115 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
12116 similar, but only includes the @code{Compiler} package.
12117
12118 In project @code{Debug} above, the ^switches^switches^ starting with
12119 @option{-gnat} that are specified in package @code{Compiler}
12120 could have been placed in package @code{Builder}, since @command{gnatmake}
12121 transmits all such ^switches^switches^ to the compiler.
12122
12123 @node Main Subprograms
12124 @unnumberedsubsubsec Main Subprograms
12125
12126 @noindent
12127 One of the specifiable properties of a project is a list of files that contain
12128 main subprograms.  This property is captured in the @code{Main} attribute,
12129 whose value is a list of strings.  If a project defines the @code{Main}
12130 attribute, it is not necessary to identify the main subprogram(s) when
12131 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
12132
12133 @node Executable File Names
12134 @unnumberedsubsubsec Executable File Names
12135
12136 @noindent
12137 By default, the executable file name corresponding to a main source is
12138 deduced from the main source file name. Through the attributes
12139 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
12140 it is possible to change this default.
12141 In project @code{Debug} above, the executable file name
12142 for main source @file{^proc.adb^PROC.ADB^} is
12143 @file{^proc1^PROC1.EXE^}.
12144 Attribute @code{Executable_Suffix}, when specified, may change the suffix
12145 of the executable files, when no attribute @code{Executable} applies:
12146 its value replace the platform-specific executable suffix.
12147 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
12148 specify a non-default executable file name when several mains are built at once
12149 in a single @command{gnatmake} command.
12150
12151 @node Source File Naming Conventions
12152 @unnumberedsubsubsec Source File Naming Conventions
12153
12154 @noindent
12155 Since the project files above do not specify any source file naming
12156 conventions, the GNAT defaults are used.  The mechanism for defining source
12157 file naming conventions -- a package named @code{Naming} --
12158 is described below (@pxref{Naming Schemes}).
12159
12160 @node Source Language(s)
12161 @unnumberedsubsubsec Source Language(s)
12162
12163 @noindent
12164 Since the project files do not specify a @code{Languages} attribute, by
12165 default the GNAT tools assume that the language of the project file is Ada.
12166 More generally, a project can comprise source files
12167 in Ada, C, and/or other languages.
12168
12169 @node Using External Variables
12170 @subsection Using External Variables
12171
12172 @noindent
12173 Instead of supplying different project files for debug and release, we can
12174 define a single project file that queries an external variable (set either
12175 on the command line or via an ^environment variable^logical name^) in order to
12176 conditionally define the appropriate settings.  Again, assume that the
12177 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
12178 located in directory @file{^/common^[COMMON]^}.  The following project file,
12179 @file{build.gpr}, queries the external variable named @code{STYLE} and
12180 defines an object directory and ^switch^switch^ settings based on whether
12181 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
12182 the default is @code{"deb"}.
12183
12184 @smallexample @c projectfile
12185 @group
12186 project Build is
12187   for Main use ("proc");
12188
12189   type Style_Type is ("deb", "rel");
12190   Style : Style_Type := external ("STYLE", "deb");
12191
12192   case Style is
12193     when "deb" =>
12194       for Object_Dir use "debug";
12195
12196     when "rel" =>
12197       for Object_Dir use "release";
12198       for Exec_Dir use ".";
12199   end case;
12200 @end group
12201
12202 @group
12203   package Builder is
12204
12205     case Style is
12206       when "deb" =>
12207         for ^Default_Switches^Default_Switches^ ("Ada")
12208             use ("^-g^-g^");
12209         for Executable ("proc") use "proc1";
12210       when others =>
12211         null;
12212     end case;
12213
12214   end Builder;
12215 @end group
12216
12217 @group
12218   package Compiler is
12219
12220     case Style is
12221       when "deb" =>
12222         for ^Default_Switches^Default_Switches^ ("Ada")
12223             use ("^-gnata^-gnata^",
12224                  "^-gnato^-gnato^",
12225                  "^-gnatE^-gnatE^");
12226
12227       when "rel" =>
12228         for ^Default_Switches^Default_Switches^ ("Ada")
12229             use ("^-O2^-O2^");
12230     end case;
12231
12232   end Compiler;
12233
12234 end Build;
12235 @end group
12236 @end smallexample
12237
12238 @noindent
12239 @code{Style_Type} is an example of a @emph{string type}, which is the project
12240 file analog of an Ada enumeration type but whose components are string literals
12241 rather than identifiers.  @code{Style} is declared as a variable of this type.
12242
12243 The form @code{external("STYLE", "deb")} is known as an
12244 @emph{external reference}; its first argument is the name of an
12245 @emph{external variable}, and the second argument is a default value to be
12246 used if the external variable doesn't exist.  You can define an external
12247 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
12248 or you can use ^an environment variable^a logical name^
12249 as an external variable.
12250
12251 Each @code{case} construct is expanded by the Project Manager based on the
12252 value of @code{Style}. Thus the command
12253 @ifclear vms
12254 @smallexample
12255 gnatmake -P/common/build.gpr -XSTYLE=deb
12256 @end smallexample
12257 @end ifclear
12258
12259 @ifset vms
12260 @smallexample
12261 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
12262 @end smallexample
12263 @end ifset
12264
12265 @noindent
12266 is equivalent to the @command{gnatmake} invocation using the project file
12267 @file{debug.gpr} in the earlier example.  So is the command
12268 @smallexample
12269 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
12270 @end smallexample
12271
12272 @noindent
12273 since @code{"deb"} is the default for @code{STYLE}.
12274
12275 Analogously,
12276
12277 @ifclear vms
12278 @smallexample
12279 gnatmake -P/common/build.gpr -XSTYLE=rel
12280 @end smallexample
12281 @end ifclear
12282
12283 @ifset vms
12284 @smallexample
12285 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
12286 @end smallexample
12287 @end ifset
12288
12289 @noindent
12290 is equivalent to the @command{gnatmake} invocation using the project file
12291 @file{release.gpr} in the earlier example.
12292
12293 @node Importing Other Projects
12294 @subsection Importing Other Projects
12295 @cindex @code{ADA_PROJECT_PATH}
12296 @cindex @code{GPR_PROJECT_PATH}
12297
12298 @noindent
12299 A compilation unit in a source file in one project may depend on compilation
12300 units in source files in other projects.  To compile this unit under
12301 control of a project file, the
12302 dependent project must @emph{import} the projects containing the needed source
12303 files.
12304 This effect is obtained using syntax similar to an Ada @code{with} clause,
12305 but where @code{with}ed entities are strings that denote project files.
12306
12307 As an example, suppose that the two projects @code{GUI_Proj} and
12308 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
12309 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
12310 and @file{^/comm^[COMM]^}, respectively.
12311 Suppose that the source files for @code{GUI_Proj} are
12312 @file{gui.ads} and @file{gui.adb}, and that the source files for
12313 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
12314 files is located in its respective project file directory.  Schematically:
12315
12316 @smallexample
12317 @group
12318 ^/gui^[GUI]^
12319   gui_proj.gpr
12320   gui.ads
12321   gui.adb
12322 @end group
12323
12324 @group
12325 ^/comm^[COMM]^
12326   comm_proj.gpr
12327   comm.ads
12328   comm.adb
12329 @end group
12330 @end smallexample
12331
12332 @noindent
12333 We want to develop an application in directory @file{^/app^[APP]^} that
12334 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12335 the corresponding project files (e.g.@: the ^switch^switch^ settings
12336 and object directory).
12337 Skeletal code for a main procedure might be something like the following:
12338
12339 @smallexample @c ada
12340 @group
12341 with GUI, Comm;
12342 procedure App_Main is
12343    @dots{}
12344 begin
12345    @dots{}
12346 end App_Main;
12347 @end group
12348 @end smallexample
12349
12350 @noindent
12351 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12352 effect:
12353
12354 @smallexample @c projectfile
12355 @group
12356 with "/gui/gui_proj", "/comm/comm_proj";
12357 project App_Proj is
12358    for Main use ("app_main");
12359 end App_Proj;
12360 @end group
12361 @end smallexample
12362
12363 @noindent
12364 Building an executable is achieved through the command:
12365 @smallexample
12366 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12367 @end smallexample
12368 @noindent
12369 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12370 in the directory where @file{app_proj.gpr} resides.
12371
12372 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12373 (as illustrated above) the @code{with} clause can omit the extension.
12374
12375 Our example specified an absolute path for each imported project file.
12376 Alternatively, the directory name of an imported object can be omitted
12377 if either
12378 @itemize @bullet
12379 @item
12380 The imported project file is in the same directory as the importing project
12381 file, or
12382 @item
12383 You have defined one or two ^environment variables^logical names^
12384 that includes the directory containing
12385 the needed project file. The syntax of @code{GPR_PROJECT_PATH} and
12386 @code{ADA_PROJECT_PATH} is the same as
12387 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12388 directory names separated by colons (semicolons on Windows).
12389 @end itemize
12390
12391 @noindent
12392 Thus, if we define @code{ADA_PROJECT_PATH} or @code{GPR_PROJECT_PATH}
12393 to include @file{^/gui^[GUI]^} and
12394 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12395 as follows:
12396
12397 @smallexample @c projectfile
12398 @group
12399 with "gui_proj", "comm_proj";
12400 project App_Proj is
12401    for Main use ("app_main");
12402 end App_Proj;
12403 @end group
12404 @end smallexample
12405
12406 @noindent
12407 Importing other projects can create ambiguities.
12408 For example, the same unit might be present in different imported projects, or
12409 it might be present in both the importing project and in an imported project.
12410 Both of these conditions are errors.  Note that in the current version of
12411 the Project Manager, it is illegal to have an ambiguous unit even if the
12412 unit is never referenced by the importing project.  This restriction may be
12413 relaxed in a future release.
12414
12415 @node Extending a Project
12416 @subsection Extending a Project
12417
12418 @noindent
12419 In large software systems it is common to have multiple
12420 implementations of a common interface; in Ada terms, multiple versions of a
12421 package body for the same spec.  For example, one implementation
12422 might be safe for use in tasking programs, while another might only be used
12423 in sequential applications.  This can be modeled in GNAT using the concept
12424 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
12425 another project (the ``parent'') then by default all source files of the
12426 parent project are inherited by the child, but the child project can
12427 override any of the parent's source files with new versions, and can also
12428 add new files.  This facility is the project analog of a type extension in
12429 Object-Oriented Programming.  Project hierarchies are permitted (a child
12430 project may be the parent of yet another project), and a project that
12431 inherits one project can also import other projects.
12432
12433 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12434 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12435 @file{pack.adb}, and @file{proc.adb}:
12436
12437 @smallexample
12438 @group
12439 ^/seq^[SEQ]^
12440   pack.ads
12441   pack.adb
12442   proc.adb
12443   seq_proj.gpr
12444 @end group
12445 @end smallexample
12446
12447 @noindent
12448 Note that the project file can simply be empty (that is, no attribute or
12449 package is defined):
12450
12451 @smallexample @c projectfile
12452 @group
12453 project Seq_Proj is
12454 end Seq_Proj;
12455 @end group
12456 @end smallexample
12457
12458 @noindent
12459 implying that its source files are all the Ada source files in the project
12460 directory.
12461
12462 Suppose we want to supply an alternate version of @file{pack.adb}, in
12463 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12464 @file{pack.ads} and @file{proc.adb}.  We can define a project
12465 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12466
12467 @smallexample
12468 @group
12469 ^/tasking^[TASKING]^
12470   pack.adb
12471   tasking_proj.gpr
12472 @end group
12473
12474 @group
12475 project Tasking_Proj extends "/seq/seq_proj" is
12476 end Tasking_Proj;
12477 @end group
12478 @end smallexample
12479
12480 @noindent
12481 The version of @file{pack.adb} used in a build depends on which project file
12482 is specified.
12483
12484 Note that we could have obtained the desired behavior using project import
12485 rather than project inheritance; a @code{base} project would contain the
12486 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12487 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12488 would import @code{base} and add a different version of @file{pack.adb}.  The
12489 choice depends on whether other sources in the original project need to be
12490 overridden.  If they do, then project extension is necessary, otherwise,
12491 importing is sufficient.
12492
12493 @noindent
12494 In a project file that extends another project file, it is possible to
12495 indicate that an inherited source is not part of the sources of the extending
12496 project. This is necessary sometimes when a package spec has been overloaded
12497 and no longer requires a body: in this case, it is necessary to indicate that
12498 the inherited body is not part of the sources of the project, otherwise there
12499 will be a compilation error when compiling the spec.
12500
12501 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12502 Its value is a string list: a list of file names. It is also possible to use
12503 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12504 the file name of a text file containing a list of file names, one per line.
12505
12506 @smallexample @c @projectfile
12507 project B extends "a" is
12508    for Source_Files use ("pkg.ads");
12509    --  New spec of Pkg does not need a completion
12510    for Excluded_Source_Files use ("pkg.adb");
12511 end B;
12512 @end smallexample
12513
12514 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12515 is still needed: if it is possible to build using @command{gnatmake} when such
12516 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12517 it is possible to remove the source completely from a system that includes
12518 project P.
12519
12520 @c ***********************
12521 @c * Project File Syntax *
12522 @c ***********************
12523
12524 @node Project File Syntax
12525 @section Project File Syntax
12526
12527 @menu
12528 * Basic Syntax::
12529 * Qualified Projects::
12530 * Packages::
12531 * Expressions::
12532 * String Types::
12533 * Variables::
12534 * Attributes::
12535 * Associative Array Attributes::
12536 * case Constructions::
12537 @end menu
12538
12539 @noindent
12540 This section describes the structure of project files.
12541
12542 A project may be an @emph{independent project}, entirely defined by a single
12543 project file. Any Ada source file in an independent project depends only
12544 on the predefined library and other Ada source files in the same project.
12545
12546 @noindent
12547 A project may also @dfn{depend on} other projects, in either or both of
12548 the following ways:
12549 @itemize @bullet
12550 @item It may import any number of projects
12551 @item It may extend at most one other project
12552 @end itemize
12553
12554 @noindent
12555 The dependence relation is a directed acyclic graph (the subgraph reflecting
12556 the ``extends'' relation is a tree).
12557
12558 A project's @dfn{immediate sources} are the source files directly defined by
12559 that project, either implicitly by residing in the project file's directory,
12560 or explicitly through any of the source-related attributes described below.
12561 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12562 of @var{proj} together with the immediate sources (unless overridden) of any
12563 project on which @var{proj} depends (either directly or indirectly).
12564
12565 @node Basic Syntax
12566 @subsection Basic Syntax
12567
12568 @noindent
12569 As seen in the earlier examples, project files have an Ada-like syntax.
12570 The minimal project file is:
12571 @smallexample @c projectfile
12572 @group
12573 project Empty is
12574
12575 end Empty;
12576 @end group
12577 @end smallexample
12578
12579 @noindent
12580 The identifier @code{Empty} is the name of the project.
12581 This project name must be present after the reserved
12582 word @code{end} at the end of the project file, followed by a semi-colon.
12583
12584 Any name in a project file, such as the project name or a variable name,
12585 has the same syntax as an Ada identifier.
12586
12587 The reserved words of project files are the Ada 95 reserved words plus
12588 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
12589 reserved words currently used in project file syntax are:
12590
12591 @itemize @bullet
12592 @item
12593 @code{all}
12594 @item
12595 @code{at}
12596 @item
12597 @code{case}
12598 @item
12599 @code{end}
12600 @item
12601 @code{for}
12602 @item
12603 @code{is}
12604 @item
12605 @code{limited}
12606 @item
12607 @code{null}
12608 @item
12609 @code{others}
12610 @item
12611 @code{package}
12612 @item
12613 @code{renames}
12614 @item
12615 @code{type}
12616 @item
12617 @code{use}
12618 @item
12619 @code{when}
12620 @item
12621 @code{with}
12622 @end itemize
12623
12624 @noindent
12625 Comments in project files have the same syntax as in Ada, two consecutive
12626 hyphens through the end of the line.
12627
12628 @node Qualified Projects
12629 @subsection Qualified Projects
12630
12631 @noindent
12632 Before the reserved @code{project}, there may be one or two "qualifiers", that
12633 is identifiers or other reserved words, to qualify the project.
12634
12635 The current list of qualifiers is:
12636
12637 @itemize @bullet
12638 @item
12639 @code{abstract}: qualify a project with no sources. A qualified abstract
12640 project must either have no declaration of attributes @code{Source_Dirs},
12641 @code{Source_Files}, @code{Languages} or @code{Source_List_File}, or one of
12642 @code{Source_Dirs}, @code{Source_Files}, or @code{Languages} must be declared
12643 as empty. If it extends another project, the project it extends must also be a
12644 qualified abstract project.
12645
12646 @item
12647 @code{standard}: a standard project is a non library project with sources.
12648
12649 @item
12650 @code{aggregate}: for future extension
12651
12652 @item
12653 @code{aggregate library}: for future extension
12654
12655 @item
12656 @code{library}: a library project must declare both attributes
12657 @code{Library_Name} and @code{Library_Dir}.
12658
12659 @item
12660 @code{configuration}: a configuration project cannot be in a project tree.
12661 @end itemize
12662
12663 @node Packages
12664 @subsection Packages
12665
12666 @noindent
12667 A project file may contain @emph{packages}. The name of a package must be one
12668 of the identifiers from the following list. A package
12669 with a given name may only appear once in a project file. Package names are
12670 case insensitive. The following package names are legal:
12671
12672 @itemize @bullet
12673 @item
12674 @code{Naming}
12675 @item
12676 @code{Builder}
12677 @item
12678 @code{Compiler}
12679 @item
12680 @code{Binder}
12681 @item
12682 @code{Linker}
12683 @item
12684 @code{Finder}
12685 @item
12686 @code{Cross_Reference}
12687 @item
12688 @code{Eliminate}
12689 @item
12690 @code{Pretty_Printer}
12691 @item
12692 @code{Metrics}
12693 @item
12694 @code{gnatls}
12695 @item
12696 @code{gnatstub}
12697 @item
12698 @code{IDE}
12699 @item
12700 @code{Language_Processing}
12701 @end itemize
12702
12703 @noindent
12704 In its simplest form, a package may be empty:
12705
12706 @smallexample @c projectfile
12707 @group
12708 project Simple is
12709   package Builder is
12710   end Builder;
12711 end Simple;
12712 @end group
12713 @end smallexample
12714
12715 @noindent
12716 A package may contain @emph{attribute declarations},
12717 @emph{variable declarations} and @emph{case constructions}, as will be
12718 described below.
12719
12720 When there is ambiguity between a project name and a package name,
12721 the name always designates the project. To avoid possible confusion, it is
12722 always a good idea to avoid naming a project with one of the
12723 names allowed for packages or any name that starts with @code{gnat}.
12724
12725 @node Expressions
12726 @subsection Expressions
12727
12728 @noindent
12729 An @emph{expression} is either a @emph{string expression} or a
12730 @emph{string list expression}.
12731
12732 A @emph{string expression} is either a @emph{simple string expression} or a
12733 @emph{compound string expression}.
12734
12735 A @emph{simple string expression} is one of the following:
12736 @itemize @bullet
12737 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12738 @item A string-valued variable reference (@pxref{Variables})
12739 @item A string-valued attribute reference (@pxref{Attributes})
12740 @item An external reference (@pxref{External References in Project Files})
12741 @end itemize
12742
12743 @noindent
12744 A @emph{compound string expression} is a concatenation of string expressions,
12745 using the operator @code{"&"}
12746 @smallexample
12747        Path & "/" & File_Name & ".ads"
12748 @end smallexample
12749
12750 @noindent
12751 A @emph{string list expression} is either a
12752 @emph{simple string list expression} or a
12753 @emph{compound string list expression}.
12754
12755 A @emph{simple string list expression} is one of the following:
12756 @itemize @bullet
12757 @item A parenthesized list of zero or more string expressions,
12758 separated by commas
12759 @smallexample
12760    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12761    Empty_List := ();
12762 @end smallexample
12763 @item A string list-valued variable reference
12764 @item A string list-valued attribute reference
12765 @end itemize
12766
12767 @noindent
12768 A @emph{compound string list expression} is the concatenation (using
12769 @code{"&"}) of a simple string list expression and an expression.  Note that
12770 each term in a compound string list expression, except the first, may be
12771 either a string expression or a string list expression.
12772
12773 @smallexample @c projectfile
12774 @group
12775    File_Name_List := () & File_Name; --  One string in this list
12776    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12777    --  Two strings
12778    Big_List := File_Name_List & Extended_File_Name_List;
12779    --  Concatenation of two string lists: three strings
12780    Illegal_List := "gnat.adc" & Extended_File_Name_List;
12781    --  Illegal: must start with a string list
12782 @end group
12783 @end smallexample
12784
12785 @node String Types
12786 @subsection String Types
12787
12788 @noindent
12789 A @emph{string type declaration} introduces a discrete set of string literals.
12790 If a string variable is declared to have this type, its value
12791 is restricted to the given set of literals.
12792
12793 Here is an example of a string type declaration:
12794
12795 @smallexample @c projectfile
12796    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12797 @end smallexample
12798
12799 @noindent
12800 Variables of a string type are called @emph{typed variables}; all other
12801 variables are called @emph{untyped variables}. Typed variables are
12802 particularly useful in @code{case} constructions, to support conditional
12803 attribute declarations.
12804 (@pxref{case Constructions}).
12805
12806 The string literals in the list are case sensitive and must all be different.
12807 They may include any graphic characters allowed in Ada, including spaces.
12808
12809 A string type may only be declared at the project level, not inside a package.
12810
12811 A string type may be referenced by its name if it has been declared in the same
12812 project file, or by an expanded name whose prefix is the name of the project
12813 in which it is declared.
12814
12815 @node Variables
12816 @subsection Variables
12817
12818 @noindent
12819 A variable may be declared at the project file level, or within a package.
12820 Here are some examples of variable declarations:
12821
12822 @smallexample @c projectfile
12823 @group
12824    This_OS : OS := external ("OS"); --  a typed variable declaration
12825    That_OS := "GNU/Linux";          --  an untyped variable declaration
12826 @end group
12827 @end smallexample
12828
12829 @noindent
12830 The syntax of a @emph{typed variable declaration} is identical to the Ada
12831 syntax for an object declaration. By contrast, the syntax of an untyped
12832 variable declaration is identical to an Ada assignment statement. In fact,
12833 variable declarations in project files have some of the characteristics of
12834 an assignment, in that successive declarations for the same variable are
12835 allowed. Untyped variable declarations do establish the expected kind of the
12836 variable (string or string list), and successive declarations for it must
12837 respect the initial kind.
12838
12839 @noindent
12840 A string variable declaration (typed or untyped) declares a variable
12841 whose value is a string. This variable may be used as a string expression.
12842 @smallexample @c projectfile
12843    File_Name       := "readme.txt";
12844    Saved_File_Name := File_Name & ".saved";
12845 @end smallexample
12846
12847 @noindent
12848 A string list variable declaration declares a variable whose value is a list
12849 of strings. The list may contain any number (zero or more) of strings.
12850
12851 @smallexample @c projectfile
12852    Empty_List := ();
12853    List_With_One_Element := ("^-gnaty^-gnaty^");
12854    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12855    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12856                  "pack2.ada", "util_.ada", "util.ada");
12857 @end smallexample
12858
12859 @noindent
12860 The same typed variable may not be declared more than once at project level,
12861 and it may not be declared more than once in any package; it is in effect
12862 a constant.
12863
12864 The same untyped variable may be declared several times. Declarations are
12865 elaborated in the order in which they appear, so  the new value replaces
12866 the old one, and any subsequent reference to the variable uses the new value.
12867 However, as noted above, if a variable has been declared as a string, all
12868 subsequent
12869 declarations must give it a string value. Similarly, if a variable has
12870 been declared as a string list, all subsequent declarations
12871 must give it a string list value.
12872
12873 A @emph{variable reference} may take several forms:
12874
12875 @itemize @bullet
12876 @item The simple variable name, for a variable in the current package (if any)
12877 or in the current project
12878 @item An expanded name, whose prefix is a context name.
12879 @end itemize
12880
12881 @noindent
12882 A @emph{context} may be one of the following:
12883
12884 @itemize @bullet
12885 @item The name of an existing package in the current project
12886 @item The name of an imported project of the current project
12887 @item The name of an ancestor project (i.e., a project extended by the current
12888 project, either directly or indirectly)
12889 @item An expanded name whose prefix is an imported/parent project name, and
12890 whose selector is a package name in that project.
12891 @end itemize
12892
12893 @noindent
12894 A variable reference may be used in an expression.
12895
12896 @node Attributes
12897 @subsection Attributes
12898
12899 @noindent
12900 A project (and its packages) may have @emph{attributes} that define
12901 the project's properties.  Some attributes have values that are strings;
12902 others have values that are string lists.
12903
12904 There are two categories of attributes: @emph{simple attributes}
12905 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12906
12907 Legal project attribute names, and attribute names for each legal package are
12908 listed below. Attributes names are case-insensitive.
12909
12910 The following attributes are defined on projects (all are simple attributes):
12911
12912 @multitable @columnfractions .4 .3
12913 @item @emph{Attribute Name}
12914 @tab @emph{Value}
12915 @item @code{Source_Files}
12916 @tab string list
12917 @item @code{Source_Dirs}
12918 @tab string list
12919 @item @code{Source_List_File}
12920 @tab string
12921 @item @code{Object_Dir}
12922 @tab string
12923 @item @code{Exec_Dir}
12924 @tab string
12925 @item @code{Excluded_Source_Dirs}
12926 @tab string list
12927 @item @code{Excluded_Source_Files}
12928 @tab string list
12929 @item @code{Excluded_Source_List_File}
12930 @tab string
12931 @item @code{Languages}
12932 @tab string list
12933 @item @code{Main}
12934 @tab string list
12935 @item @code{Library_Dir}
12936 @tab string
12937 @item @code{Library_Name}
12938 @tab string
12939 @item @code{Library_Kind}
12940 @tab string
12941 @item @code{Library_Version}
12942 @tab string
12943 @item @code{Library_Interface}
12944 @tab string
12945 @item @code{Library_Auto_Init}
12946 @tab string
12947 @item @code{Library_Options}
12948 @tab string list
12949 @item @code{Library_Src_Dir}
12950 @tab string
12951 @item @code{Library_ALI_Dir}
12952 @tab string
12953 @item @code{Library_GCC}
12954 @tab string
12955 @item @code{Library_Symbol_File}
12956 @tab string
12957 @item @code{Library_Symbol_Policy}
12958 @tab string
12959 @item @code{Library_Reference_Symbol_File}
12960 @tab string
12961 @item @code{Externally_Built}
12962 @tab string
12963 @end multitable
12964
12965 @noindent
12966 The following attributes are defined for package  @code{Naming}
12967 (@pxref{Naming Schemes}):
12968
12969 @multitable @columnfractions .4 .2 .2 .2
12970 @item Attribute Name @tab Category @tab Index @tab Value
12971 @item @code{Spec_Suffix}
12972 @tab associative array
12973 @tab language name
12974 @tab string
12975 @item @code{Body_Suffix}
12976 @tab associative array
12977 @tab language name
12978 @tab string
12979 @item @code{Separate_Suffix}
12980 @tab simple attribute
12981 @tab n/a
12982 @tab string
12983 @item @code{Casing}
12984 @tab simple attribute
12985 @tab n/a
12986 @tab string
12987 @item @code{Dot_Replacement}
12988 @tab simple attribute
12989 @tab n/a
12990 @tab string
12991 @item @code{Spec}
12992 @tab associative array
12993 @tab Ada unit name
12994 @tab string
12995 @item @code{Body}
12996 @tab associative array
12997 @tab Ada unit name
12998 @tab string
12999 @item @code{Specification_Exceptions}
13000 @tab associative array
13001 @tab language name
13002 @tab string list
13003 @item @code{Implementation_Exceptions}
13004 @tab associative array
13005 @tab language name
13006 @tab string list
13007 @end multitable
13008
13009 @noindent
13010 The following attributes are defined for packages @code{Builder},
13011 @code{Compiler}, @code{Binder},
13012 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
13013 (@pxref{^Switches^Switches^ and Project Files}).
13014
13015 @multitable @columnfractions .4 .2 .2 .2
13016 @item Attribute Name @tab Category @tab Index @tab Value
13017 @item @code{^Default_Switches^Default_Switches^}
13018 @tab associative array
13019 @tab language name
13020 @tab string list
13021 @item @code{^Switches^Switches^}
13022 @tab associative array
13023 @tab file name
13024 @tab string list
13025 @end multitable
13026
13027 @noindent
13028 In addition, package @code{Compiler} has a single string attribute
13029 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
13030 string attribute @code{Global_Configuration_Pragmas}.
13031
13032 @noindent
13033 Each simple attribute has a default value: the empty string (for string-valued
13034 attributes) and the empty list (for string list-valued attributes).
13035
13036 An attribute declaration defines a new value for an attribute.
13037
13038 Examples of simple attribute declarations:
13039
13040 @smallexample @c projectfile
13041    for Object_Dir use "objects";
13042    for Source_Dirs use ("units", "test/drivers");
13043 @end smallexample
13044
13045 @noindent
13046 The syntax of a @dfn{simple attribute declaration} is similar to that of an
13047 attribute definition clause in Ada.
13048
13049 Attributes references may be appear in expressions.
13050 The general form for such a reference is @code{<entity>'<attribute>}:
13051 Associative array attributes are functions. Associative
13052 array attribute references must have an argument that is a string literal.
13053
13054 Examples are:
13055
13056 @smallexample @c projectfile
13057   project'Object_Dir
13058   Naming'Dot_Replacement
13059   Imported_Project'Source_Dirs
13060   Imported_Project.Naming'Casing
13061   Builder'^Default_Switches^Default_Switches^("Ada")
13062 @end smallexample
13063
13064 @noindent
13065 The prefix of an attribute may be:
13066 @itemize @bullet
13067 @item @code{project} for an attribute of the current project
13068 @item The name of an existing package of the current project
13069 @item The name of an imported project
13070 @item The name of a parent project that is extended by the current project
13071 @item An expanded name whose prefix is imported/parent project name,
13072 and whose selector is a package name
13073 @end itemize
13074
13075 @noindent
13076 Example:
13077 @smallexample @c projectfile
13078 @group
13079    project Prj is
13080      for Source_Dirs use project'Source_Dirs & "units";
13081      for Source_Dirs use project'Source_Dirs & "test/drivers"
13082    end Prj;
13083 @end group
13084 @end smallexample
13085
13086 @noindent
13087 In the first attribute declaration, initially the attribute @code{Source_Dirs}
13088 has the default value: an empty string list. After this declaration,
13089 @code{Source_Dirs} is a string list of one element: @code{"units"}.
13090 After the second attribute declaration @code{Source_Dirs} is a string list of
13091 two elements: @code{"units"} and @code{"test/drivers"}.
13092
13093 Note: this example is for illustration only. In practice,
13094 the project file would contain only one attribute declaration:
13095
13096 @smallexample @c projectfile
13097    for Source_Dirs use ("units", "test/drivers");
13098 @end smallexample
13099
13100 @node Associative Array Attributes
13101 @subsection Associative Array Attributes
13102
13103 @noindent
13104 Some attributes are defined as @emph{associative arrays}. An associative
13105 array may be regarded as a function that takes a string as a parameter
13106 and delivers a string or string list value as its result.
13107
13108 Here are some examples of single associative array attribute associations:
13109
13110 @smallexample @c projectfile
13111    for Body ("main") use "Main.ada";
13112    for ^Switches^Switches^ ("main.ada")
13113        use ("^-v^-v^",
13114             "^-gnatv^-gnatv^");
13115    for ^Switches^Switches^ ("main.ada")
13116             use Builder'^Switches^Switches^ ("main.ada")
13117               & "^-g^-g^";
13118 @end smallexample
13119
13120 @noindent
13121 Like untyped variables and simple attributes, associative array attributes
13122 may be declared several times. Each declaration supplies a new value for the
13123 attribute, and replaces the previous setting.
13124
13125 @noindent
13126 An associative array attribute may be declared as a full associative array
13127 declaration, with the value of the same attribute in an imported or extended
13128 project.
13129
13130 @smallexample @c projectfile
13131    package Builder is
13132       for Default_Switches use Default.Builder'Default_Switches;
13133    end Builder;
13134 @end smallexample
13135
13136 @noindent
13137 In this example, @code{Default} must be either a project imported by the
13138 current project, or the project that the current project extends. If the
13139 attribute is in a package (in this case, in package @code{Builder}), the same
13140 package needs to be specified.
13141
13142 @noindent
13143 A full associative array declaration replaces any other declaration for the
13144 attribute, including other full associative array declaration. Single
13145 associative array associations may be declare after a full associative
13146 declaration, modifying the value for a single association of the attribute.
13147
13148 @node case Constructions
13149 @subsection @code{case} Constructions
13150
13151 @noindent
13152 A @code{case} construction is used in a project file to effect conditional
13153 behavior.
13154 Here is a typical example:
13155
13156 @smallexample @c projectfile
13157 @group
13158 project MyProj is
13159    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
13160
13161    OS : OS_Type := external ("OS", "GNU/Linux");
13162 @end group
13163
13164 @group
13165    package Compiler is
13166      case OS is
13167        when "GNU/Linux" | "Unix" =>
13168          for ^Default_Switches^Default_Switches^ ("Ada")
13169              use ("^-gnath^-gnath^");
13170        when "NT" =>
13171          for ^Default_Switches^Default_Switches^ ("Ada")
13172              use ("^-gnatP^-gnatP^");
13173        when others =>
13174      end case;
13175    end Compiler;
13176 end MyProj;
13177 @end group
13178 @end smallexample
13179
13180 @noindent
13181 The syntax of a @code{case} construction is based on the Ada case statement
13182 (although there is no @code{null} construction for empty alternatives).
13183
13184 The case expression must be a typed string variable.
13185 Each alternative comprises the reserved word @code{when}, either a list of
13186 literal strings separated by the @code{"|"} character or the reserved word
13187 @code{others},  and the @code{"=>"} token.
13188 Each literal string must belong to the string type that is the type of the
13189 case variable.
13190 An @code{others} alternative, if present, must occur last.
13191
13192 After each @code{=>}, there are zero or more constructions.  The only
13193 constructions allowed in a case construction are other case constructions,
13194 attribute declarations and variable declarations. String type declarations and
13195 package declarations are not allowed. Variable declarations are restricted to
13196 variables that have already been declared before the case construction.
13197
13198 The value of the case variable is often given by an external reference
13199 (@pxref{External References in Project Files}).
13200
13201 @c ****************************************
13202 @c * Objects and Sources in Project Files *
13203 @c ****************************************
13204
13205 @node Objects and Sources in Project Files
13206 @section Objects and Sources in Project Files
13207
13208 @menu
13209 * Object Directory::
13210 * Exec Directory::
13211 * Source Directories::
13212 * Source File Names::
13213 @end menu
13214
13215 @noindent
13216 Each project has exactly one object directory and one or more source
13217 directories. The source directories must contain at least one source file,
13218 unless  the project file explicitly specifies that no source files are present
13219 (@pxref{Source File Names}).
13220
13221 @node Object Directory
13222 @subsection Object Directory
13223
13224 @noindent
13225 The object directory for a project is the directory containing the compiler's
13226 output (such as @file{ALI} files and object files) for the project's immediate
13227 sources.
13228
13229 The object directory is given by the value of the attribute @code{Object_Dir}
13230 in the project file.
13231
13232 @smallexample @c projectfile
13233    for Object_Dir use "objects";
13234 @end smallexample
13235
13236 @noindent
13237 The attribute @code{Object_Dir} has a string value, the path name of the object
13238 directory. The path name may be absolute or relative to the directory of the
13239 project file. This directory must already exist, and be readable and writable.
13240
13241 By default, when the attribute @code{Object_Dir} is not given an explicit value
13242 or when its value is the empty string, the object directory is the same as the
13243 directory containing the project file.
13244
13245 @node Exec Directory
13246 @subsection Exec Directory
13247
13248 @noindent
13249 The exec directory for a project is the directory containing the executables
13250 for the project's main subprograms.
13251
13252 The exec directory is given by the value of the attribute @code{Exec_Dir}
13253 in the project file.
13254
13255 @smallexample @c projectfile
13256    for Exec_Dir use "executables";
13257 @end smallexample
13258
13259 @noindent
13260 The attribute @code{Exec_Dir} has a string value, the path name of the exec
13261 directory. The path name may be absolute or relative to the directory of the
13262 project file. This directory must already exist, and be writable.
13263
13264 By default, when the attribute @code{Exec_Dir} is not given an explicit value
13265 or when its value is the empty string, the exec directory is the same as the
13266 object directory of the project file.
13267
13268 @node Source Directories
13269 @subsection Source Directories
13270
13271 @noindent
13272 The source directories of a project are specified by the project file
13273 attribute @code{Source_Dirs}.
13274
13275 This attribute's value is a string list. If the attribute is not given an
13276 explicit value, then there is only one source directory, the one where the
13277 project file resides.
13278
13279 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
13280 as in
13281
13282 @smallexample @c projectfile
13283     for Source_Dirs use ();
13284 @end smallexample
13285
13286 @noindent
13287 indicates that the project contains no source files.
13288
13289 Otherwise, each string in the string list designates one or more
13290 source directories.
13291
13292 @smallexample @c projectfile
13293    for Source_Dirs use ("sources", "test/drivers");
13294 @end smallexample
13295
13296 @noindent
13297 If a string in the list ends with @code{"/**"},  then the directory whose path
13298 name precedes the two asterisks, as well as all its subdirectories
13299 (recursively), are source directories.
13300
13301 @smallexample @c projectfile
13302    for Source_Dirs use ("/system/sources/**");
13303 @end smallexample
13304
13305 @noindent
13306 Here the directory @code{/system/sources} and all of its subdirectories
13307 (recursively) are source directories.
13308
13309 To specify that the source directories are the directory of the project file
13310 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
13311 @smallexample @c projectfile
13312    for Source_Dirs use ("./**");
13313 @end smallexample
13314
13315 @noindent
13316 Each of the source directories must exist and be readable.
13317
13318 @node Source File Names
13319 @subsection Source File Names
13320
13321 @noindent
13322 In a project that contains source files, their names may be specified by the
13323 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
13324 (a string). Source file names never include any directory information.
13325
13326 If the attribute @code{Source_Files} is given an explicit value, then each
13327 element of the list is a source file name.
13328
13329 @smallexample @c projectfile
13330    for Source_Files use ("main.adb");
13331    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
13332 @end smallexample
13333
13334 @noindent
13335 If the attribute @code{Source_Files} is not given an explicit value,
13336 but the attribute @code{Source_List_File} is given a string value,
13337 then the source file names are contained in the text file whose path name
13338 (absolute or relative to the directory of the project file) is the
13339 value of the attribute @code{Source_List_File}.
13340
13341 Each line in the file that is not empty or is not a comment
13342 contains a source file name.
13343
13344 @smallexample @c projectfile
13345    for Source_List_File use "source_list.txt";
13346 @end smallexample
13347
13348 @noindent
13349 By default, if neither the attribute @code{Source_Files} nor the attribute
13350 @code{Source_List_File} is given an explicit value, then each file in the
13351 source directories that conforms to the project's naming scheme
13352 (@pxref{Naming Schemes}) is an immediate source of the project.
13353
13354 A warning is issued if both attributes @code{Source_Files} and
13355 @code{Source_List_File} are given explicit values. In this case, the attribute
13356 @code{Source_Files} prevails.
13357
13358 Each source file name must be the name of one existing source file
13359 in one of the source directories.
13360
13361 A @code{Source_Files} attribute whose value is an empty list
13362 indicates that there are no source files in the project.
13363
13364 If the order of the source directories is known statically, that is if
13365 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13366 be several files with the same source file name. In this case, only the file
13367 in the first directory is considered as an immediate source of the project
13368 file. If the order of the source directories is not known statically, it is
13369 an error to have several files with the same source file name.
13370
13371 Projects can be specified to have no Ada source
13372 files: the value of @code{Source_Dirs} or @code{Source_Files} may be an empty
13373 list, or the @code{"Ada"} may be absent from @code{Languages}:
13374
13375 @smallexample @c projectfile
13376    for Source_Dirs use ();
13377    for Source_Files use ();
13378    for Languages use ("C", "C++");
13379 @end smallexample
13380
13381 @noindent
13382 Otherwise, a project must contain at least one immediate source.
13383
13384 Projects with no source files are useful as template packages
13385 (@pxref{Packages in Project Files}) for other projects; in particular to
13386 define a package @code{Naming} (@pxref{Naming Schemes}).
13387
13388 @c ****************************
13389 @c * Importing Projects *
13390 @c ****************************
13391
13392 @node  Importing Projects
13393 @section Importing Projects
13394 @cindex @code{ADA_PROJECT_PATH}
13395 @cindex @code{GPR_PROJECT_PATH}
13396
13397 @noindent
13398 An immediate source of a project P may depend on source files that
13399 are neither immediate sources of P nor in the predefined library.
13400 To get this effect, P must @emph{import} the projects that contain the needed
13401 source files.
13402
13403 @smallexample @c projectfile
13404 @group
13405   with "project1", "utilities.gpr";
13406   with "/namings/apex.gpr";
13407   project Main is
13408     @dots{}
13409 @end group
13410 @end smallexample
13411
13412 @noindent
13413 As can be seen in this example, the syntax for importing projects is similar
13414 to the syntax for importing compilation units in Ada. However, project files
13415 use literal strings instead of names, and the @code{with} clause identifies
13416 project files rather than packages.
13417
13418 Each literal string is the file name or path name (absolute or relative) of a
13419 project file. If a string corresponds to a file name, with no path or a
13420 relative path, then its location is determined by the @emph{project path}. The
13421 latter can be queried using @code{gnatls -v}. It contains:
13422
13423 @itemize @bullet
13424 @item
13425 In first position, the directory containing the current project file.
13426 @item
13427 In last position, the default project directory. This default project directory
13428 is part of the GNAT installation and is the standard place to install project
13429 files giving access to standard support libraries.
13430 @ifclear vms
13431 @ref{Installing a library}
13432 @end ifclear
13433
13434 @item
13435 In between, all the directories referenced in the
13436 ^environment variables^logical names^ @env{GPR_PROJECT_PATH}
13437 and @env{ADA_PROJECT_PATH} if they exist, and in that order.
13438 @end itemize
13439
13440 @noindent
13441 If a relative pathname is used, as in
13442
13443 @smallexample @c projectfile
13444   with "tests/proj";
13445 @end smallexample
13446
13447 @noindent
13448 then the full path for the project is constructed by concatenating this
13449 relative path to those in the project path, in order, until a matching file is
13450 found. Any symbolic link will be fully resolved in the directory of the
13451 importing project file before the imported project file is examined.
13452
13453 If the @code{with}'ed project file name does not have an extension,
13454 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13455 then the file name as specified in the @code{with} clause (no extension) will
13456 be used. In the above example, if a file @code{project1.gpr} is found, then it
13457 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13458 then it will be used; if neither file exists, this is an error.
13459
13460 A warning is issued if the name of the project file does not match the
13461 name of the project; this check is case insensitive.
13462
13463 Any source file that is an immediate source of the imported project can be
13464 used by the immediate sources of the importing project, transitively. Thus
13465 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13466 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13467 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13468 because if and when @code{B} ceases to import @code{C}, some sources in
13469 @code{A} will no longer compile.
13470
13471 A side effect of this capability is that normally cyclic dependencies are not
13472 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13473 is not allowed to import @code{A}. However, there are cases when cyclic
13474 dependencies would be beneficial. For these cases, another form of import
13475 between projects exists, the @code{limited with}: a project @code{A} that
13476 imports a project @code{B} with a straight @code{with} may also be imported,
13477 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13478 to @code{A} include at least one @code{limited with}.
13479
13480 @smallexample @c 0projectfile
13481 with "../b/b.gpr";
13482 with "../c/c.gpr";
13483 project A is
13484 end A;
13485
13486 limited with "../a/a.gpr";
13487 project B is
13488 end B;
13489
13490 with "../d/d.gpr";
13491 project C is
13492 end C;
13493
13494 limited with "../a/a.gpr";
13495 project D is
13496 end D;
13497 @end smallexample
13498
13499 @noindent
13500 In the above legal example, there are two project cycles:
13501 @itemize @bullet
13502 @item A-> B-> A
13503 @item A -> C -> D -> A
13504 @end itemize
13505
13506 @noindent
13507 In each of these cycle there is one @code{limited with}: import of @code{A}
13508 from @code{B} and import of @code{A} from @code{D}.
13509
13510 The difference between straight @code{with} and @code{limited with} is that
13511 the name of a project imported with a @code{limited with} cannot be used in the
13512 project that imports it. In particular, its packages cannot be renamed and
13513 its variables cannot be referred to.
13514
13515 An exception to the above rules for @code{limited with} is that for the main
13516 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13517 @code{limited with} is equivalent to a straight @code{with}. For example,
13518 in the example above, projects @code{B} and @code{D} could not be main
13519 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13520 each have a @code{limited with} that is the only one in a cycle of importing
13521 projects.
13522
13523 @c *********************
13524 @c * Project Extension *
13525 @c *********************
13526
13527 @node Project Extension
13528 @section Project Extension
13529
13530 @noindent
13531 During development of a large system, it is sometimes necessary to use
13532 modified versions of some of the source files, without changing the original
13533 sources. This can be achieved through the @emph{project extension} facility.
13534
13535 @smallexample @c projectfile
13536    project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13537 @end smallexample
13538
13539 @noindent
13540 A project extension declaration introduces an extending project
13541 (the @emph{child}) and a project being extended (the @emph{parent}).
13542
13543 By default, a child project inherits all the sources of its parent.
13544 However, inherited sources can be overridden: a unit in a parent is hidden
13545 by a unit of the same name in the child.
13546
13547 Inherited sources are considered to be sources (but not immediate sources)
13548 of the child project; see @ref{Project File Syntax}.
13549
13550 An inherited source file retains any switches specified in the parent project.
13551
13552 For example if the project @code{Utilities} contains the spec and the
13553 body of an Ada package @code{Util_IO}, then the project
13554 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13555 The original body of @code{Util_IO} will not be considered in program builds.
13556 However, the package spec will still be found in the project
13557 @code{Utilities}.
13558
13559 A child project can have only one parent, except when it is qualified as
13560 abstract. But it may import any number of other projects.
13561
13562 A project is not allowed to import directly or indirectly at the same time a
13563 child project and any of its ancestors.
13564
13565 @c *******************************
13566 @c * Project Hierarchy Extension *
13567 @c *******************************
13568
13569 @node Project Hierarchy Extension
13570 @section Project Hierarchy Extension
13571
13572 @noindent
13573 When extending a large system spanning multiple projects, it is often
13574 inconvenient to extend every project in the hierarchy that is impacted by a
13575 small change introduced. In such cases, it is possible to create a virtual
13576 extension of entire hierarchy using @code{extends all} relationship.
13577
13578 When the project is extended using @code{extends all} inheritance, all projects
13579 that are imported by it, both directly and indirectly, are considered virtually
13580 extended. That is, the Project Manager creates "virtual projects"
13581 that extend every project in the hierarchy; all these virtual projects have
13582 no sources of their own and have as object directory the object directory of
13583 the root of "extending all" project.
13584
13585 It is possible to explicitly extend one or more projects in the hierarchy
13586 in order to modify the sources. These extending projects must be imported by
13587 the "extending all" project, which will replace the corresponding virtual
13588 projects with the explicit ones.
13589
13590 When building such a project hierarchy extension, the Project Manager will
13591 ensure that both modified sources and sources in virtual extending projects
13592 that depend on them, are recompiled.
13593
13594 By means of example, consider the following hierarchy of projects.
13595
13596 @enumerate
13597 @item
13598 project A, containing package P1
13599 @item
13600 project B importing A and containing package P2 which depends on P1
13601 @item
13602 project C importing B and containing package P3 which depends on P2
13603 @end enumerate
13604
13605 @noindent
13606 We want to modify packages P1 and P3.
13607
13608 This project hierarchy will need to be extended as follows:
13609
13610 @enumerate
13611 @item
13612 Create project A1 that extends A, placing modified P1 there:
13613
13614 @smallexample @c 0projectfile
13615 project A1 extends "(@dots{})/A" is
13616 end A1;
13617 @end smallexample
13618
13619 @item
13620 Create project C1 that "extends all" C and imports A1, placing modified
13621 P3 there:
13622
13623 @smallexample @c 0projectfile
13624 with "(@dots{})/A1";
13625 project C1 extends all "(@dots{})/C" is
13626 end C1;
13627 @end smallexample
13628 @end enumerate
13629
13630 When you build project C1, your entire modified project space will be
13631 recompiled, including the virtual project B1 that has been impacted by the
13632 "extending all" inheritance of project C.
13633
13634 Note that if a Library Project in the hierarchy is virtually extended,
13635 the virtual project that extends the Library Project is not a Library Project.
13636
13637 @c ****************************************
13638 @c * External References in Project Files *
13639 @c ****************************************
13640
13641 @node  External References in Project Files
13642 @section External References in Project Files
13643
13644 @noindent
13645 A project file may contain references to external variables; such references
13646 are called @emph{external references}.
13647
13648 An external variable is either defined as part of the environment (an
13649 environment variable in Unix, for example) or else specified on the command
13650 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13651 If both, then the command line value is used.
13652
13653 The value of an external reference is obtained by means of the built-in
13654 function @code{external}, which returns a string value.
13655 This function has two forms:
13656 @itemize @bullet
13657 @item @code{external (external_variable_name)}
13658 @item @code{external (external_variable_name, default_value)}
13659 @end itemize
13660
13661 @noindent
13662 Each parameter must be a string literal.  For example:
13663
13664 @smallexample @c projectfile
13665    external ("USER")
13666    external ("OS", "GNU/Linux")
13667 @end smallexample
13668
13669 @noindent
13670 In the form with one parameter, the function returns the value of
13671 the external variable given as parameter. If this name is not present in the
13672 environment, the function returns an empty string.
13673
13674 In the form with two string parameters, the second argument is
13675 the value returned when the variable given as the first argument is not
13676 present in the environment. In the example above, if @code{"OS"} is not
13677 the name of ^an environment variable^a logical name^ and is not passed on
13678 the command line, then the returned value is @code{"GNU/Linux"}.
13679
13680 An external reference may be part of a string expression or of a string
13681 list expression, and can therefore appear in a variable declaration or
13682 an attribute declaration.
13683
13684 @smallexample @c projectfile
13685 @group
13686    type Mode_Type is ("Debug", "Release");
13687    Mode : Mode_Type := external ("MODE");
13688    case Mode is
13689      when "Debug" =>
13690         @dots{}
13691 @end group
13692 @end smallexample
13693
13694 @c *****************************
13695 @c * Packages in Project Files *
13696 @c *****************************
13697
13698 @node  Packages in Project Files
13699 @section Packages in Project Files
13700
13701 @noindent
13702 A @emph{package} defines the settings for project-aware tools within a
13703 project.
13704 For each such tool one can declare a package; the names for these
13705 packages are preset (@pxref{Packages}).
13706 A package may contain variable declarations, attribute declarations, and case
13707 constructions.
13708
13709 @smallexample @c projectfile
13710 @group
13711    project Proj is
13712       package Builder is  -- used by gnatmake
13713          for ^Default_Switches^Default_Switches^ ("Ada")
13714              use ("^-v^-v^",
13715                   "^-g^-g^");
13716       end Builder;
13717    end Proj;
13718 @end group
13719 @end smallexample
13720
13721 @noindent
13722 The syntax of package declarations mimics that of package in Ada.
13723
13724 Most of the packages have an attribute
13725 @code{^Default_Switches^Default_Switches^}.
13726 This attribute is an associative array, and its value is a string list.
13727 The index of the associative array is the name of a programming language (case
13728 insensitive). This attribute indicates the ^switch^switch^
13729 or ^switches^switches^ to be used
13730 with the corresponding tool.
13731
13732 Some packages also have another attribute, @code{^Switches^Switches^},
13733 an associative array whose value is a string list.
13734 The index is the name of a source file.
13735 This attribute indicates the ^switch^switch^
13736 or ^switches^switches^ to be used by the corresponding
13737 tool when dealing with this specific file.
13738
13739 Further information on these ^switch^switch^-related attributes is found in
13740 @ref{^Switches^Switches^ and Project Files}.
13741
13742 A package may be declared as a @emph{renaming} of another package; e.g., from
13743 the project file for an imported project.
13744
13745 @smallexample @c projectfile
13746 @group
13747   with "/global/apex.gpr";
13748   project Example is
13749     package Naming renames Apex.Naming;
13750     @dots{}
13751   end Example;
13752 @end group
13753 @end smallexample
13754
13755 @noindent
13756 Packages that are renamed in other project files often come from project files
13757 that have no sources: they are just used as templates. Any modification in the
13758 template will be reflected automatically in all the project files that rename
13759 a package from the template.
13760
13761 In addition to the tool-oriented packages, you can also declare a package
13762 named @code{Naming} to establish specialized source file naming conventions
13763 (@pxref{Naming Schemes}).
13764
13765 @c ************************************
13766 @c * Variables from Imported Projects *
13767 @c ************************************
13768
13769 @node Variables from Imported Projects
13770 @section Variables from Imported Projects
13771
13772 @noindent
13773 An attribute or variable defined in an imported or parent project can
13774 be used in expressions in the importing / extending project.
13775 Such an attribute or variable is denoted by an expanded name whose prefix
13776 is either the name of the project or the expanded name of a package within
13777 a project.
13778
13779 @smallexample @c projectfile
13780 @group
13781   with "imported";
13782   project Main extends "base" is
13783      Var1 := Imported.Var;
13784      Var2 := Base.Var & ".new";
13785 @end group
13786
13787 @group
13788      package Builder is
13789         for ^Default_Switches^Default_Switches^ ("Ada")
13790             use Imported.Builder'Ada_^Switches^Switches^ &
13791                 "^-gnatg^-gnatg^" &
13792                 "^-v^-v^";
13793      end Builder;
13794 @end group
13795
13796 @group
13797      package Compiler is
13798         for ^Default_Switches^Default_Switches^ ("Ada")
13799             use Base.Compiler'Ada_^Switches^Switches^;
13800      end Compiler;
13801   end Main;
13802 @end group
13803 @end smallexample
13804
13805 @noindent
13806 In this example:
13807
13808 @itemize @bullet
13809 @item
13810 The value of @code{Var1} is a copy of the variable @code{Var} defined
13811 in the project file @file{"imported.gpr"}
13812 @item
13813 the value of @code{Var2} is a copy of the value of variable @code{Var}
13814 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13815 @item
13816 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13817 @code{Builder} is a string list that includes in its value a copy of the value
13818 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13819 in project file @file{imported.gpr} plus two new elements:
13820 @option{"^-gnatg^-gnatg^"}
13821 and @option{"^-v^-v^"};
13822 @item
13823 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13824 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13825 defined in the @code{Compiler} package in project file @file{base.gpr},
13826 the project being extended.
13827 @end itemize
13828
13829 @c ******************
13830 @c * Naming Schemes *
13831 @c ******************
13832
13833 @node  Naming Schemes
13834 @section Naming Schemes
13835
13836 @noindent
13837 Sometimes an Ada software system is ported from a foreign compilation
13838 environment to GNAT, and the file names do not use the default GNAT
13839 conventions. Instead of changing all the file names (which for a variety
13840 of reasons might not be possible), you can define the relevant file
13841 naming scheme in the @code{Naming} package in your project file.
13842
13843 @noindent
13844 Note that the use of pragmas described in
13845 @ref{Alternative File Naming Schemes} by mean of a configuration
13846 pragmas file is not supported when using project files. You must use
13847 the features described in this paragraph. You can however use specify
13848 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13849
13850 @ifclear vms
13851 For example, the following
13852 package models the Apex file naming rules:
13853
13854 @smallexample @c projectfile
13855 @group
13856   package Naming is
13857     for Casing               use "lowercase";
13858     for Dot_Replacement      use ".";
13859     for Spec_Suffix ("Ada")  use ".1.ada";
13860     for Body_Suffix ("Ada")  use ".2.ada";
13861   end Naming;
13862 @end group
13863 @end smallexample
13864 @end ifclear
13865
13866 @ifset vms
13867 For example, the following package models the HP Ada file naming rules:
13868
13869 @smallexample @c projectfile
13870 @group
13871   package Naming is
13872     for Casing               use "lowercase";
13873     for Dot_Replacement      use "__";
13874     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
13875     for Body_Suffix ("Ada")  use ".^ada^ada^";
13876   end Naming;
13877 @end group
13878 @end smallexample
13879
13880 @noindent
13881 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13882 names in lower case)
13883 @end ifset
13884
13885 @noindent
13886 You can define the following attributes in package @code{Naming}:
13887
13888 @table @code
13889
13890 @item @code{Casing}
13891 This must be a string with one of the three values @code{"lowercase"},
13892 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13893
13894 @noindent
13895 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13896
13897 @item @code{Dot_Replacement}
13898 This must be a string whose value satisfies the following conditions:
13899
13900 @itemize @bullet
13901 @item It must not be empty
13902 @item It cannot start or end with an alphanumeric character
13903 @item It cannot be a single underscore
13904 @item It cannot start with an underscore followed by an alphanumeric
13905 @item It cannot contain a dot @code{'.'} except if the entire string
13906 is @code{"."}
13907 @end itemize
13908
13909 @noindent
13910 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13911
13912 @item @code{Spec_Suffix}
13913 This is an associative array (indexed by the programming language name, case
13914 insensitive) whose value is a string that must satisfy the following
13915 conditions:
13916
13917 @itemize @bullet
13918 @item It must not be empty
13919 @item It must include at least one dot
13920 @end itemize
13921 @noindent
13922 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13923 @code{"^.ads^.ADS^"}.
13924
13925 @item @code{Body_Suffix}
13926 This is an associative array (indexed by the programming language name, case
13927 insensitive) whose value is a string that must satisfy the following
13928 conditions:
13929
13930 @itemize @bullet
13931 @item It must not be empty
13932 @item It must include at least one dot
13933 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13934 @end itemize
13935 @noindent
13936 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13937 same string, then a file name that ends with the longest of these two suffixes
13938 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13939 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13940
13941 If the suffix does not start with a '.', a file with a name exactly equal
13942 to the suffix will also be part of the project (for instance if you define
13943 the suffix as @code{Makefile}, a file called @file{Makefile} will be part
13944 of the project. This is not interesting in general when using projects to
13945 compile. However, it might become useful when a project is also used to
13946 find the list of source files in an editor, like the GNAT Programming System
13947 (GPS).
13948
13949 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13950 @code{"^.adb^.ADB^"}.
13951
13952 @item @code{Separate_Suffix}
13953 This must be a string whose value satisfies the same conditions as
13954 @code{Body_Suffix}. The same "longest suffix" rules apply.
13955
13956 @noindent
13957 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13958 value as @code{Body_Suffix ("Ada")}.
13959
13960 @item @code{Spec}
13961 @noindent
13962 You can use the associative array attribute @code{Spec}  to define
13963 the source file name for an individual Ada compilation unit's spec. The array
13964 index must be a string literal that identifies the Ada unit (case insensitive).
13965 The value of this attribute must be a string that identifies the file that
13966 contains this unit's spec (case sensitive or insensitive depending on the
13967 operating system).
13968
13969 @smallexample @c projectfile
13970    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13971 @end smallexample
13972
13973 When the source file contains several units, you can indicate at what
13974 position the unit occurs in the file, with the following. The first unit
13975 in the file has index 1
13976
13977 @smallexample @c projectfile
13978   for Body ("top") use "foo.a" at 1;
13979   for Body ("foo") use "foo.a" at 2;
13980 @end smallexample
13981
13982 @item @code{Body}
13983
13984 You can use the associative array attribute @code{Body} to
13985 define the source file name for an individual Ada compilation unit's body
13986 (possibly a subunit).  The array index must be a string literal that identifies
13987 the Ada unit (case insensitive).  The value of this attribute must be a string
13988 that identifies the file that contains this unit's body or subunit (case
13989 sensitive or insensitive depending on the operating system).
13990
13991 @smallexample @c projectfile
13992    for Body ("MyPack.MyChild") use "mypack.mychild.body";
13993 @end smallexample
13994 @end table
13995
13996 @c ********************
13997 @c * Library Projects *
13998 @c ********************
13999
14000 @node Library Projects
14001 @section Library Projects
14002
14003 @noindent
14004 @emph{Library projects} are projects whose object code is placed in a library.
14005 (Note that this facility is not yet supported on all platforms).
14006
14007 @code{gnatmake} or @code{gprbuild} will collect all object files into a
14008 single archive, which might either be a shared or a static library. This
14009 library can later on be linked with multiple executables, potentially
14010 reducing their sizes.
14011
14012 If your project file specifies languages other than Ada, but you are still
14013 using @code{gnatmake} to compile and link, the latter will not try to
14014 compile your sources other than Ada (you should use @code{gprbuild} if that
14015 is your intent). However, @code{gnatmake} will automatically link all object
14016 files found in the object directory, whether or not they were compiled from
14017 an Ada source file. This specific behavior only applies when multiple
14018 languages are specified.
14019
14020 To create a library project, you need to define in its project file
14021 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
14022 Additionally, you may define other library-related attributes such as
14023 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
14024 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
14025
14026 The @code{Library_Name} attribute has a string value. There is no restriction
14027 on the name of a library. It is the responsibility of the developer to
14028 choose a name that will be accepted by the platform. It is recommended to
14029 choose names that could be Ada identifiers; such names are almost guaranteed
14030 to be acceptable on all platforms.
14031
14032 The @code{Library_Dir} attribute has a string value that designates the path
14033 (absolute or relative) of the directory where the library will reside.
14034 It must designate an existing directory, and this directory must be writable,
14035 different from the project's object directory and from any source directory
14036 in the project tree.
14037
14038 If both @code{Library_Name} and @code{Library_Dir} are specified and
14039 are legal, then the project file defines a library project.  The optional
14040 library-related attributes are checked only for such project files.
14041
14042 The @code{Library_Kind} attribute has a string value that must be one of the
14043 following (case insensitive): @code{"static"}, @code{"dynamic"} or
14044 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
14045 attribute is not specified, the library is a static library, that is
14046 an archive of object files that can be potentially linked into a
14047 static executable. Otherwise, the library may be dynamic or
14048 relocatable, that is a library that is loaded only at the start of execution.
14049
14050 If you need to build both a static and a dynamic library, you should use two
14051 different object directories, since in some cases some extra code needs to
14052 be generated for the latter. For such cases, it is recommended to either use
14053 two different project files, or a single one which uses external variables
14054 to indicate what kind of library should be build.
14055
14056 The @code{Library_ALI_Dir} attribute may be specified to indicate the
14057 directory where the ALI files of the library will be copied. When it is
14058 not specified, the ALI files are copied to the directory specified in
14059 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
14060 must be writable and different from the project's object directory and from
14061 any source directory in the project tree.
14062
14063 The @code{Library_Version} attribute has a string value whose interpretation
14064 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
14065 used only for dynamic/relocatable libraries as the internal name of the
14066 library (the @code{"soname"}). If the library file name (built from the
14067 @code{Library_Name}) is different from the @code{Library_Version}, then the
14068 library file will be a symbolic link to the actual file whose name will be
14069 @code{Library_Version}.
14070
14071 Example (on Unix):
14072
14073 @smallexample @c projectfile
14074 @group
14075 project Plib is
14076
14077    Version := "1";
14078
14079    for Library_Dir use "lib_dir";
14080    for Library_Name use "dummy";
14081    for Library_Kind use "relocatable";
14082    for Library_Version use "libdummy.so." & Version;
14083
14084 end Plib;
14085 @end group
14086 @end smallexample
14087
14088 @noindent
14089 Directory @file{lib_dir} will contain the internal library file whose name
14090 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
14091 @file{libdummy.so.1}.
14092
14093 When @command{gnatmake} detects that a project file
14094 is a library project file, it will check all immediate sources of the project
14095 and rebuild the library if any of the sources have been recompiled.
14096
14097 Standard project files can import library project files. In such cases,
14098 the libraries will only be rebuilt if some of its sources are recompiled
14099 because they are in the closure of some other source in an importing project.
14100 Sources of the library project files that are not in such a closure will
14101 not be checked, unless the full library is checked, because one of its sources
14102 needs to be recompiled.
14103
14104 For instance, assume the project file @code{A} imports the library project file
14105 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
14106 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
14107 @file{l2.ads}, @file{l2.adb}.
14108
14109 If @file{l1.adb} has been modified, then the library associated with @code{L}
14110 will be rebuilt when compiling all the immediate sources of @code{A} only
14111 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
14112 @code{"with L1;"}.
14113
14114 To be sure that all the sources in the library associated with @code{L} are
14115 up to date, and that all the sources of project @code{A} are also up to date,
14116 the following two commands needs to be used:
14117
14118 @smallexample
14119 gnatmake -Pl.gpr
14120 gnatmake -Pa.gpr
14121 @end smallexample
14122
14123 When a library is built or rebuilt, an attempt is made first to delete all
14124 files in the library directory.
14125 All @file{ALI} files will also be copied from the object directory to the
14126 library directory. To build executables, @command{gnatmake} will use the
14127 library rather than the individual object files.
14128
14129 @ifclear vms
14130 It is also possible to create library project files for third-party libraries
14131 that are precompiled and cannot be compiled locally thanks to the
14132 @code{externally_built} attribute. (See @ref{Installing a library}).
14133 @end ifclear
14134
14135 @c *******************************
14136 @c * Stand-alone Library Projects *
14137 @c *******************************
14138
14139 @node Stand-alone Library Projects
14140 @section Stand-alone Library Projects
14141
14142 @noindent
14143 A Stand-alone Library is a library that contains the necessary code to
14144 elaborate the Ada units that are included in the library. A Stand-alone
14145 Library is suitable to be used in an executable when the main is not
14146 in Ada. However, Stand-alone Libraries may also be used with an Ada main
14147 subprogram.
14148
14149 A Stand-alone Library Project is a Library Project where the library is
14150 a Stand-alone Library.
14151
14152 To be a Stand-alone Library Project, in addition to the two attributes
14153 that make a project a Library Project (@code{Library_Name} and
14154 @code{Library_Dir}, see @ref{Library Projects}), the attribute
14155 @code{Library_Interface} must be defined.
14156
14157 @smallexample @c projectfile
14158 @group
14159    for Library_Dir use "lib_dir";
14160    for Library_Name use "dummy";
14161    for Library_Interface use ("int1", "int1.child");
14162 @end group
14163 @end smallexample
14164
14165 Attribute @code{Library_Interface} has a nonempty string list value,
14166 each string in the list designating a unit contained in an immediate source
14167 of the project file.
14168
14169 When a Stand-alone Library is built, first the binder is invoked to build
14170 a package whose name depends on the library name
14171 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
14172 This binder-generated package includes initialization and
14173 finalization procedures whose
14174 names depend on the library name (dummyinit and dummyfinal in the example
14175 above). The object corresponding to this package is included in the library.
14176
14177 A dynamic or relocatable Stand-alone Library is automatically initialized
14178 if automatic initialization of Stand-alone Libraries is supported on the
14179 platform and if attribute @code{Library_Auto_Init} is not specified or
14180 is specified with the value "true". A static Stand-alone Library is never
14181 automatically initialized.
14182
14183 Single string attribute @code{Library_Auto_Init} may be specified with only
14184 two possible values: "false" or "true" (case-insensitive). Specifying
14185 "false" for attribute @code{Library_Auto_Init} will prevent automatic
14186 initialization of dynamic or relocatable libraries.
14187
14188 When a non-automatically initialized Stand-alone Library is used
14189 in an executable, its initialization procedure must be called before
14190 any service of the library is used.
14191 When the main subprogram is in Ada, it may mean that the initialization
14192 procedure has to be called during elaboration of another package.
14193
14194 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
14195 (those that are listed in attribute @code{Library_Interface}) are copied to
14196 the Library Directory. As a consequence, only the Interface Units may be
14197 imported from Ada units outside of the library. If other units are imported,
14198 the binding phase will fail.
14199
14200 When a Stand-Alone Library is bound, the switches that are specified in
14201 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
14202 used in the call to @command{gnatbind}.
14203
14204 The string list attribute @code{Library_Options} may be used to specified
14205 additional switches to the call to @command{gcc} to link the library.
14206
14207 The attribute @code{Library_Src_Dir}, may be specified for a
14208 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
14209 single string value. Its value must be the path (absolute or relative to the
14210 project directory) of an existing directory. This directory cannot be the
14211 object directory or one of the source directories, but it can be the same as
14212 the library directory. The sources of the Interface
14213 Units of the library, necessary to an Ada client of the library, will be
14214 copied to the designated directory, called Interface Copy directory.
14215 These sources includes the specs of the Interface Units, but they may also
14216 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
14217 are used, or when there is a generic units in the spec. Before the sources
14218 are copied to the Interface Copy directory, an attempt is made to delete all
14219 files in the Interface Copy directory.
14220
14221 @c *************************************
14222 @c * Switches Related to Project Files *
14223 @c *************************************
14224 @node Switches Related to Project Files
14225 @section Switches Related to Project Files
14226
14227 @noindent
14228 The following switches are used by GNAT tools that support project files:
14229
14230 @table @option
14231
14232 @item ^-P^/PROJECT_FILE=^@var{project}
14233 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
14234 Indicates the name of a project file. This project file will be parsed with
14235 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
14236 if any, and using the external references indicated
14237 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
14238 @ifclear vms
14239 There may zero, one or more spaces between @option{-P} and @var{project}.
14240 @end ifclear
14241
14242 @noindent
14243 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
14244
14245 @noindent
14246 Since the Project Manager parses the project file only after all the switches
14247 on the command line are checked, the order of the switches
14248 @option{^-P^/PROJECT_FILE^},
14249 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
14250 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
14251
14252 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
14253 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
14254 Indicates that external variable @var{name} has the value @var{value}.
14255 The Project Manager will use this value for occurrences of
14256 @code{external(name)} when parsing the project file.
14257
14258 @ifclear vms
14259 @noindent
14260 If @var{name} or @var{value} includes a space, then @var{name=value} should be
14261 put between quotes.
14262 @smallexample
14263   -XOS=NT
14264   -X"user=John Doe"
14265 @end smallexample
14266 @end ifclear
14267
14268 @noindent
14269 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
14270 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
14271 @var{name}, only the last one is used.
14272
14273 @noindent
14274 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
14275 takes precedence over the value of the same name in the environment.
14276
14277 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
14278 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
14279 Indicates the verbosity of the parsing of GNAT project files.
14280
14281 @ifclear vms
14282 @option{-vP0} means Default;
14283 @option{-vP1} means Medium;
14284 @option{-vP2} means High.
14285 @end ifclear
14286
14287 @ifset vms
14288 There are three possible options for this qualifier: DEFAULT, MEDIUM and
14289 HIGH.
14290 @end ifset
14291
14292 @noindent
14293 The default is ^Default^DEFAULT^: no output for syntactically correct
14294 project files.
14295 @noindent
14296 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
14297 only the last one is used.
14298
14299 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
14300 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
14301 Add directory <dir> at the beginning of the project search path, in order,
14302 after the current working directory.
14303
14304 @ifclear vms
14305 @item -eL
14306 @cindex @option{-eL} (any project-aware tool)
14307 Follow all symbolic links when processing project files.
14308 @end ifclear
14309
14310 @item ^--subdirs^/SUBDIRS^=<subdir>
14311 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
14312 This switch is recognized by gnatmake and gnatclean. It indicate that the real
14313 directories (except the source directories) are the subdirectories <subdir>
14314 of the directories specified in the project files. This applies in particular
14315 to object directories, library directories and exec directories. If the
14316 subdirectories do not exist, they are created automatically.
14317
14318 @end table
14319
14320 @c **********************************
14321 @c * Tools Supporting Project Files *
14322 @c **********************************
14323
14324 @node  Tools Supporting Project Files
14325 @section Tools Supporting Project Files
14326
14327 @menu
14328 * gnatmake and Project Files::
14329 * The GNAT Driver and Project Files::
14330 @end menu
14331
14332 @node gnatmake and Project Files
14333 @subsection gnatmake and Project Files
14334
14335 @noindent
14336 This section covers several topics related to @command{gnatmake} and
14337 project files: defining ^switches^switches^ for @command{gnatmake}
14338 and for the tools that it invokes; specifying configuration pragmas;
14339 the use of the @code{Main} attribute; building and rebuilding library project
14340 files.
14341
14342 @menu
14343 * ^Switches^Switches^ and Project Files::
14344 * Specifying Configuration Pragmas::
14345 * Project Files and Main Subprograms::
14346 * Library Project Files::
14347 @end menu
14348
14349 @node ^Switches^Switches^ and Project Files
14350 @subsubsection ^Switches^Switches^ and Project Files
14351
14352 @ifset vms
14353 It is not currently possible to specify VMS style qualifiers in the project
14354 files; only Unix style ^switches^switches^ may be specified.
14355 @end ifset
14356
14357 @noindent
14358 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14359 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14360 attribute, a @code{^Switches^Switches^} attribute, or both;
14361 as their names imply, these ^switch^switch^-related
14362 attributes affect the ^switches^switches^ that are used for each of these GNAT
14363 components when
14364 @command{gnatmake} is invoked.  As will be explained below, these
14365 component-specific ^switches^switches^ precede
14366 the ^switches^switches^ provided on the @command{gnatmake} command line.
14367
14368 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14369 array indexed by language name (case insensitive) whose value is a string list.
14370 For example:
14371
14372 @smallexample @c projectfile
14373 @group
14374 package Compiler is
14375   for ^Default_Switches^Default_Switches^ ("Ada")
14376       use ("^-gnaty^-gnaty^",
14377            "^-v^-v^");
14378 end Compiler;
14379 @end group
14380 @end smallexample
14381
14382 @noindent
14383 The @code{^Switches^Switches^} attribute is also an associative array,
14384 indexed by a file name (which may or may not be case sensitive, depending
14385 on the operating system) whose value is a string list.  For example:
14386
14387 @smallexample @c projectfile
14388 @group
14389 package Builder is
14390    for ^Switches^Switches^ ("main1.adb")
14391        use ("^-O2^-O2^");
14392    for ^Switches^Switches^ ("main2.adb")
14393        use ("^-g^-g^");
14394 end Builder;
14395 @end group
14396 @end smallexample
14397
14398 @noindent
14399 For the @code{Builder} package, the file names must designate source files
14400 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
14401 file names must designate @file{ALI} or source files for main subprograms.
14402 In each case just the file name without an explicit extension is acceptable.
14403
14404 For each tool used in a program build (@command{gnatmake}, the compiler, the
14405 binder, and the linker), the corresponding package @dfn{contributes} a set of
14406 ^switches^switches^ for each file on which the tool is invoked, based on the
14407 ^switch^switch^-related attributes defined in the package.
14408 In particular, the ^switches^switches^
14409 that each of these packages contributes for a given file @var{f} comprise:
14410
14411 @itemize @bullet
14412 @item
14413 the value of attribute @code{^Switches^Switches^ (@var{f})},
14414 if it is specified in the package for the given file,
14415 @item
14416 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14417 if it is specified in the package.
14418 @end itemize
14419
14420 @noindent
14421 If neither of these attributes is defined in the package, then the package does
14422 not contribute any ^switches^switches^ for the given file.
14423
14424 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14425 two sets, in the following order: those contributed for the file
14426 by the @code{Builder} package;
14427 and the switches passed on the command line.
14428
14429 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14430 the ^switches^switches^ passed to the tool comprise three sets,
14431 in the following order:
14432
14433 @enumerate
14434 @item
14435 the applicable ^switches^switches^ contributed for the file
14436 by the @code{Builder} package in the project file supplied on the command line;
14437
14438 @item
14439 those contributed for the file by the package (in the relevant project file --
14440 see below) corresponding to the tool; and
14441
14442 @item
14443 the applicable switches passed on the command line.
14444 @end enumerate
14445
14446 @noindent
14447 The term @emph{applicable ^switches^switches^} reflects the fact that
14448 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14449 tools, depending on the individual ^switch^switch^.
14450
14451 @command{gnatmake} may invoke the compiler on source files from different
14452 projects. The Project Manager will use the appropriate project file to
14453 determine the @code{Compiler} package for each source file being compiled.
14454 Likewise for the @code{Binder} and @code{Linker} packages.
14455
14456 As an example, consider the following package in a project file:
14457
14458 @smallexample @c projectfile
14459 @group
14460 project Proj1 is
14461    package Compiler is
14462       for ^Default_Switches^Default_Switches^ ("Ada")
14463           use ("^-g^-g^");
14464       for ^Switches^Switches^ ("a.adb")
14465           use ("^-O1^-O1^");
14466       for ^Switches^Switches^ ("b.adb")
14467           use ("^-O2^-O2^",
14468                "^-gnaty^-gnaty^");
14469    end Compiler;
14470 end Proj1;
14471 @end group
14472 @end smallexample
14473
14474 @noindent
14475 If @command{gnatmake} is invoked with this project file, and it needs to
14476 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14477 @file{a.adb} will be compiled with the ^switch^switch^
14478 @option{^-O1^-O1^},
14479 @file{b.adb} with ^switches^switches^
14480 @option{^-O2^-O2^}
14481 and @option{^-gnaty^-gnaty^},
14482 and @file{c.adb} with @option{^-g^-g^}.
14483
14484 The following example illustrates the ordering of the ^switches^switches^
14485 contributed by different packages:
14486
14487 @smallexample @c projectfile
14488 @group
14489 project Proj2 is
14490    package Builder is
14491       for ^Switches^Switches^ ("main.adb")
14492           use ("^-g^-g^",
14493                "^-O1^-)1^",
14494                "^-f^-f^");
14495    end Builder;
14496 @end group
14497
14498 @group
14499    package Compiler is
14500       for ^Switches^Switches^ ("main.adb")
14501           use ("^-O2^-O2^");
14502    end Compiler;
14503 end Proj2;
14504 @end group
14505 @end smallexample
14506
14507 @noindent
14508 If you issue the command:
14509
14510 @smallexample
14511     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14512 @end smallexample
14513
14514 @noindent
14515 then the compiler will be invoked on @file{main.adb} with the following
14516 sequence of ^switches^switches^
14517
14518 @smallexample
14519    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14520 @end smallexample
14521
14522 with the last @option{^-O^-O^}
14523 ^switch^switch^ having precedence over the earlier ones;
14524 several other ^switches^switches^
14525 (such as @option{^-c^-c^}) are added implicitly.
14526
14527 The ^switches^switches^
14528 @option{^-g^-g^}
14529 and @option{^-O1^-O1^} are contributed by package
14530 @code{Builder},  @option{^-O2^-O2^} is contributed
14531 by the package @code{Compiler}
14532 and @option{^-O0^-O0^} comes from the command line.
14533
14534 The @option{^-g^-g^}
14535 ^switch^switch^ will also be passed in the invocation of
14536 @command{Gnatlink.}
14537
14538 A final example illustrates switch contributions from packages in different
14539 project files:
14540
14541 @smallexample @c projectfile
14542 @group
14543 project Proj3 is
14544    for Source_Files use ("pack.ads", "pack.adb");
14545    package Compiler is
14546       for ^Default_Switches^Default_Switches^ ("Ada")
14547           use ("^-gnata^-gnata^");
14548    end Compiler;
14549 end Proj3;
14550 @end group
14551
14552 @group
14553 with "Proj3";
14554 project Proj4 is
14555    for Source_Files use ("foo_main.adb", "bar_main.adb");
14556    package Builder is
14557       for ^Switches^Switches^ ("foo_main.adb")
14558           use ("^-s^-s^",
14559                "^-g^-g^");
14560    end Builder;
14561 end Proj4;
14562 @end group
14563
14564 @group
14565 -- Ada source file:
14566 with Pack;
14567 procedure Foo_Main is
14568    @dots{}
14569 end Foo_Main;
14570 @end group
14571 @end smallexample
14572
14573 If the command is
14574 @smallexample
14575 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14576 @end smallexample
14577
14578 @noindent
14579 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14580 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14581 @option{^-gnato^-gnato^} (passed on the command line).
14582 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14583 are @option{^-g^-g^} from @code{Proj4.Builder},
14584 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14585 and @option{^-gnato^-gnato^} from the command line.
14586
14587 @noindent
14588 When using @command{gnatmake} with project files, some ^switches^switches^ or
14589 arguments may be expressed as relative paths. As the working directory where
14590 compilation occurs may change, these relative paths are converted to absolute
14591 paths. For the ^switches^switches^ found in a project file, the relative paths
14592 are relative to the project file directory, for the switches on the command
14593 line, they are relative to the directory where @command{gnatmake} is invoked.
14594 The ^switches^switches^ for which this occurs are:
14595 ^-I^-I^,
14596 ^-A^-A^,
14597 ^-L^-L^,
14598 ^-aO^-aO^,
14599 ^-aL^-aL^,
14600 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14601 ^switch^switch^
14602 ^-o^-o^, object files specified in package @code{Linker} or after
14603 -largs on the command line). The exception to this rule is the ^switch^switch^
14604 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14605
14606 @node Specifying Configuration Pragmas
14607 @subsubsection Specifying Configuration Pragmas
14608
14609 When using @command{gnatmake} with project files, if there exists a file
14610 @file{gnat.adc} that contains configuration pragmas, this file will be
14611 ignored.
14612
14613 Configuration pragmas can be defined by means of the following attributes in
14614 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14615 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14616
14617 Both these attributes are single string attributes. Their values is the path
14618 name of a file containing configuration pragmas. If a path name is relative,
14619 then it is relative to the project directory of the project file where the
14620 attribute is defined.
14621
14622 When compiling a source, the configuration pragmas used are, in order,
14623 those listed in the file designated by attribute
14624 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14625 project file, if it is specified, and those listed in the file designated by
14626 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14627 the project file of the source, if it exists.
14628
14629 @node Project Files and Main Subprograms
14630 @subsubsection Project Files and Main Subprograms
14631
14632 @noindent
14633 When using a project file, you can invoke @command{gnatmake}
14634 with one or several main subprograms, by specifying their source files on the
14635 command line.
14636
14637 @smallexample
14638     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14639 @end smallexample
14640
14641 @noindent
14642 Each of these needs to be a source file of the same project, except
14643 when the switch ^-u^/UNIQUE^ is used.
14644
14645 @noindent
14646 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14647 same project, one of the project in the tree rooted at the project specified
14648 on the command line. The package @code{Builder} of this common project, the
14649 "main project" is the one that is considered by @command{gnatmake}.
14650
14651 @noindent
14652 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14653 imported directly or indirectly by the project specified on the command line.
14654 Note that if such a source file is not part of the project specified on the
14655 command line, the ^switches^switches^ found in package @code{Builder} of the
14656 project specified on the command line, if any, that are transmitted
14657 to the compiler will still be used, not those found in the project file of
14658 the source file.
14659
14660 @noindent
14661 When using a project file, you can also invoke @command{gnatmake} without
14662 explicitly specifying any main, and the effect depends on whether you have
14663 defined the @code{Main} attribute.  This attribute has a string list value,
14664 where each element in the list is the name of a source file (the file
14665 extension is optional) that contains a unit that can be a main subprogram.
14666
14667 If the @code{Main} attribute is defined in a project file as a non-empty
14668 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14669 line, then invoking @command{gnatmake} with this project file but without any
14670 main on the command line is equivalent to invoking @command{gnatmake} with all
14671 the file names in the @code{Main} attribute on the command line.
14672
14673 Example:
14674 @smallexample @c projectfile
14675 @group
14676    project Prj is
14677       for Main use ("main1", "main2", "main3");
14678    end Prj;
14679 @end group
14680 @end smallexample
14681
14682 @noindent
14683 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14684 is equivalent to
14685 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14686
14687 When the project attribute @code{Main} is not specified, or is specified
14688 as an empty string list, or when the switch @option{-u} is used on the command
14689 line, then invoking @command{gnatmake} with no main on the command line will
14690 result in all immediate sources of the project file being checked, and
14691 potentially recompiled. Depending on the presence of the switch @option{-u},
14692 sources from other project files on which the immediate sources of the main
14693 project file depend are also checked and potentially recompiled. In other
14694 words, the @option{-u} switch is applied to all of the immediate sources of the
14695 main project file.
14696
14697 When no main is specified on the command line and attribute @code{Main} exists
14698 and includes several mains, or when several mains are specified on the
14699 command line, the default ^switches^switches^ in package @code{Builder} will
14700 be used for all mains, even if there are specific ^switches^switches^
14701 specified for one or several mains.
14702
14703 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14704 the specific ^switches^switches^ for each main, if they are specified.
14705
14706 @node Library Project Files
14707 @subsubsection Library Project Files
14708
14709 @noindent
14710 When @command{gnatmake} is invoked with a main project file that is a library
14711 project file, it is not allowed to specify one or more mains on the command
14712 line.
14713
14714 @noindent
14715 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14716 ^-l^/ACTION=LINK^ have special meanings.
14717
14718 @itemize @bullet
14719 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14720 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14721 library.
14722
14723 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14724 to @command{gnatmake} that the binder generated file should be compiled
14725 (in the case of a stand-alone library) and that the library should be built.
14726
14727 @end itemize
14728
14729 @node The GNAT Driver and Project Files
14730 @subsection The GNAT Driver and Project Files
14731
14732 @noindent
14733 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14734 can benefit from project files:
14735 @command{^gnatbind^gnatbind^},
14736 @command{^gnatcheck^gnatcheck^}),
14737 @command{^gnatclean^gnatclean^}),
14738 @command{^gnatelim^gnatelim^},
14739 @command{^gnatfind^gnatfind^},
14740 @command{^gnatlink^gnatlink^},
14741 @command{^gnatls^gnatls^},
14742 @command{^gnatmetric^gnatmetric^},
14743 @command{^gnatpp^gnatpp^},
14744 @command{^gnatstub^gnatstub^},
14745 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
14746 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14747 They must be invoked through the @command{gnat} driver.
14748
14749 The @command{gnat} driver is a wrapper that accepts a number of commands and
14750 calls the corresponding tool. It was designed initially for VMS platforms (to
14751 convert VMS qualifiers to Unix-style switches), but it is now available on all
14752 GNAT platforms.
14753
14754 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14755 (case insensitive):
14756
14757 @itemize @bullet
14758 @item
14759 BIND to invoke @command{^gnatbind^gnatbind^}
14760 @item
14761 CHOP to invoke @command{^gnatchop^gnatchop^}
14762 @item
14763 CLEAN to invoke @command{^gnatclean^gnatclean^}
14764 @item
14765 COMP or COMPILE to invoke the compiler
14766 @item
14767 ELIM to invoke @command{^gnatelim^gnatelim^}
14768 @item
14769 FIND to invoke @command{^gnatfind^gnatfind^}
14770 @item
14771 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14772 @item
14773 LINK to invoke @command{^gnatlink^gnatlink^}
14774 @item
14775 LS or LIST to invoke @command{^gnatls^gnatls^}
14776 @item
14777 MAKE to invoke @command{^gnatmake^gnatmake^}
14778 @item
14779 NAME to invoke @command{^gnatname^gnatname^}
14780 @item
14781 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14782 @item
14783 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14784 @item
14785 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14786 @item
14787 STUB to invoke @command{^gnatstub^gnatstub^}
14788 @item
14789 XREF to invoke @command{^gnatxref^gnatxref^}
14790 @end itemize
14791
14792 @noindent
14793 (note that the compiler is invoked using the command
14794 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14795
14796 @noindent
14797 On non-VMS platforms, between @command{gnat} and the command, two
14798 special switches may be used:
14799
14800 @itemize @bullet
14801 @item
14802 @command{-v} to display the invocation of the tool.
14803 @item
14804 @command{-dn} to prevent the @command{gnat} driver from removing
14805 the temporary files it has created. These temporary files are
14806 configuration files and temporary file list files.
14807 @end itemize
14808
14809 @noindent
14810 The command may be followed by switches and arguments for the invoked
14811 tool.
14812
14813 @smallexample
14814   gnat bind -C main.ali
14815   gnat ls -a main
14816   gnat chop foo.txt
14817 @end smallexample
14818
14819 @noindent
14820 Switches may also be put in text files, one switch per line, and the text
14821 files may be specified with their path name preceded by '@@'.
14822
14823 @smallexample
14824    gnat bind @@args.txt main.ali
14825 @end smallexample
14826
14827 @noindent
14828 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14829 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14830 (@option{^-P^/PROJECT_FILE^},
14831 @option{^-X^/EXTERNAL_REFERENCE^} and
14832 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14833 the switches of the invoking tool.
14834
14835 @noindent
14836 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14837 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14838 the immediate sources of the specified project file.
14839
14840 @noindent
14841 When GNAT METRIC is used with a project file, but with no source
14842 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14843 with all the immediate sources of the specified project file and with
14844 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14845 of the project.
14846
14847 @noindent
14848 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14849 a project file, no source is specified on the command line and
14850 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14851 the underlying tool (^gnatpp^gnatpp^ or
14852 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14853 not only for the immediate sources of the main project.
14854 @ifclear vms
14855 (-U stands for Universal or Union of the project files of the project tree)
14856 @end ifclear
14857
14858 @noindent
14859 For each of the following commands, there is optionally a corresponding
14860 package in the main project.
14861
14862 @itemize @bullet
14863 @item
14864 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14865
14866 @item
14867 package @code{Check} for command CHECK (invoking
14868 @code{^gnatcheck^gnatcheck^})
14869
14870 @item
14871 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14872
14873 @item
14874 package @code{Cross_Reference} for command XREF (invoking
14875 @code{^gnatxref^gnatxref^})
14876
14877 @item
14878 package @code{Eliminate} for command ELIM (invoking
14879 @code{^gnatelim^gnatelim^})
14880
14881 @item
14882 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14883
14884 @item
14885 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14886
14887 @item
14888 package @code{Gnatstub} for command STUB
14889 (invoking @code{^gnatstub^gnatstub^})
14890
14891 @item
14892 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14893
14894 @item
14895 package @code{Metrics} for command METRIC
14896 (invoking @code{^gnatmetric^gnatmetric^})
14897
14898 @item
14899 package @code{Pretty_Printer} for command PP or PRETTY
14900 (invoking @code{^gnatpp^gnatpp^})
14901
14902 @end itemize
14903
14904 @noindent
14905 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14906 a simple variable with a string list value. It contains ^switches^switches^
14907 for the invocation of @code{^gnatls^gnatls^}.
14908
14909 @smallexample @c projectfile
14910 @group
14911 project Proj1 is
14912    package gnatls is
14913       for ^Switches^Switches^
14914           use ("^-a^-a^",
14915                "^-v^-v^");
14916    end gnatls;
14917 end Proj1;
14918 @end group
14919 @end smallexample
14920
14921 @noindent
14922 All other packages have two attribute @code{^Switches^Switches^} and
14923 @code{^Default_Switches^Default_Switches^}.
14924
14925 @noindent
14926 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14927 source file name, that has a string list value: the ^switches^switches^ to be
14928 used when the tool corresponding to the package is invoked for the specific
14929 source file.
14930
14931 @noindent
14932 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14933 indexed by  the programming language that has a string list value.
14934 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14935 ^switches^switches^ for the invocation of the tool corresponding
14936 to the package, except if a specific @code{^Switches^Switches^} attribute
14937 is specified for the source file.
14938
14939 @smallexample @c projectfile
14940 @group
14941 project Proj is
14942
14943    for Source_Dirs use ("./**");
14944
14945    package gnatls is
14946       for ^Switches^Switches^ use
14947           ("^-a^-a^",
14948            "^-v^-v^");
14949    end gnatls;
14950 @end group
14951 @group
14952
14953    package Compiler is
14954       for ^Default_Switches^Default_Switches^ ("Ada")
14955           use ("^-gnatv^-gnatv^",
14956                "^-gnatwa^-gnatwa^");
14957    end Binder;
14958 @end group
14959 @group
14960
14961    package Binder is
14962       for ^Default_Switches^Default_Switches^ ("Ada")
14963           use ("^-C^-C^",
14964                "^-e^-e^");
14965    end Binder;
14966 @end group
14967 @group
14968
14969    package Linker is
14970       for ^Default_Switches^Default_Switches^ ("Ada")
14971           use ("^-C^-C^");
14972       for ^Switches^Switches^ ("main.adb")
14973           use ("^-C^-C^",
14974                "^-v^-v^",
14975                "^-v^-v^");
14976    end Linker;
14977 @end group
14978 @group
14979
14980    package Finder is
14981       for ^Default_Switches^Default_Switches^ ("Ada")
14982            use ("^-a^-a^",
14983                 "^-f^-f^");
14984    end Finder;
14985 @end group
14986 @group
14987
14988    package Cross_Reference is
14989       for ^Default_Switches^Default_Switches^ ("Ada")
14990           use ("^-a^-a^",
14991                "^-f^-f^",
14992                "^-d^-d^",
14993                "^-u^-u^");
14994    end Cross_Reference;
14995 end Proj;
14996 @end group
14997 @end smallexample
14998
14999 @noindent
15000 With the above project file, commands such as
15001
15002 @smallexample
15003    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
15004    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
15005    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
15006    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
15007    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
15008 @end smallexample
15009
15010 @noindent
15011 will set up the environment properly and invoke the tool with the switches
15012 found in the package corresponding to the tool:
15013 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
15014 except @code{^Switches^Switches^ ("main.adb")}
15015 for @code{^gnatlink^gnatlink^}.
15016 It is also possible to invoke some of the tools,
15017 @code{^gnatcheck^gnatcheck^}),
15018 @code{^gnatmetric^gnatmetric^}),
15019 and @code{^gnatpp^gnatpp^})
15020 on a set of project units thanks to the combination of the switches
15021 @option{-P}, @option{-U} and possibly the main unit when one is interested
15022 in its closure. For instance,
15023 @smallexample
15024 gnat metric -Pproj
15025 @end smallexample
15026 will compute the metrics for all the immediate units of project
15027 @code{proj}.
15028 @smallexample
15029 gnat metric -Pproj -U
15030 @end smallexample
15031 will compute the metrics for all the units of the closure of projects
15032 rooted at @code{proj}.
15033 @smallexample
15034 gnat metric -Pproj -U main_unit
15035 @end smallexample
15036 will compute the metrics for the closure of units rooted at
15037 @code{main_unit}. This last possibility relies implicitly
15038 on @command{gnatbind}'s option @option{-R}.
15039
15040 @c **********************
15041 @node An Extended Example
15042 @section An Extended Example
15043
15044 @noindent
15045 Suppose that we have two programs, @var{prog1} and @var{prog2},
15046 whose sources are in corresponding directories. We would like
15047 to build them with a single @command{gnatmake} command, and we want to place
15048 their object files into @file{build} subdirectories of the source directories.
15049 Furthermore, we want to have to have two separate subdirectories
15050 in @file{build}  -- @file{release} and @file{debug} -- which will contain
15051 the object files compiled with different set of compilation flags.
15052
15053 In other words, we have the following structure:
15054
15055 @smallexample
15056 @group
15057    main
15058      |- prog1
15059      |    |- build
15060      |         | debug
15061      |         | release
15062      |- prog2
15063           |- build
15064                | debug
15065                | release
15066 @end group
15067 @end smallexample
15068
15069 @noindent
15070 Here are the project files that we must place in a directory @file{main}
15071 to maintain this structure:
15072
15073 @enumerate
15074
15075 @item We create a @code{Common} project with a package @code{Compiler} that
15076 specifies the compilation ^switches^switches^:
15077
15078 @smallexample
15079 File "common.gpr":
15080 @group
15081 @b{project} Common @b{is}
15082
15083    @b{for} Source_Dirs @b{use} (); -- No source files
15084 @end group
15085
15086 @group
15087    @b{type} Build_Type @b{is} ("release", "debug");
15088    Build : Build_Type := External ("BUILD", "debug");
15089 @end group
15090 @group
15091    @b{package} Compiler @b{is}
15092       @b{case} Build @b{is}
15093          @b{when} "release" =>
15094            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15095                    @b{use} ("^-O2^-O2^");
15096          @b{when} "debug"   =>
15097            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15098                    @b{use} ("^-g^-g^");
15099       @b{end case};
15100    @b{end} Compiler;
15101
15102 @b{end} Common;
15103 @end group
15104 @end smallexample
15105
15106 @item We create separate projects for the two programs:
15107
15108 @smallexample
15109 @group
15110 File "prog1.gpr":
15111
15112 @b{with} "common";
15113 @b{project} Prog1 @b{is}
15114
15115     @b{for} Source_Dirs @b{use} ("prog1");
15116     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
15117
15118     @b{package} Compiler @b{renames} Common.Compiler;
15119
15120 @b{end} Prog1;
15121 @end group
15122 @end smallexample
15123
15124 @smallexample
15125 @group
15126 File "prog2.gpr":
15127
15128 @b{with} "common";
15129 @b{project} Prog2 @b{is}
15130
15131     @b{for} Source_Dirs @b{use} ("prog2");
15132     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
15133
15134     @b{package} Compiler @b{renames} Common.Compiler;
15135
15136 @end group
15137 @b{end} Prog2;
15138 @end smallexample
15139
15140 @item We create a wrapping project @code{Main}:
15141
15142 @smallexample
15143 @group
15144 File "main.gpr":
15145
15146 @b{with} "common";
15147 @b{with} "prog1";
15148 @b{with} "prog2";
15149 @b{project} Main @b{is}
15150
15151    @b{package} Compiler @b{renames} Common.Compiler;
15152
15153 @b{end} Main;
15154 @end group
15155 @end smallexample
15156
15157 @item Finally we need to create a dummy procedure that @code{with}s (either
15158 explicitly or implicitly) all the sources of our two programs.
15159
15160 @end enumerate
15161
15162 @noindent
15163 Now we can build the programs using the command
15164
15165 @smallexample
15166    gnatmake ^-P^/PROJECT_FILE=^main dummy
15167 @end smallexample
15168
15169 @noindent
15170 for the Debug mode, or
15171
15172 @ifclear vms
15173 @smallexample
15174    gnatmake -Pmain -XBUILD=release
15175 @end smallexample
15176 @end ifclear
15177
15178 @ifset vms
15179 @smallexample
15180    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
15181 @end smallexample
15182 @end ifset
15183
15184 @noindent
15185 for the Release mode.
15186
15187 @c ********************************
15188 @c * Project File Complete Syntax *
15189 @c ********************************
15190
15191 @node Project File Complete Syntax
15192 @section Project File Complete Syntax
15193
15194 @smallexample
15195 project ::=
15196   context_clause project_declaration
15197
15198 context_clause ::=
15199   @{with_clause@}
15200
15201 with_clause ::=
15202   @b{with} path_name @{ , path_name @} ;
15203
15204 path_name ::=
15205    string_literal
15206
15207 project_declaration ::=
15208   simple_project_declaration | project_extension
15209
15210 simple_project_declaration ::=
15211   @b{project} <project_>simple_name @b{is}
15212     @{declarative_item@}
15213   @b{end} <project_>simple_name;
15214
15215 project_extension ::=
15216   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
15217     @{declarative_item@}
15218   @b{end} <project_>simple_name;
15219
15220 declarative_item ::=
15221   package_declaration |
15222   typed_string_declaration |
15223   other_declarative_item
15224
15225 package_declaration ::=
15226   package_spec | package_renaming
15227
15228 package_spec ::=
15229   @b{package} package_identifier @b{is}
15230     @{simple_declarative_item@}
15231   @b{end} package_identifier ;
15232
15233 package_identifier ::=
15234   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
15235   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
15236   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
15237
15238 package_renaming ::==
15239   @b{package} package_identifier @b{renames}
15240        <project_>simple_name.package_identifier ;
15241
15242 typed_string_declaration ::=
15243   @b{type} <typed_string_>_simple_name @b{is}
15244    ( string_literal @{, string_literal@} );
15245
15246 other_declarative_item ::=
15247   attribute_declaration |
15248   typed_variable_declaration |
15249   variable_declaration |
15250   case_construction
15251
15252 attribute_declaration ::=
15253   full_associative_array_declaration |
15254   @b{for} attribute_designator @b{use} expression ;
15255
15256 full_associative_array_declaration ::=
15257   @b{for} <associative_array_attribute_>simple_name @b{use}
15258   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
15259
15260 attribute_designator ::=
15261   <simple_attribute_>simple_name |
15262   <associative_array_attribute_>simple_name ( string_literal )
15263
15264 typed_variable_declaration ::=
15265   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
15266
15267 variable_declaration ::=
15268   <variable_>simple_name := expression;
15269
15270 expression ::=
15271   term @{& term@}
15272
15273 term ::=
15274   literal_string |
15275   string_list |
15276   <variable_>name |
15277   external_value |
15278   attribute_reference
15279
15280 string_literal ::=
15281   (same as Ada)
15282
15283 string_list ::=
15284   ( <string_>expression @{ , <string_>expression @} )
15285
15286 external_value ::=
15287   @b{external} ( string_literal [, string_literal] )
15288
15289 attribute_reference ::=
15290   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
15291
15292 attribute_prefix ::=
15293   @b{project} |
15294   <project_>simple_name | package_identifier |
15295   <project_>simple_name . package_identifier
15296
15297 case_construction ::=
15298   @b{case} <typed_variable_>name @b{is}
15299     @{case_item@}
15300   @b{end case} ;
15301
15302 case_item ::=
15303   @b{when} discrete_choice_list =>
15304       @{case_construction | attribute_declaration@}
15305
15306 discrete_choice_list ::=
15307   string_literal @{| string_literal@} |
15308   @b{others}
15309
15310 name ::=
15311   simple_name @{. simple_name@}
15312
15313 simple_name ::=
15314   identifier (same as Ada)
15315
15316 @end smallexample
15317
15318 @node The Cross-Referencing Tools gnatxref and gnatfind
15319 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
15320 @findex gnatxref
15321 @findex gnatfind
15322
15323 @noindent
15324 The compiler generates cross-referencing information (unless
15325 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
15326 This information indicates where in the source each entity is declared and
15327 referenced. Note that entities in package Standard are not included, but
15328 entities in all other predefined units are included in the output.
15329
15330 Before using any of these two tools, you need to compile successfully your
15331 application, so that GNAT gets a chance to generate the cross-referencing
15332 information.
15333
15334 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
15335 information to provide the user with the capability to easily locate the
15336 declaration and references to an entity. These tools are quite similar,
15337 the difference being that @code{gnatfind} is intended for locating
15338 definitions and/or references to a specified entity or entities, whereas
15339 @code{gnatxref} is oriented to generating a full report of all
15340 cross-references.
15341
15342 To use these tools, you must not compile your application using the
15343 @option{-gnatx} switch on the @command{gnatmake} command line
15344 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
15345 information will not be generated.
15346
15347 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
15348 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15349
15350 @menu
15351 * gnatxref Switches::
15352 * gnatfind Switches::
15353 * Project Files for gnatxref and gnatfind::
15354 * Regular Expressions in gnatfind and gnatxref::
15355 * Examples of gnatxref Usage::
15356 * Examples of gnatfind Usage::
15357 @end menu
15358
15359 @node gnatxref Switches
15360 @section @code{gnatxref} Switches
15361
15362 @noindent
15363 The command invocation for @code{gnatxref} is:
15364 @smallexample
15365 $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15366 @end smallexample
15367
15368 @noindent
15369 where
15370
15371 @table @var
15372 @item sourcefile1
15373 @itemx sourcefile2
15374 identifies the source files for which a report is to be generated. The
15375 ``with''ed units will be processed too. You must provide at least one file.
15376
15377 These file names are considered to be regular expressions, so for instance
15378 specifying @file{source*.adb} is the same as giving every file in the current
15379 directory whose name starts with @file{source} and whose extension is
15380 @file{adb}.
15381
15382 You shouldn't specify any directory name, just base names. @command{gnatxref}
15383 and @command{gnatfind} will be able to locate these files by themselves using
15384 the source path. If you specify directories, no result is produced.
15385
15386 @end table
15387
15388 @noindent
15389 The switches can be:
15390 @table @option
15391 @c !sort!
15392 @item --version
15393 @cindex @option{--version} @command{gnatxref}
15394 Display Copyright and version, then exit disregarding all other options.
15395
15396 @item --help
15397 @cindex @option{--help} @command{gnatxref}
15398 If @option{--version} was not used, display usage, then exit disregarding
15399 all other options.
15400
15401 @item ^-a^/ALL_FILES^
15402 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15403 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15404 the read-only files found in the library search path. Otherwise, these files
15405 will be ignored. This option can be used to protect Gnat sources or your own
15406 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15407 much faster, and their output much smaller. Read-only here refers to access
15408 or permissions status in the file system for the current user.
15409
15410 @item -aIDIR
15411 @cindex @option{-aIDIR} (@command{gnatxref})
15412 When looking for source files also look in directory DIR. The order in which
15413 source file search is undertaken is the same as for @command{gnatmake}.
15414
15415 @item -aODIR
15416 @cindex @option{-aODIR} (@command{gnatxref})
15417 When searching for library and object files, look in directory
15418 DIR. The order in which library files are searched is the same as for
15419 @command{gnatmake}.
15420
15421 @item -nostdinc
15422 @cindex @option{-nostdinc} (@command{gnatxref})
15423 Do not look for sources in the system default directory.
15424
15425 @item -nostdlib
15426 @cindex @option{-nostdlib} (@command{gnatxref})
15427 Do not look for library files in the system default directory.
15428
15429 @item --RTS=@var{rts-path}
15430 @cindex @option{--RTS} (@command{gnatxref})
15431 Specifies the default location of the runtime library. Same meaning as the
15432 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15433
15434 @item ^-d^/DERIVED_TYPES^
15435 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15436 If this switch is set @code{gnatxref} will output the parent type
15437 reference for each matching derived types.
15438
15439 @item ^-f^/FULL_PATHNAME^
15440 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15441 If this switch is set, the output file names will be preceded by their
15442 directory (if the file was found in the search path). If this switch is
15443 not set, the directory will not be printed.
15444
15445 @item ^-g^/IGNORE_LOCALS^
15446 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15447 If this switch is set, information is output only for library-level
15448 entities, ignoring local entities. The use of this switch may accelerate
15449 @code{gnatfind} and @code{gnatxref}.
15450
15451 @item -IDIR
15452 @cindex @option{-IDIR} (@command{gnatxref})
15453 Equivalent to @samp{-aODIR -aIDIR}.
15454
15455 @item -pFILE
15456 @cindex @option{-pFILE} (@command{gnatxref})
15457 Specify a project file to use @xref{Project Files}.
15458 If you need to use the @file{.gpr}
15459 project files, you should use gnatxref through the GNAT driver
15460 (@command{gnat xref -Pproject}).
15461
15462 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15463 project file in the current directory.
15464
15465 If a project file is either specified or found by the tools, then the content
15466 of the source directory and object directory lines are added as if they
15467 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15468 and @samp{^-aO^OBJECT_SEARCH^}.
15469 @item ^-u^/UNUSED^
15470 Output only unused symbols. This may be really useful if you give your
15471 main compilation unit on the command line, as @code{gnatxref} will then
15472 display every unused entity and 'with'ed package.
15473
15474 @ifclear vms
15475 @item -v
15476 Instead of producing the default output, @code{gnatxref} will generate a
15477 @file{tags} file that can be used by vi. For examples how to use this
15478 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15479 to the standard output, thus you will have to redirect it to a file.
15480 @end ifclear
15481
15482 @end table
15483
15484 @noindent
15485 All these switches may be in any order on the command line, and may even
15486 appear after the file names. They need not be separated by spaces, thus
15487 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15488 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15489
15490 @node gnatfind Switches
15491 @section @code{gnatfind} Switches
15492
15493 @noindent
15494 The command line for @code{gnatfind} is:
15495
15496 @smallexample
15497 $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15498       @r{[}@var{file1} @var{file2} @dots{}]
15499 @end smallexample
15500
15501 @noindent
15502 where
15503
15504 @table @var
15505 @item pattern
15506 An entity will be output only if it matches the regular expression found
15507 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15508
15509 Omitting the pattern is equivalent to specifying @samp{*}, which
15510 will match any entity. Note that if you do not provide a pattern, you
15511 have to provide both a sourcefile and a line.
15512
15513 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15514 for matching purposes. At the current time there is no support for
15515 8-bit codes other than Latin-1, or for wide characters in identifiers.
15516
15517 @item sourcefile
15518 @code{gnatfind} will look for references, bodies or declarations
15519 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15520 and column @var{column}. See @ref{Examples of gnatfind Usage}
15521 for syntax examples.
15522
15523 @item line
15524 is a decimal integer identifying the line number containing
15525 the reference to the entity (or entities) to be located.
15526
15527 @item column
15528 is a decimal integer identifying the exact location on the
15529 line of the first character of the identifier for the
15530 entity reference. Columns are numbered from 1.
15531
15532 @item file1 file2 @dots{}
15533 The search will be restricted to these source files. If none are given, then
15534 the search will be done for every library file in the search path.
15535 These file must appear only after the pattern or sourcefile.
15536
15537 These file names are considered to be regular expressions, so for instance
15538 specifying @file{source*.adb} is the same as giving every file in the current
15539 directory whose name starts with @file{source} and whose extension is
15540 @file{adb}.
15541
15542 The location of the spec of the entity will always be displayed, even if it
15543 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
15544 occurrences of the entity in the separate units of the ones given on the
15545 command line will also be displayed.
15546
15547 Note that if you specify at least one file in this part, @code{gnatfind} may
15548 sometimes not be able to find the body of the subprograms.
15549
15550 @end table
15551
15552 @noindent
15553 At least one of 'sourcefile' or 'pattern' has to be present on
15554 the command line.
15555
15556 The following switches are available:
15557 @table @option
15558 @c !sort!
15559
15560 @cindex @option{--version} @command{gnatfind}
15561 Display Copyright and version, then exit disregarding all other options.
15562
15563 @item --help
15564 @cindex @option{--help} @command{gnatfind}
15565 If @option{--version} was not used, display usage, then exit disregarding
15566 all other options.
15567
15568 @item ^-a^/ALL_FILES^
15569 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15570 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15571 the read-only files found in the library search path. Otherwise, these files
15572 will be ignored. This option can be used to protect Gnat sources or your own
15573 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15574 much faster, and their output much smaller. Read-only here refers to access
15575 or permission status in the file system for the current user.
15576
15577 @item -aIDIR
15578 @cindex @option{-aIDIR} (@command{gnatfind})
15579 When looking for source files also look in directory DIR. The order in which
15580 source file search is undertaken is the same as for @command{gnatmake}.
15581
15582 @item -aODIR
15583 @cindex @option{-aODIR} (@command{gnatfind})
15584 When searching for library and object files, look in directory
15585 DIR. The order in which library files are searched is the same as for
15586 @command{gnatmake}.
15587
15588 @item -nostdinc
15589 @cindex @option{-nostdinc} (@command{gnatfind})
15590 Do not look for sources in the system default directory.
15591
15592 @item -nostdlib
15593 @cindex @option{-nostdlib} (@command{gnatfind})
15594 Do not look for library files in the system default directory.
15595
15596 @item --ext=@var{extension}
15597 @cindex @option{--ext} (@command{gnatfind})
15598 Specify an alternate ali file extension. The default is @code{ali} and other
15599 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
15600 switch. Note that if this switch overrides the default, which means that only
15601 the new extension will be considered.
15602
15603 @item --RTS=@var{rts-path}
15604 @cindex @option{--RTS} (@command{gnatfind})
15605 Specifies the default location of the runtime library. Same meaning as the
15606 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15607
15608 @item ^-d^/DERIVED_TYPE_INFORMATION^
15609 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15610 If this switch is set, then @code{gnatfind} will output the parent type
15611 reference for each matching derived types.
15612
15613 @item ^-e^/EXPRESSIONS^
15614 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15615 By default, @code{gnatfind} accept the simple regular expression set for
15616 @samp{pattern}. If this switch is set, then the pattern will be
15617 considered as full Unix-style regular expression.
15618
15619 @item ^-f^/FULL_PATHNAME^
15620 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15621 If this switch is set, the output file names will be preceded by their
15622 directory (if the file was found in the search path). If this switch is
15623 not set, the directory will not be printed.
15624
15625 @item ^-g^/IGNORE_LOCALS^
15626 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15627 If this switch is set, information is output only for library-level
15628 entities, ignoring local entities. The use of this switch may accelerate
15629 @code{gnatfind} and @code{gnatxref}.
15630
15631 @item -IDIR
15632 @cindex @option{-IDIR} (@command{gnatfind})
15633 Equivalent to @samp{-aODIR -aIDIR}.
15634
15635 @item -pFILE
15636 @cindex @option{-pFILE} (@command{gnatfind})
15637 Specify a project file (@pxref{Project Files}) to use.
15638 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15639 project file in the current directory.
15640
15641 If a project file is either specified or found by the tools, then the content
15642 of the source directory and object directory lines are added as if they
15643 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15644 @samp{^-aO^/OBJECT_SEARCH^}.
15645
15646 @item ^-r^/REFERENCES^
15647 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15648 By default, @code{gnatfind} will output only the information about the
15649 declaration, body or type completion of the entities. If this switch is
15650 set, the @code{gnatfind} will locate every reference to the entities in
15651 the files specified on the command line (or in every file in the search
15652 path if no file is given on the command line).
15653
15654 @item ^-s^/PRINT_LINES^
15655 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15656 If this switch is set, then @code{gnatfind} will output the content
15657 of the Ada source file lines were the entity was found.
15658
15659 @item ^-t^/TYPE_HIERARCHY^
15660 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15661 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15662 the specified type. It act like -d option but recursively from parent
15663 type to parent type. When this switch is set it is not possible to
15664 specify more than one file.
15665
15666 @end table
15667
15668 @noindent
15669 All these switches may be in any order on the command line, and may even
15670 appear after the file names. They need not be separated by spaces, thus
15671 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15672 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15673
15674 As stated previously, gnatfind will search in every directory in the
15675 search path. You can force it to look only in the current directory if
15676 you specify @code{*} at the end of the command line.
15677
15678 @node Project Files for gnatxref and gnatfind
15679 @section Project Files for @command{gnatxref} and @command{gnatfind}
15680
15681 @noindent
15682 Project files allow a programmer to specify how to compile its
15683 application, where to find sources, etc.  These files are used
15684 @ifclear vms
15685 primarily by GPS, but they can also be used
15686 @end ifclear
15687 by the two tools
15688 @code{gnatxref} and @code{gnatfind}.
15689
15690 A project file name must end with @file{.gpr}. If a single one is
15691 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15692 extract the information from it. If multiple project files are found, none of
15693 them is read, and you have to use the @samp{-p} switch to specify the one
15694 you want to use.
15695
15696 The following lines can be included, even though most of them have default
15697 values which can be used in most cases.
15698 The lines can be entered in any order in the file.
15699 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15700 each line. If you have multiple instances, only the last one is taken into
15701 account.
15702
15703 @table @code
15704 @item src_dir=DIR
15705 [default: @code{"^./^[]^"}]
15706 specifies a directory where to look for source files. Multiple @code{src_dir}
15707 lines can be specified and they will be searched in the order they
15708 are specified.
15709
15710 @item obj_dir=DIR
15711 [default: @code{"^./^[]^"}]
15712 specifies a directory where to look for object and library files. Multiple
15713 @code{obj_dir} lines can be specified, and they will be searched in the order
15714 they are specified
15715
15716 @item comp_opt=SWITCHES
15717 [default: @code{""}]
15718 creates a variable which can be referred to subsequently by using
15719 the @code{$@{comp_opt@}} notation. This is intended to store the default
15720 switches given to @command{gnatmake} and @command{gcc}.
15721
15722 @item bind_opt=SWITCHES
15723 [default: @code{""}]
15724 creates a variable which can be referred to subsequently by using
15725 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15726 switches given to @command{gnatbind}.
15727
15728 @item link_opt=SWITCHES
15729 [default: @code{""}]
15730 creates a variable which can be referred to subsequently by using
15731 the @samp{$@{link_opt@}} notation. This is intended to store the default
15732 switches given to @command{gnatlink}.
15733
15734 @item main=EXECUTABLE
15735 [default: @code{""}]
15736 specifies the name of the executable for the application. This variable can
15737 be referred to in the following lines by using the @samp{$@{main@}} notation.
15738
15739 @ifset vms
15740 @item comp_cmd=COMMAND
15741 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15742 @end ifset
15743 @ifclear vms
15744 @item comp_cmd=COMMAND
15745 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15746 @end ifclear
15747 specifies the command used to compile a single file in the application.
15748
15749 @ifset vms
15750 @item make_cmd=COMMAND
15751 [default: @code{"GNAT MAKE $@{main@}
15752 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15753 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15754 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15755 @end ifset
15756 @ifclear vms
15757 @item make_cmd=COMMAND
15758 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15759 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15760 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15761 @end ifclear
15762 specifies the command used to recompile the whole application.
15763
15764 @item run_cmd=COMMAND
15765 [default: @code{"$@{main@}"}]
15766 specifies the command used to run the application.
15767
15768 @item debug_cmd=COMMAND
15769 [default: @code{"gdb $@{main@}"}]
15770 specifies the command used to debug the application
15771
15772 @end table
15773
15774 @noindent
15775 @command{gnatxref} and @command{gnatfind} only take into account the
15776 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15777
15778 @node Regular Expressions in gnatfind and gnatxref
15779 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15780
15781 @noindent
15782 As specified in the section about @command{gnatfind}, the pattern can be a
15783 regular expression. Actually, there are to set of regular expressions
15784 which are recognized by the program:
15785
15786 @table @code
15787 @item globbing patterns
15788 These are the most usual regular expression. They are the same that you
15789 generally used in a Unix shell command line, or in a DOS session.
15790
15791 Here is a more formal grammar:
15792 @smallexample
15793 @group
15794 @iftex
15795 @leftskip=.5cm
15796 @end iftex
15797 regexp ::= term
15798 term   ::= elmt            -- matches elmt
15799 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15800 term   ::= *               -- any string of 0 or more characters
15801 term   ::= ?               -- matches any character
15802 term   ::= [char @{char@}]   -- matches any character listed
15803 term   ::= [char - char]   -- matches any character in range
15804 @end group
15805 @end smallexample
15806
15807 @item full regular expression
15808 The second set of regular expressions is much more powerful. This is the
15809 type of regular expressions recognized by utilities such a @file{grep}.
15810
15811 The following is the form of a regular expression, expressed in Ada
15812 reference manual style BNF is as follows
15813
15814 @smallexample
15815 @iftex
15816 @leftskip=.5cm
15817 @end iftex
15818 @group
15819 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
15820
15821 term ::= item @{item@}       -- concatenation (item then item)
15822
15823 item ::= elmt              -- match elmt
15824 item ::= elmt *            -- zero or more elmt's
15825 item ::= elmt +            -- one or more elmt's
15826 item ::= elmt ?            -- matches elmt or nothing
15827 @end group
15828 @group
15829 elmt ::= nschar            -- matches given character
15830 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15831 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15832 elmt ::= [char - char]     -- matches chars in given range
15833 elmt ::= \ char            -- matches given character
15834 elmt ::= .                 -- matches any single character
15835 elmt ::= ( regexp )        -- parens used for grouping
15836
15837 char ::= any character, including special characters
15838 nschar ::= any character except ()[].*+?^^^
15839 @end group
15840 @end smallexample
15841
15842 Following are a few examples:
15843
15844 @table @samp
15845 @item abcde|fghi
15846 will match any of the two strings @samp{abcde} and @samp{fghi},
15847
15848 @item abc*d
15849 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15850 @samp{abcccd}, and so on,
15851
15852 @item [a-z]+
15853 will match any string which has only lowercase characters in it (and at
15854 least one character.
15855
15856 @end table
15857 @end table
15858
15859 @node Examples of gnatxref Usage
15860 @section Examples of @code{gnatxref} Usage
15861
15862 @subsection General Usage
15863
15864 @noindent
15865 For the following examples, we will consider the following units:
15866
15867 @smallexample @c ada
15868 @group
15869 @cartouche
15870 main.ads:
15871 1: with Bar;
15872 2: package Main is
15873 3:     procedure Foo (B : in Integer);
15874 4:     C : Integer;
15875 5: private
15876 6:     D : Integer;
15877 7: end Main;
15878
15879 main.adb:
15880 1: package body Main is
15881 2:     procedure Foo (B : in Integer) is
15882 3:     begin
15883 4:        C := B;
15884 5:        D := B;
15885 6:        Bar.Print (B);
15886 7:        Bar.Print (C);
15887 8:     end Foo;
15888 9: end Main;
15889
15890 bar.ads:
15891 1: package Bar is
15892 2:     procedure Print (B : Integer);
15893 3: end bar;
15894 @end cartouche
15895 @end group
15896 @end smallexample
15897
15898 @table @code
15899
15900 @noindent
15901 The first thing to do is to recompile your application (for instance, in
15902 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15903 the cross-referencing information.
15904 You can then issue any of the following commands:
15905
15906 @item gnatxref main.adb
15907 @code{gnatxref} generates cross-reference information for main.adb
15908 and every unit 'with'ed by main.adb.
15909
15910 The output would be:
15911 @smallexample
15912 @iftex
15913 @leftskip=0cm
15914 @end iftex
15915 B                                                      Type: Integer
15916   Decl: bar.ads           2:22
15917 B                                                      Type: Integer
15918   Decl: main.ads          3:20
15919   Body: main.adb          2:20
15920   Ref:  main.adb          4:13     5:13     6:19
15921 Bar                                                    Type: Unit
15922   Decl: bar.ads           1:9
15923   Ref:  main.adb          6:8      7:8
15924        main.ads           1:6
15925 C                                                      Type: Integer
15926   Decl: main.ads          4:5
15927   Modi: main.adb          4:8
15928   Ref:  main.adb          7:19
15929 D                                                      Type: Integer
15930   Decl: main.ads          6:5
15931   Modi: main.adb          5:8
15932 Foo                                                    Type: Unit
15933   Decl: main.ads          3:15
15934   Body: main.adb          2:15
15935 Main                                                    Type: Unit
15936   Decl: main.ads          2:9
15937   Body: main.adb          1:14
15938 Print                                                   Type: Unit
15939   Decl: bar.ads           2:15
15940   Ref:  main.adb          6:12     7:12
15941 @end smallexample
15942
15943 @noindent
15944 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15945 its body is in main.adb, line 1, column 14 and is not referenced any where.
15946
15947 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15948 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15949
15950 @item gnatxref package1.adb package2.ads
15951 @code{gnatxref} will generates cross-reference information for
15952 package1.adb, package2.ads and any other package 'with'ed by any
15953 of these.
15954
15955 @end table
15956
15957 @ifclear vms
15958 @subsection Using gnatxref with vi
15959
15960 @code{gnatxref} can generate a tags file output, which can be used
15961 directly from @command{vi}. Note that the standard version of @command{vi}
15962 will not work properly with overloaded symbols. Consider using another
15963 free implementation of @command{vi}, such as @command{vim}.
15964
15965 @smallexample
15966 $ gnatxref -v gnatfind.adb > tags
15967 @end smallexample
15968
15969 @noindent
15970 will generate the tags file for @code{gnatfind} itself (if the sources
15971 are in the search path!).
15972
15973 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
15974 (replacing @var{entity} by whatever you are looking for), and vi will
15975 display a new file with the corresponding declaration of entity.
15976 @end ifclear
15977
15978 @node Examples of gnatfind Usage
15979 @section Examples of @code{gnatfind} Usage
15980
15981 @table @code
15982
15983 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15984 Find declarations for all entities xyz referenced at least once in
15985 main.adb. The references are search in every library file in the search
15986 path.
15987
15988 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15989 switch is set)
15990
15991 The output will look like:
15992 @smallexample
15993 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15994 ^directory/^[directory]^main.adb:24:10: xyz <= body
15995 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15996 @end smallexample
15997
15998 @noindent
15999 that is to say, one of the entities xyz found in main.adb is declared at
16000 line 12 of main.ads (and its body is in main.adb), and another one is
16001 declared at line 45 of foo.ads
16002
16003 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
16004 This is the same command as the previous one, instead @code{gnatfind} will
16005 display the content of the Ada source file lines.
16006
16007 The output will look like:
16008
16009 @smallexample
16010 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
16011    procedure xyz;
16012 ^directory/^[directory]^main.adb:24:10: xyz <= body
16013    procedure xyz is
16014 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
16015    xyz : Integer;
16016 @end smallexample
16017
16018 @noindent
16019 This can make it easier to find exactly the location your are looking
16020 for.
16021
16022 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
16023 Find references to all entities containing an x that are
16024 referenced on line 123 of main.ads.
16025 The references will be searched only in main.ads and foo.adb.
16026
16027 @item gnatfind main.ads:123
16028 Find declarations and bodies for all entities that are referenced on
16029 line 123 of main.ads.
16030
16031 This is the same as @code{gnatfind "*":main.adb:123}.
16032
16033 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
16034 Find the declaration for the entity referenced at column 45 in
16035 line 123 of file main.adb in directory mydir. Note that it
16036 is usual to omit the identifier name when the column is given,
16037 since the column position identifies a unique reference.
16038
16039 The column has to be the beginning of the identifier, and should not
16040 point to any character in the middle of the identifier.
16041
16042 @end table
16043
16044 @c *********************************
16045 @node The GNAT Pretty-Printer gnatpp
16046 @chapter The GNAT Pretty-Printer @command{gnatpp}
16047 @findex gnatpp
16048 @cindex Pretty-Printer
16049
16050 @noindent
16051 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
16052 for source reformatting / pretty-printing.
16053 It takes an Ada source file as input and generates a reformatted
16054 version as output.
16055 You can specify various style directives via switches; e.g.,
16056 identifier case conventions, rules of indentation, and comment layout.
16057
16058 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
16059 tree for the input source and thus requires the input to be syntactically and
16060 semantically legal.
16061 If this condition is not met, @command{gnatpp} will terminate with an
16062 error message; no output file will be generated.
16063
16064 If the source files presented to @command{gnatpp} contain
16065 preprocessing directives, then the output file will
16066 correspond to the generated source after all
16067 preprocessing is carried out. There is no way
16068 using @command{gnatpp} to obtain pretty printed files that
16069 include the preprocessing directives.
16070
16071 If the compilation unit
16072 contained in the input source depends semantically upon units located
16073 outside the current directory, you have to provide the source search path
16074 when invoking @command{gnatpp}, if these units are contained in files with
16075 names that do not follow the GNAT file naming rules, you have to provide
16076 the configuration file describing the corresponding naming scheme;
16077 see the description of the @command{gnatpp}
16078 switches below. Another possibility is to use a project file and to
16079 call @command{gnatpp} through the @command{gnat} driver
16080
16081 The @command{gnatpp} command has the form
16082
16083 @smallexample
16084 $ gnatpp @ovar{switches} @var{filename}
16085 @end smallexample
16086
16087 @noindent
16088 where
16089 @itemize @bullet
16090 @item
16091 @var{switches} is an optional sequence of switches defining such properties as
16092 the formatting rules, the source search path, and the destination for the
16093 output source file
16094
16095 @item
16096 @var{filename} is the name (including the extension) of the source file to
16097 reformat; ``wildcards'' or several file names on the same gnatpp command are
16098 allowed.  The file name may contain path information; it does not have to
16099 follow the GNAT file naming rules
16100 @end itemize
16101
16102 @menu
16103 * Switches for gnatpp::
16104 * Formatting Rules::
16105 @end menu
16106
16107 @node Switches for gnatpp
16108 @section Switches for @command{gnatpp}
16109
16110 @noindent
16111 The following subsections describe the various switches accepted by
16112 @command{gnatpp}, organized by category.
16113
16114 @ifclear vms
16115 You specify a switch by supplying a name and generally also a value.
16116 In many cases the values for a switch with a given name are incompatible with
16117 each other
16118 (for example the switch that controls the casing of a reserved word may have
16119 exactly one value: upper case, lower case, or
16120 mixed case) and thus exactly one such switch can be in effect for an
16121 invocation of @command{gnatpp}.
16122 If more than one is supplied, the last one is used.
16123 However, some values for the same switch are mutually compatible.
16124 You may supply several such switches to @command{gnatpp}, but then
16125 each must be specified in full, with both the name and the value.
16126 Abbreviated forms (the name appearing once, followed by each value) are
16127 not permitted.
16128 For example, to set
16129 the alignment of the assignment delimiter both in declarations and in
16130 assignment statements, you must write @option{-A2A3}
16131 (or @option{-A2 -A3}), but not @option{-A23}.
16132 @end ifclear
16133
16134 @ifset vms
16135 In many cases the set of options for a given qualifier are incompatible with
16136 each other (for example the qualifier that controls the casing of a reserved
16137 word may have exactly one option, which specifies either upper case, lower
16138 case, or mixed case), and thus exactly one such option can be in effect for
16139 an invocation of @command{gnatpp}.
16140 If more than one is supplied, the last one is used.
16141 However, some qualifiers have options that are mutually compatible,
16142 and then you may then supply several such options when invoking
16143 @command{gnatpp}.
16144 @end ifset
16145
16146 In most cases, it is obvious whether or not the
16147 ^values for a switch with a given name^options for a given qualifier^
16148 are compatible with each other.
16149 When the semantics might not be evident, the summaries below explicitly
16150 indicate the effect.
16151
16152 @menu
16153 * Alignment Control::
16154 * Casing Control::
16155 * Construct Layout Control::
16156 * General Text Layout Control::
16157 * Other Formatting Options::
16158 * Setting the Source Search Path::
16159 * Output File Control::
16160 * Other gnatpp Switches::
16161 @end menu
16162
16163 @node Alignment Control
16164 @subsection Alignment Control
16165 @cindex Alignment control in @command{gnatpp}
16166
16167 @noindent
16168 Programs can be easier to read if certain constructs are vertically aligned.
16169 By default all alignments are set ON.
16170 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
16171 OFF, and then use one or more of the other
16172 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
16173 to activate alignment for specific constructs.
16174
16175 @table @option
16176 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
16177
16178 @ifset vms
16179 @item /ALIGN=ON
16180 Set all alignments to ON
16181 @end ifset
16182
16183 @item ^-A0^/ALIGN=OFF^
16184 Set all alignments to OFF
16185
16186 @item ^-A1^/ALIGN=COLONS^
16187 Align @code{:} in declarations
16188
16189 @item ^-A2^/ALIGN=DECLARATIONS^
16190 Align @code{:=} in initializations in declarations
16191
16192 @item ^-A3^/ALIGN=STATEMENTS^
16193 Align @code{:=} in assignment statements
16194
16195 @item ^-A4^/ALIGN=ARROWS^
16196 Align @code{=>} in associations
16197
16198 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
16199 Align @code{at} keywords in the component clauses in record
16200 representation clauses
16201 @end table
16202
16203 @noindent
16204 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
16205 is allowed.
16206
16207 @node Casing Control
16208 @subsection Casing Control
16209 @cindex Casing control in @command{gnatpp}
16210
16211 @noindent
16212 @command{gnatpp} allows you to specify the casing for reserved words,
16213 pragma names, attribute designators and identifiers.
16214 For identifiers you may define a
16215 general rule for name casing but also override this rule
16216 via a set of dictionary files.
16217
16218 Three types of casing are supported: lower case, upper case, and mixed case.
16219 Lower and upper case are self-explanatory (but since some letters in
16220 Latin1 and other GNAT-supported character sets
16221 exist only in lower-case form, an upper case conversion will have no
16222 effect on them.)
16223 ``Mixed case'' means that the first letter, and also each letter immediately
16224 following an underscore, are converted to their uppercase forms;
16225 all the other letters are converted to their lowercase forms.
16226
16227 @table @option
16228 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
16229 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
16230 Attribute designators are lower case
16231
16232 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
16233 Attribute designators are upper case
16234
16235 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
16236 Attribute designators are mixed case (this is the default)
16237
16238 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
16239 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
16240 Keywords (technically, these are known in Ada as @emph{reserved words}) are
16241 lower case (this is the default)
16242
16243 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
16244 Keywords are upper case
16245
16246 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
16247 @item ^-nD^/NAME_CASING=AS_DECLARED^
16248 Name casing for defining occurrences are as they appear in the source file
16249 (this is the default)
16250
16251 @item ^-nU^/NAME_CASING=UPPER_CASE^
16252 Names are in upper case
16253
16254 @item ^-nL^/NAME_CASING=LOWER_CASE^
16255 Names are in lower case
16256
16257 @item ^-nM^/NAME_CASING=MIXED_CASE^
16258 Names are in mixed case
16259
16260 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
16261 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
16262 Pragma names are lower case
16263
16264 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
16265 Pragma names are upper case
16266
16267 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
16268 Pragma names are mixed case (this is the default)
16269
16270 @item ^-D@var{file}^/DICTIONARY=@var{file}^
16271 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
16272 Use @var{file} as a @emph{dictionary file} that defines
16273 the casing for a set of specified names,
16274 thereby overriding the effect on these names by
16275 any explicit or implicit
16276 ^-n^/NAME_CASING^ switch.
16277 To supply more than one dictionary file,
16278 use ^several @option{-D} switches^a list of files as options^.
16279
16280 @noindent
16281 @option{gnatpp} implicitly uses a @emph{default dictionary file}
16282 to define the casing for the Ada predefined names and
16283 the names declared in the GNAT libraries.
16284
16285 @item ^-D-^/SPECIFIC_CASING^
16286 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
16287 Do not use the default dictionary file;
16288 instead, use the casing
16289 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
16290 dictionary file(s)
16291 @end table
16292
16293 @noindent
16294 The structure of a dictionary file, and details on the conventions
16295 used in the default dictionary file, are defined in @ref{Name Casing}.
16296
16297 The @option{^-D-^/SPECIFIC_CASING^} and
16298 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
16299 compatible.
16300
16301 @node Construct Layout Control
16302 @subsection Construct Layout Control
16303 @cindex Layout control in @command{gnatpp}
16304
16305 @noindent
16306 This group of @command{gnatpp} switches controls the layout of comments and
16307 complex syntactic constructs.  See @ref{Formatting Comments} for details
16308 on their effect.
16309
16310 @table @option
16311 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
16312 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
16313 All the comments remain unchanged
16314
16315 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
16316 GNAT-style comment line indentation (this is the default).
16317
16318 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
16319 Reference-manual comment line indentation.
16320
16321 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
16322 GNAT-style comment beginning
16323
16324 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
16325 Reformat comment blocks
16326
16327 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
16328 Keep unchanged special form comments
16329
16330 Reformat comment blocks
16331
16332 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
16333 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
16334 GNAT-style layout (this is the default)
16335
16336 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
16337 Compact layout
16338
16339 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
16340 Uncompact layout
16341
16342 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
16343 @item ^-N^/NOTABS^
16344 All the VT characters are removed from the comment text. All the HT characters
16345 are expanded with the sequences of space characters to get to the next tab
16346 stops.
16347
16348 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
16349 @item ^--no-separate-is^/NO_SEPARATE_IS^
16350 Do not place the keyword @code{is} on a separate line in a subprogram body in
16351 case if the spec occupies more then one line.
16352
16353 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
16354 @item ^--separate-label^/SEPARATE_LABEL^
16355 Place statement label(s) on a separate line, with the following statement
16356 on the next line.
16357
16358 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
16359 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
16360 Place the keyword @code{loop} in FOR and WHILE loop statements and the
16361 keyword @code{then} in IF statements on a separate line.
16362
16363 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
16364 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
16365 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
16366 keyword @code{then} in IF statements on a separate line. This option is
16367 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16368
16369 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16370 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16371 Start each USE clause in a context clause from a separate line.
16372
16373 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16374 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16375 Use a separate line for a loop or block statement name, but do not use an extra
16376 indentation level for the statement itself.
16377
16378 @end table
16379
16380 @ifclear vms
16381 @noindent
16382 The @option{-c1} and @option{-c2} switches are incompatible.
16383 The @option{-c3} and @option{-c4} switches are compatible with each other and
16384 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16385 the other comment formatting switches.
16386
16387 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16388 @end ifclear
16389
16390 @ifset vms
16391 @noindent
16392 For the @option{/COMMENTS_LAYOUT} qualifier:
16393 @itemize @bullet
16394 @item
16395 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16396 @item
16397 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16398 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16399 @end itemize
16400
16401 @noindent
16402 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16403 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16404 @end ifset
16405
16406 @node General Text Layout Control
16407 @subsection General Text Layout Control
16408
16409 @noindent
16410 These switches allow control over line length and indentation.
16411
16412 @table @option
16413 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16414 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16415 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16416
16417 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16418 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16419 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16420
16421 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16422 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16423 Indentation level for continuation lines (relative to the line being
16424 continued), @var{nnn} from 1@dots{}9.
16425 The default
16426 value is one less then the (normal) indentation level, unless the
16427 indentation is set to 1 (in which case the default value for continuation
16428 line indentation is also 1)
16429 @end table
16430
16431 @node Other Formatting Options
16432 @subsection Other Formatting Options
16433
16434 @noindent
16435 These switches control the inclusion of missing end/exit labels, and
16436 the indentation level in @b{case} statements.
16437
16438 @table @option
16439 @item ^-e^/NO_MISSED_LABELS^
16440 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16441 Do not insert missing end/exit labels. An end label is the name of
16442 a construct that may optionally be repeated at the end of the
16443 construct's declaration;
16444 e.g., the names of packages, subprograms, and tasks.
16445 An exit label is the name of a loop that may appear as target
16446 of an exit statement within the loop.
16447 By default, @command{gnatpp} inserts these end/exit labels when
16448 they are absent from the original source. This option suppresses such
16449 insertion, so that the formatted source reflects the original.
16450
16451 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16452 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16453 Insert a Form Feed character after a pragma Page.
16454
16455 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16456 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16457 Do not use an additional indentation level for @b{case} alternatives
16458 and variants if there are @var{nnn} or more (the default
16459 value is 10).
16460 If @var{nnn} is 0, an additional indentation level is
16461 used for @b{case} alternatives and variants regardless of their number.
16462 @end table
16463
16464 @node Setting the Source Search Path
16465 @subsection Setting the Source Search Path
16466
16467 @noindent
16468 To define the search path for the input source file, @command{gnatpp}
16469 uses the same switches as the GNAT compiler, with the same effects.
16470
16471 @table @option
16472 @item ^-I^/SEARCH=^@var{dir}
16473 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16474 The same as the corresponding gcc switch
16475
16476 @item ^-I-^/NOCURRENT_DIRECTORY^
16477 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16478 The same as the corresponding gcc switch
16479
16480 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16481 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16482 The same as the corresponding gcc switch
16483
16484 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16485 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16486 The same as the corresponding gcc switch
16487
16488 @end table
16489
16490 @node Output File Control
16491 @subsection Output File Control
16492
16493 @noindent
16494 By default the output is sent to the file whose name is obtained by appending
16495 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16496 (if the file with this name already exists, it is unconditionally overwritten).
16497 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16498 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16499 as output file.
16500 The output may be redirected by the following switches:
16501
16502 @table @option
16503 @item ^-pipe^/STANDARD_OUTPUT^
16504 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16505 Send the output to @code{Standard_Output}
16506
16507 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16508 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16509 Write the output into @var{output_file}.
16510 If @var{output_file} already exists, @command{gnatpp} terminates without
16511 reading or processing the input file.
16512
16513 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16514 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16515 Write the output into @var{output_file}, overwriting the existing file
16516 (if one is present).
16517
16518 @item ^-r^/REPLACE^
16519 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16520 Replace the input source file with the reformatted output, and copy the
16521 original input source into the file whose name is obtained by appending the
16522 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16523 If a file with this name already exists, @command{gnatpp} terminates without
16524 reading or processing the input file.
16525
16526 @item ^-rf^/OVERRIDING_REPLACE^
16527 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16528 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16529 already exists, it is overwritten.
16530
16531 @item ^-rnb^/REPLACE_NO_BACKUP^
16532 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16533 Replace the input source file with the reformatted output without
16534 creating any backup copy of the input source.
16535
16536 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16537 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16538 Specifies the format of the reformatted output file. The @var{xxx}
16539 ^string specified with the switch^option^ may be either
16540 @itemize @bullet
16541 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16542 @item ``@option{^crlf^CRLF^}''
16543 the same as @option{^crlf^CRLF^}
16544 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16545 @item ``@option{^lf^LF^}''
16546 the same as @option{^unix^UNIX^}
16547 @end itemize
16548
16549 @item ^-W^/RESULT_ENCODING=^@var{e}
16550 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16551 Specify the wide character encoding method used to write the code in the
16552 result file
16553 @var{e} is one of the following:
16554
16555 @itemize @bullet
16556
16557 @item ^h^HEX^
16558 Hex encoding
16559
16560 @item ^u^UPPER^
16561 Upper half encoding
16562
16563 @item ^s^SHIFT_JIS^
16564 Shift/JIS encoding
16565
16566 @item ^e^EUC^
16567 EUC encoding
16568
16569 @item ^8^UTF8^
16570 UTF-8 encoding
16571
16572 @item ^b^BRACKETS^
16573 Brackets encoding (default value)
16574 @end itemize
16575
16576 @end table
16577
16578 @noindent
16579 Options @option{^-pipe^/STANDARD_OUTPUT^},
16580 @option{^-o^/OUTPUT^} and
16581 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16582 contains only one file to reformat.
16583 Option
16584 @option{^--eol^/END_OF_LINE^}
16585 and
16586 @option{^-W^/RESULT_ENCODING^}
16587 cannot be used together
16588 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16589
16590 @node Other gnatpp Switches
16591 @subsection Other @code{gnatpp} Switches
16592
16593 @noindent
16594 The additional @command{gnatpp} switches are defined in this subsection.
16595
16596 @table @option
16597 @item ^-files @var{filename}^/FILES=@var{output_file}^
16598 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16599 Take the argument source files from the specified file. This file should be an
16600 ordinary textual file containing file names separated by spaces or
16601 line breaks. You can use this switch more then once in the same call to
16602 @command{gnatpp}. You also can combine this switch with explicit list of
16603 files.
16604
16605 @item ^-v^/VERBOSE^
16606 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16607 Verbose mode;
16608 @command{gnatpp} generates version information and then
16609 a trace of the actions it takes to produce or obtain the ASIS tree.
16610
16611 @item ^-w^/WARNINGS^
16612 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16613 Warning mode;
16614 @command{gnatpp} generates a warning whenever it cannot provide
16615 a required layout in the result source.
16616 @end table
16617
16618 @node Formatting Rules
16619 @section Formatting Rules
16620
16621 @noindent
16622 The following subsections show how @command{gnatpp} treats ``white space'',
16623 comments, program layout, and name casing.
16624 They provide the detailed descriptions of the switches shown above.
16625
16626 @menu
16627 * White Space and Empty Lines::
16628 * Formatting Comments::
16629 * Construct Layout::
16630 * Name Casing::
16631 @end menu
16632
16633 @node White Space and Empty Lines
16634 @subsection White Space and Empty Lines
16635
16636 @noindent
16637 @command{gnatpp} does not have an option to control space characters.
16638 It will add or remove spaces according to the style illustrated by the
16639 examples in the @cite{Ada Reference Manual}.
16640
16641 The only format effectors
16642 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16643 that will appear in the output file are platform-specific line breaks,
16644 and also format effectors within (but not at the end of) comments.
16645 In particular, each horizontal tab character that is not inside
16646 a comment will be treated as a space and thus will appear in the
16647 output file as zero or more spaces depending on
16648 the reformatting of the line in which it appears.
16649 The only exception is a Form Feed character, which is inserted after a
16650 pragma @code{Page} when @option{-ff} is set.
16651
16652 The output file will contain no lines with trailing ``white space'' (spaces,
16653 format effectors).
16654
16655 Empty lines in the original source are preserved
16656 only if they separate declarations or statements.
16657 In such contexts, a
16658 sequence of two or more empty lines is replaced by exactly one empty line.
16659 Note that a blank line will be removed if it separates two ``comment blocks''
16660 (a comment block is a sequence of whole-line comments).
16661 In order to preserve a visual separation between comment blocks, use an
16662 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16663 Likewise, if for some reason you wish to have a sequence of empty lines,
16664 use a sequence of empty comments instead.
16665
16666 @node Formatting Comments
16667 @subsection Formatting Comments
16668
16669 @noindent
16670 Comments in Ada code are of two kinds:
16671 @itemize @bullet
16672 @item
16673 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16674 ``white space'') on a line
16675
16676 @item
16677 an @emph{end-of-line comment}, which follows some other Ada lexical element
16678 on the same line.
16679 @end itemize
16680
16681 @noindent
16682 The indentation of a whole-line comment is that of either
16683 the preceding or following line in
16684 the formatted source, depending on switch settings as will be described below.
16685
16686 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16687 between the end of the preceding Ada lexical element and the beginning
16688 of the comment as appear in the original source,
16689 unless either the comment has to be split to
16690 satisfy the line length limitation, or else the next line contains a
16691 whole line comment that is considered a continuation of this end-of-line
16692 comment (because it starts at the same position).
16693 In the latter two
16694 cases, the start of the end-of-line comment is moved right to the nearest
16695 multiple of the indentation level.
16696 This may result in a ``line overflow'' (the right-shifted comment extending
16697 beyond the maximum line length), in which case the comment is split as
16698 described below.
16699
16700 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16701 (GNAT-style comment line indentation)
16702 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16703 (reference-manual comment line indentation).
16704 With reference-manual style, a whole-line comment is indented as if it
16705 were a declaration or statement at the same place
16706 (i.e., according to the indentation of the preceding line(s)).
16707 With GNAT style, a whole-line comment that is immediately followed by an
16708 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16709 word @b{begin}, is indented based on the construct that follows it.
16710
16711 For example:
16712 @smallexample @c ada
16713 @cartouche
16714 if A then
16715     null;
16716        -- some comment
16717 else
16718    null;
16719 end if;
16720 @end cartouche
16721 @end smallexample
16722
16723 @noindent
16724 Reference-manual indentation produces:
16725
16726 @smallexample @c ada
16727 @cartouche
16728 if A then
16729    null;
16730    --  some comment
16731 else
16732    null;
16733 end if;
16734 @end cartouche
16735 @end smallexample
16736
16737 @noindent
16738 while GNAT-style indentation produces:
16739
16740 @smallexample @c ada
16741 @cartouche
16742 if A then
16743    null;
16744 --  some comment
16745 else
16746    null;
16747 end if;
16748 @end cartouche
16749 @end smallexample
16750
16751 @noindent
16752 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16753 (GNAT style comment beginning) has the following
16754 effect:
16755
16756 @itemize @bullet
16757 @item
16758 For each whole-line comment that does not end with two hyphens,
16759 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16760 to ensure that there are at least two spaces between these hyphens and the
16761 first non-blank character of the comment.
16762 @end itemize
16763
16764 @noindent
16765 For an end-of-line comment, if in the original source the next line is a
16766 whole-line comment that starts at the same position
16767 as the end-of-line comment,
16768 then the whole-line comment (and all whole-line comments
16769 that follow it and that start at the same position)
16770 will start at this position in the output file.
16771
16772 @noindent
16773 That is, if in the original source we have:
16774
16775 @smallexample @c ada
16776 @cartouche
16777 begin
16778 A := B + C;            --  B must be in the range Low1..High1
16779                        --  C must be in the range Low2..High2
16780              --B+C will be in the range Low1+Low2..High1+High2
16781 X := X + 1;
16782 @end cartouche
16783 @end smallexample
16784
16785 @noindent
16786 Then in the formatted source we get
16787
16788 @smallexample @c ada
16789 @cartouche
16790 begin
16791    A := B + C;            --  B must be in the range Low1..High1
16792                           --  C must be in the range Low2..High2
16793    --  B+C will be in the range Low1+Low2..High1+High2
16794    X := X + 1;
16795 @end cartouche
16796 @end smallexample
16797
16798 @noindent
16799 A comment that exceeds the line length limit will be split.
16800 Unless switch
16801 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16802 the line belongs to a reformattable block, splitting the line generates a
16803 @command{gnatpp} warning.
16804 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16805 comments may be reformatted in typical
16806 word processor style (that is, moving words between lines and putting as
16807 many words in a line as possible).
16808
16809 @noindent
16810 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16811 that has a special format (that is, a character that is neither a letter nor digit
16812 not white space nor line break immediately following the leading @code{--} of
16813 the comment) should be without any change moved from the argument source
16814 into reformatted source. This switch allows to preserve comments that are used
16815 as a special marks in the code (e.g.@: SPARK annotation).
16816
16817 @node Construct Layout
16818 @subsection Construct Layout
16819
16820 @noindent
16821 In several cases the suggested layout in the Ada Reference Manual includes
16822 an extra level of indentation that many programmers prefer to avoid. The
16823 affected cases include:
16824
16825 @itemize @bullet
16826
16827 @item Record type declaration (RM 3.8)
16828
16829 @item Record representation clause (RM 13.5.1)
16830
16831 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16832
16833 @item Block statement in case if a block has a statement identifier (RM 5.6)
16834 @end itemize
16835
16836 @noindent
16837 In compact mode (when GNAT style layout or compact layout is set),
16838 the pretty printer uses one level of indentation instead
16839 of two. This is achieved in the record definition and record representation
16840 clause cases by putting the @code{record} keyword on the same line as the
16841 start of the declaration or representation clause, and in the block and loop
16842 case by putting the block or loop header on the same line as the statement
16843 identifier.
16844
16845 @noindent
16846 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16847 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16848 layout on the one hand, and uncompact layout
16849 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16850 can be illustrated by the following examples:
16851
16852 @iftex
16853 @cartouche
16854 @multitable @columnfractions .5 .5
16855 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16856
16857 @item
16858 @smallexample @c ada
16859 type q is record
16860    a : integer;
16861    b : integer;
16862 end record;
16863 @end smallexample
16864 @tab
16865 @smallexample @c ada
16866 type q is
16867    record
16868       a : integer;
16869       b : integer;
16870    end record;
16871 @end smallexample
16872
16873 @item
16874 @smallexample @c ada
16875 for q use record
16876    a at 0 range  0 .. 31;
16877    b at 4 range  0 .. 31;
16878 end record;
16879 @end smallexample
16880 @tab
16881 @smallexample @c ada
16882 for q use
16883    record
16884       a at 0 range  0 .. 31;
16885       b at 4 range  0 .. 31;
16886    end record;
16887 @end smallexample
16888
16889 @item
16890 @smallexample @c ada
16891 Block : declare
16892    A : Integer := 3;
16893 begin
16894    Proc (A, A);
16895 end Block;
16896 @end smallexample
16897 @tab
16898 @smallexample @c ada
16899 Block :
16900    declare
16901       A : Integer := 3;
16902    begin
16903       Proc (A, A);
16904    end Block;
16905 @end smallexample
16906
16907 @item
16908 @smallexample @c ada
16909 Clear : for J in 1 .. 10 loop
16910    A (J) := 0;
16911 end loop Clear;
16912 @end smallexample
16913 @tab
16914 @smallexample @c ada
16915 Clear :
16916    for J in 1 .. 10 loop
16917       A (J) := 0;
16918    end loop Clear;
16919 @end smallexample
16920 @end multitable
16921 @end cartouche
16922 @end iftex
16923
16924 @ifnottex
16925 @smallexample
16926 @cartouche
16927 GNAT style, compact layout              Uncompact layout
16928
16929 type q is record                        type q is
16930    a : integer;                            record
16931    b : integer;                               a : integer;
16932 end record;                                   b : integer;
16933                                            end record;
16934
16935 for q use record                        for q use
16936    a at 0 range  0 .. 31;                  record
16937    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16938 end record;                                   b at 4 range  0 .. 31;
16939                                            end record;
16940
16941 Block : declare                         Block :
16942    A : Integer := 3;                       declare
16943 begin                                         A : Integer := 3;
16944    Proc (A, A);                            begin
16945 end Block;                                    Proc (A, A);
16946                                            end Block;
16947
16948 Clear : for J in 1 .. 10 loop           Clear :
16949    A (J) := 0;                             for J in 1 .. 10 loop
16950 end loop Clear;                               A (J) := 0;
16951                                            end loop Clear;
16952 @end cartouche
16953 @end smallexample
16954 @end ifnottex
16955
16956 @noindent
16957 A further difference between GNAT style layout and compact layout is that
16958 GNAT style layout inserts empty lines as separation for
16959 compound statements, return statements and bodies.
16960
16961 Note that the layout specified by
16962 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16963 for named block and loop statements overrides the layout defined by these
16964 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16965 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16966 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16967
16968 @node Name Casing
16969 @subsection Name Casing
16970
16971 @noindent
16972 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16973 the same casing as the corresponding defining identifier.
16974
16975 You control the casing for defining occurrences via the
16976 @option{^-n^/NAME_CASING^} switch.
16977 @ifclear vms
16978 With @option{-nD} (``as declared'', which is the default),
16979 @end ifclear
16980 @ifset vms
16981 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16982 @end ifset
16983 defining occurrences appear exactly as in the source file
16984 where they are declared.
16985 The other ^values for this switch^options for this qualifier^ ---
16986 @option{^-nU^UPPER_CASE^},
16987 @option{^-nL^LOWER_CASE^},
16988 @option{^-nM^MIXED_CASE^} ---
16989 result in
16990 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16991 If @command{gnatpp} changes the casing of a defining
16992 occurrence, it analogously changes the casing of all the
16993 usage occurrences of this name.
16994
16995 If the defining occurrence of a name is not in the source compilation unit
16996 currently being processed by @command{gnatpp}, the casing of each reference to
16997 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16998 switch (subject to the dictionary file mechanism described below).
16999 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
17000 had affected the
17001 casing for the defining occurrence of the name.
17002
17003 Some names may need to be spelled with casing conventions that are not
17004 covered by the upper-, lower-, and mixed-case transformations.
17005 You can arrange correct casing by placing such names in a
17006 @emph{dictionary file},
17007 and then supplying a @option{^-D^/DICTIONARY^} switch.
17008 The casing of names from dictionary files overrides
17009 any @option{^-n^/NAME_CASING^} switch.
17010
17011 To handle the casing of Ada predefined names and the names from GNAT libraries,
17012 @command{gnatpp} assumes a default dictionary file.
17013 The name of each predefined entity is spelled with the same casing as is used
17014 for the entity in the @cite{Ada Reference Manual}.
17015 The name of each entity in the GNAT libraries is spelled with the same casing
17016 as is used in the declaration of that entity.
17017
17018 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
17019 default dictionary file.
17020 Instead, the casing for predefined and GNAT-defined names will be established
17021 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
17022 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
17023 will appear as just shown,
17024 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
17025 To ensure that even such names are rendered in uppercase,
17026 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
17027 (or else, less conveniently, place these names in upper case in a dictionary
17028 file).
17029
17030 A dictionary file is
17031 a plain text file; each line in this file can be either a blank line
17032 (containing only space characters and ASCII.HT characters), an Ada comment
17033 line, or the specification of exactly one @emph{casing schema}.
17034
17035 A casing schema is a string that has the following syntax:
17036
17037 @smallexample
17038 @cartouche
17039   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
17040
17041   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
17042 @end cartouche
17043 @end smallexample
17044
17045 @noindent
17046 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
17047 @var{identifier} lexical element and the @var{letter_or_digit} category.)
17048
17049 The casing schema string can be followed by white space and/or an Ada-style
17050 comment; any amount of white space is allowed before the string.
17051
17052 If a dictionary file is passed as
17053 @ifclear vms
17054 the value of a @option{-D@var{file}} switch
17055 @end ifclear
17056 @ifset vms
17057 an option to the @option{/DICTIONARY} qualifier
17058 @end ifset
17059 then for every
17060 simple name and every identifier, @command{gnatpp} checks if the dictionary
17061 defines the casing for the name or for some of its parts (the term ``subword''
17062 is used below to denote the part of a name which is delimited by ``_'' or by
17063 the beginning or end of the word and which does not contain any ``_'' inside):
17064
17065 @itemize @bullet
17066 @item
17067 if the whole name is in the dictionary, @command{gnatpp} uses for this name
17068 the casing defined by the dictionary; no subwords are checked for this word
17069
17070 @item
17071 for every subword @command{gnatpp} checks if the dictionary contains the
17072 corresponding string of the form @code{*@var{simple_identifier}*},
17073 and if it does, the casing of this @var{simple_identifier} is used
17074 for this subword
17075
17076 @item
17077 if the whole name does not contain any ``_'' inside, and if for this name
17078 the dictionary contains two entries - one of the form @var{identifier},
17079 and another - of the form *@var{simple_identifier}*, then the first one
17080 is applied to define the casing of this name
17081
17082 @item
17083 if more than one dictionary file is passed as @command{gnatpp} switches, each
17084 dictionary adds new casing exceptions and overrides all the existing casing
17085 exceptions set by the previous dictionaries
17086
17087 @item
17088 when @command{gnatpp} checks if the word or subword is in the dictionary,
17089 this check is not case sensitive
17090 @end itemize
17091
17092 @noindent
17093 For example, suppose we have the following source to reformat:
17094
17095 @smallexample @c ada
17096 @cartouche
17097 procedure test is
17098    name1 : integer := 1;
17099    name4_name3_name2 : integer := 2;
17100    name2_name3_name4 : Boolean;
17101    name1_var : Float;
17102 begin
17103    name2_name3_name4 := name4_name3_name2 > name1;
17104 end;
17105 @end cartouche
17106 @end smallexample
17107
17108 @noindent
17109 And suppose we have two dictionaries:
17110
17111 @smallexample
17112 @cartouche
17113 @i{dict1:}
17114    NAME1
17115    *NaMe3*
17116    *Name1*
17117 @end cartouche
17118
17119 @cartouche
17120 @i{dict2:}
17121   *NAME3*
17122 @end cartouche
17123 @end smallexample
17124
17125 @noindent
17126 If @command{gnatpp} is called with the following switches:
17127
17128 @smallexample
17129 @ifclear vms
17130 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
17131 @end ifclear
17132 @ifset vms
17133 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
17134 @end ifset
17135 @end smallexample
17136
17137 @noindent
17138 then we will get the following name casing in the @command{gnatpp} output:
17139
17140 @smallexample @c ada
17141 @cartouche
17142 procedure Test is
17143    NAME1             : Integer := 1;
17144    Name4_NAME3_Name2 : Integer := 2;
17145    Name2_NAME3_Name4 : Boolean;
17146    Name1_Var         : Float;
17147 begin
17148    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
17149 end Test;
17150 @end cartouche
17151 @end smallexample
17152
17153 @c *********************************
17154 @node The GNAT Metric Tool gnatmetric
17155 @chapter The GNAT Metric Tool @command{gnatmetric}
17156 @findex gnatmetric
17157 @cindex Metric tool
17158
17159 @noindent
17160 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
17161 for computing various program metrics.
17162 It takes an Ada source file as input and generates a file containing the
17163 metrics data as output. Various switches control which
17164 metrics are computed and output.
17165
17166 @command{gnatmetric} generates and uses the ASIS
17167 tree for the input source and thus requires the input to be syntactically and
17168 semantically legal.
17169 If this condition is not met, @command{gnatmetric} will generate
17170 an error message; no metric information for this file will be
17171 computed and reported.
17172
17173 If the compilation unit contained in the input source depends semantically
17174 upon units in files located outside the current directory, you have to provide
17175 the source search path when invoking @command{gnatmetric}.
17176 If it depends semantically upon units that are contained
17177 in files with names that do not follow the GNAT file naming rules, you have to
17178 provide the configuration file describing the corresponding naming scheme (see
17179 the description of the @command{gnatmetric} switches below.)
17180 Alternatively, you may use a project file and invoke @command{gnatmetric}
17181 through the @command{gnat} driver.
17182
17183 The @command{gnatmetric} command has the form
17184
17185 @smallexample
17186 $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17187 @end smallexample
17188
17189 @noindent
17190 where
17191 @itemize @bullet
17192 @item
17193 @var{switches} specify the metrics to compute and define the destination for
17194 the output
17195
17196 @item
17197 Each @var{filename} is the name (including the extension) of a source
17198 file to process. ``Wildcards'' are allowed, and
17199 the file name may contain path information.
17200 If no @var{filename} is supplied, then the @var{switches} list must contain
17201 at least one
17202 @option{-files} switch (@pxref{Other gnatmetric Switches}).
17203 Including both a @option{-files} switch and one or more
17204 @var{filename} arguments is permitted.
17205
17206 @item
17207 @samp{-cargs @var{gcc_switches}} is a list of switches for
17208 @command{gcc}. They will be passed on to all compiler invocations made by
17209 @command{gnatmetric} to generate the ASIS trees. Here you can provide
17210 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17211 and use the @option{-gnatec} switch to set the configuration file.
17212 @end itemize
17213
17214 @menu
17215 * Switches for gnatmetric::
17216 @end menu
17217
17218 @node Switches for gnatmetric
17219 @section Switches for @command{gnatmetric}
17220
17221 @noindent
17222 The following subsections describe the various switches accepted by
17223 @command{gnatmetric}, organized by category.
17224
17225 @menu
17226 * Output Files Control::
17227 * Disable Metrics For Local Units::
17228 * Specifying a set of metrics to compute::
17229 * Other gnatmetric Switches::
17230 * Generate project-wide metrics::
17231 @end menu
17232
17233 @node Output Files Control
17234 @subsection Output File Control
17235 @cindex Output file control in @command{gnatmetric}
17236
17237 @noindent
17238 @command{gnatmetric} has two output formats. It can generate a
17239 textual (human-readable) form, and also XML. By default only textual
17240 output is generated.
17241
17242 When generating the output in textual form, @command{gnatmetric} creates
17243 for each Ada source file a corresponding text file
17244 containing the computed metrics, except for the case when the set of metrics
17245 specified by gnatmetric parameters consists only of metrics that are computed
17246 for the whole set of analyzed sources, but not for each Ada source.
17247 By default, this file is placed in the same directory as where the source
17248 file is located, and its name is obtained
17249 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
17250 input file.
17251
17252 All the output information generated in XML format is placed in a single
17253 file. By default this file is placed in the current directory and has the
17254 name ^@file{metrix.xml}^@file{METRIX$XML}^.
17255
17256 Some of the computed metrics are summed over the units passed to
17257 @command{gnatmetric}; for example, the total number of lines of code.
17258 By default this information is sent to @file{stdout}, but a file
17259 can be specified with the @option{-og} switch.
17260
17261 The following switches control the @command{gnatmetric} output:
17262
17263 @table @option
17264 @cindex @option{^-x^/XML^} (@command{gnatmetric})
17265 @item ^-x^/XML^
17266 Generate the XML output
17267
17268 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
17269 @item ^-xs^/XSD^
17270 Generate the XML output and the XML schema file that describes the structure
17271 of the XML metric report, this schema is assigned to the XML file. The schema
17272 file has the same name as the XML output file with @file{.xml} suffix replaced
17273 with @file{.xsd}
17274
17275 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
17276 @item ^-nt^/NO_TEXT^
17277 Do not generate the output in text form (implies @option{^-x^/XML^})
17278
17279 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
17280 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
17281 Put textual files with detailed metrics into @var{output_dir}
17282
17283 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
17284 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
17285 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
17286 in the name of the output file.
17287
17288 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
17289 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
17290 Put global metrics into @var{file_name}
17291
17292 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
17293 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
17294 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
17295
17296 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
17297 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
17298 Use ``short'' source file names in the output.  (The @command{gnatmetric}
17299 output includes the name(s) of the Ada source file(s) from which the metrics
17300 are computed.  By default each name includes the absolute path. The
17301 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
17302 to exclude all directory information from the file names that are output.)
17303
17304 @end table
17305
17306 @node Disable Metrics For Local Units
17307 @subsection Disable Metrics For Local Units
17308 @cindex Disable Metrics For Local Units in @command{gnatmetric}
17309
17310 @noindent
17311 @command{gnatmetric} relies on the GNAT compilation model @minus{}
17312 one compilation
17313 unit per one source file. It computes line metrics for the whole source
17314 file, and it also computes syntax
17315 and complexity metrics for the file's outermost unit.
17316
17317 By default, @command{gnatmetric} will also compute all metrics for certain
17318 kinds of locally declared program units:
17319
17320 @itemize @bullet
17321 @item
17322 subprogram (and generic subprogram) bodies;
17323
17324 @item
17325 package (and generic package) specs and bodies;
17326
17327 @item
17328 task object and type specifications and bodies;
17329
17330 @item
17331 protected object and type specifications and bodies.
17332 @end itemize
17333
17334 @noindent
17335 These kinds of entities will be referred to as
17336 @emph{eligible local program units}, or simply @emph{eligible local units},
17337 @cindex Eligible local unit (for @command{gnatmetric})
17338 in the discussion below.
17339
17340 Note that a subprogram declaration, generic instantiation,
17341 or renaming declaration only receives metrics
17342 computation when it appear as the outermost entity
17343 in a source file.
17344
17345 Suppression of metrics computation for eligible local units can be
17346 obtained via the following switch:
17347
17348 @table @option
17349 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
17350 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
17351 Do not compute detailed metrics for eligible local program units
17352
17353 @end table
17354
17355 @node Specifying a set of metrics to compute
17356 @subsection Specifying a set of metrics to compute
17357
17358 @noindent
17359 By default all the metrics are computed and reported. The switches
17360 described in this subsection allow you to control, on an individual
17361 basis, whether metrics are computed and
17362 reported. If at least one positive metric
17363 switch is specified (that is, a switch that defines that a given
17364 metric or set of metrics is to be computed), then only
17365 explicitly specified metrics are reported.
17366
17367 @menu
17368 * Line Metrics Control::
17369 * Syntax Metrics Control::
17370 * Complexity Metrics Control::
17371 * Object-Oriented Metrics Control::
17372 @end menu
17373
17374 @node Line Metrics Control
17375 @subsubsection Line Metrics Control
17376 @cindex Line metrics control in @command{gnatmetric}
17377
17378 @noindent
17379 For any (legal) source file, and for each of its
17380 eligible local program units, @command{gnatmetric} computes the following
17381 metrics:
17382
17383 @itemize @bullet
17384 @item
17385 the total number of lines;
17386
17387 @item
17388 the total number of code lines (i.e., non-blank lines that are not comments)
17389
17390 @item
17391 the number of comment lines
17392
17393 @item
17394 the number of code lines containing end-of-line comments;
17395
17396 @item
17397 the comment percentage: the ratio between the number of lines that contain
17398 comments and the number of all non-blank lines, expressed as a percentage;
17399
17400 @item
17401 the number of empty lines and lines containing only space characters and/or
17402 format effectors (blank lines)
17403
17404 @item
17405 the average number of code lines in subprogram bodies, task bodies, entry
17406 bodies and statement sequences in package bodies (this metric is only computed
17407 across the whole set of the analyzed units)
17408
17409 @end itemize
17410
17411 @noindent
17412 @command{gnatmetric} sums the values of the line metrics for all the
17413 files being processed and then generates the cumulative results. The tool
17414 also computes for all the files being processed the average number of code
17415 lines in bodies.
17416
17417 You can use the following switches to select the specific line metrics
17418 to be computed and reported.
17419
17420 @table @option
17421 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17422
17423 @ifclear vms
17424 @cindex @option{--no-lines@var{x}}
17425 @end ifclear
17426
17427 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
17428 Report all the line metrics
17429
17430 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
17431 Do not report any of line metrics
17432
17433 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
17434 Report the number of all lines
17435
17436 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
17437 Do not report the number of all lines
17438
17439 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
17440 Report the number of code lines
17441
17442 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
17443 Do not report the number of code lines
17444
17445 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
17446 Report the number of comment lines
17447
17448 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
17449 Do not report the number of comment lines
17450
17451 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
17452 Report the number of code lines containing
17453 end-of-line comments
17454
17455 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
17456 Do not report the number of code lines containing
17457 end-of-line comments
17458
17459 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
17460 Report the comment percentage in the program text
17461
17462 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
17463 Do not report the comment percentage in the program text
17464
17465 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
17466 Report the number of blank lines
17467
17468 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
17469 Do not report the number of blank lines
17470
17471 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
17472 Report the average number of code lines in subprogram bodies, task bodies,
17473 entry bodies and statement sequences in package bodies. The metric is computed
17474 and reported for the whole set of processed Ada sources only.
17475
17476 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
17477 Do not report the average number of code lines in subprogram bodies,
17478 task bodies, entry bodies and statement sequences in package bodies.
17479
17480 @end table
17481
17482 @node Syntax Metrics Control
17483 @subsubsection Syntax Metrics Control
17484 @cindex Syntax metrics control in @command{gnatmetric}
17485
17486 @noindent
17487 @command{gnatmetric} computes various syntactic metrics for the
17488 outermost unit and for each eligible local unit:
17489
17490 @table @emph
17491 @item LSLOC (``Logical Source Lines Of Code'')
17492 The total number of declarations and the total number of statements
17493
17494 @item Maximal static nesting level of inner program units
17495 According to
17496 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17497 package, a task unit, a protected unit, a
17498 protected entry, a generic unit, or an explicitly declared subprogram other
17499 than an enumeration literal.''
17500
17501 @item Maximal nesting level of composite syntactic constructs
17502 This corresponds to the notion of the
17503 maximum nesting level in the GNAT built-in style checks
17504 (@pxref{Style Checking})
17505 @end table
17506
17507 @noindent
17508 For the outermost unit in the file, @command{gnatmetric} additionally computes
17509 the following metrics:
17510
17511 @table @emph
17512 @item Public subprograms
17513 This metric is computed for package specs. It is the
17514 number of subprograms and generic subprograms declared in the visible
17515 part (including the visible part of nested packages, protected objects, and
17516 protected types).
17517
17518 @item All subprograms
17519 This metric is computed for bodies and subunits. The
17520 metric is equal to a total number of subprogram bodies in the compilation
17521 unit.
17522 Neither generic instantiations nor renamings-as-a-body nor body stubs
17523 are counted. Any subprogram body is counted, independently of its nesting
17524 level and enclosing constructs. Generic bodies and bodies of protected
17525 subprograms are counted in the same way as ``usual'' subprogram bodies.
17526
17527 @item Public types
17528 This metric is computed for package specs and
17529 generic package declarations. It is the total number of types
17530 that can be referenced from outside this compilation unit, plus the
17531 number of types from all the visible parts of all the visible generic
17532 packages. Generic formal types are not counted.  Only types, not subtypes,
17533 are included.
17534
17535 @noindent
17536 Along with the total number of public types, the following
17537 types are counted and reported separately:
17538
17539 @itemize @bullet
17540 @item
17541 Abstract types
17542
17543 @item
17544 Root tagged types (abstract, non-abstract, private, non-private). Type
17545 extensions are @emph{not} counted
17546
17547 @item
17548 Private types (including private extensions)
17549
17550 @item
17551 Task types
17552
17553 @item
17554 Protected types
17555
17556 @end itemize
17557
17558 @item All types
17559 This metric is computed for any compilation unit. It is equal to the total
17560 number of the declarations of different types given in the compilation unit.
17561 The private and the corresponding full type declaration are counted as one
17562 type declaration. Incomplete type declarations and generic formal types
17563 are not counted.
17564 No distinction is made among different kinds of types (abstract,
17565 private etc.); the total number of types is computed and reported.
17566
17567 @end table
17568
17569 @noindent
17570 By default, all the syntax metrics are computed and reported. You can use the
17571 following switches to select specific syntax metrics.
17572
17573 @table @option
17574
17575 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17576
17577 @ifclear vms
17578 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17579 @end ifclear
17580
17581 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
17582 Report all the syntax metrics
17583
17584 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
17585 Do not report any of syntax metrics
17586
17587 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
17588 Report the total number of declarations
17589
17590 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
17591 Do not report the total number of declarations
17592
17593 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
17594 Report the total number of statements
17595
17596 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
17597 Do not report the total number of statements
17598
17599 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
17600 Report the number of public subprograms in a compilation unit
17601
17602 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
17603 Do not report the number of public subprograms in a compilation unit
17604
17605 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
17606 Report the number of all the subprograms in a compilation unit
17607
17608 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
17609 Do not report the number of all the subprograms in a compilation unit
17610
17611 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
17612 Report the number of public types in a compilation unit
17613
17614 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
17615 Do not report the number of public types in a compilation unit
17616
17617 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
17618 Report the number of all the types in a compilation unit
17619
17620 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
17621 Do not report the number of all the types in a compilation unit
17622
17623 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
17624 Report the maximal program unit nesting level
17625
17626 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17627 Do not report the maximal program unit nesting level
17628
17629 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
17630 Report the maximal construct nesting level
17631
17632 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
17633 Do not report the maximal construct nesting level
17634
17635 @end table
17636
17637 @node Complexity Metrics Control
17638 @subsubsection Complexity Metrics Control
17639 @cindex Complexity metrics control in @command{gnatmetric}
17640
17641 @noindent
17642 For a program unit that is an executable body (a subprogram body (including
17643 generic bodies), task body, entry body or a package body containing
17644 its own statement sequence) @command{gnatmetric} computes the following
17645 complexity metrics:
17646
17647 @itemize @bullet
17648 @item
17649 McCabe cyclomatic complexity;
17650
17651 @item
17652 McCabe essential complexity;
17653
17654 @item
17655 maximal loop nesting level
17656
17657 @end itemize
17658
17659 @noindent
17660 The McCabe complexity metrics are defined
17661 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17662
17663 According to McCabe, both control statements and short-circuit control forms
17664 should be taken into account when computing cyclomatic complexity. For each
17665 body, we compute three metric values:
17666
17667 @itemize @bullet
17668 @item
17669 the complexity introduced by control
17670 statements only, without taking into account short-circuit forms,
17671
17672 @item
17673 the complexity introduced by short-circuit control forms only, and
17674
17675 @item
17676 the total
17677 cyclomatic complexity, which is the sum of these two values.
17678 @end itemize
17679
17680 @noindent
17681 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17682 the code in the exception handlers and in all the nested program units.
17683
17684 By default, all the complexity metrics are computed and reported.
17685 For more fine-grained control you can use
17686 the following switches:
17687
17688 @table @option
17689 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17690
17691 @ifclear vms
17692 @cindex @option{--no-complexity@var{x}}
17693 @end ifclear
17694
17695 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
17696 Report all the complexity metrics
17697
17698 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
17699 Do not report any of complexity metrics
17700
17701 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
17702 Report the McCabe Cyclomatic Complexity
17703
17704 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
17705 Do not report the McCabe Cyclomatic Complexity
17706
17707 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
17708 Report the Essential Complexity
17709
17710 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
17711 Do not report the Essential Complexity
17712
17713 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17714 Report maximal loop nesting level
17715
17716 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
17717 Do not report maximal loop nesting level
17718
17719 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
17720 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17721 task bodies, entry bodies and statement sequences in package bodies.
17722 The metric is computed and reported for whole set of processed Ada sources
17723 only.
17724
17725 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
17726 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17727 bodies, task bodies, entry bodies and statement sequences in package bodies
17728
17729 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17730 @item ^-ne^/NO_EXITS_AS_GOTOS^
17731 Do not consider @code{exit} statements as @code{goto}s when
17732 computing Essential Complexity
17733
17734 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
17735 Report the extra exit points for subprogram bodies. As an exit point, this
17736 metric counts @code{return} statements and raise statements in case when the
17737 raised exception is not handled in the same body. In case of a function this
17738 metric subtracts 1 from the number of exit points, because a function body
17739 must contain at least one @code{return} statement.
17740
17741 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
17742 Do not report the extra exit points for subprogram bodies
17743 @end table
17744
17745
17746 @node Object-Oriented Metrics Control
17747 @subsubsection Object-Oriented Metrics Control
17748 @cindex Object-Oriented metrics control in @command{gnatmetric}
17749
17750 @noindent
17751 @cindex Coupling metrics (in in @command{gnatmetric})
17752 Coupling metrics are object-oriented metrics that measure the
17753 dependencies between a given class (or a group of classes) and the
17754 ``external world'' (that is, the other classes in the program). In this
17755 subsection the term ``class'' is used in its
17756 traditional object-oriented programming sense
17757 (an instantiable module that contains data and/or method members).
17758 A @emph{category} (of classes)
17759 is a group of closely related classes that are reused and/or
17760 modified together.
17761
17762 A class @code{K}'s @emph{efferent coupling} is the number of classes
17763 that @code{K} depends upon.
17764 A category's efferent coupling is the number of classes outside the
17765 category that the classes inside the category depend upon.
17766
17767 A class @code{K}'s @emph{afferent coupling} is the number of classes
17768 that depend upon @code{K}.
17769 A category's afferent coupling is the number of classes outside the
17770 category that depend on classes belonging to the category.
17771
17772 Ada's implementation of the object-oriented paradigm does not use the
17773 traditional class notion, so the definition of the coupling
17774 metrics for Ada maps the class and class category notions
17775 onto Ada constructs.
17776
17777 For the coupling metrics, several kinds of modules -- a library package,
17778 a library generic package, and a library generic package instantiation --
17779 that define a tagged type or an interface type are
17780 considered to be a class. A category consists of a library package (or
17781 a library generic package) that defines a tagged or an interface type,
17782 together with all its descendant (generic) packages that define tagged
17783 or interface types. For any package counted as a class,
17784 its body and subunits (if any) are considered
17785 together with its spec when counting the dependencies, and coupling
17786 metrics are reported for spec units only. For dependencies
17787 between classes, the Ada semantic dependencies are considered.
17788 For coupling metrics, only dependencies on units that are considered as
17789 classes, are considered.
17790
17791 When computing coupling metrics, @command{gnatmetric} counts only
17792 dependencies between units that are arguments of the gnatmetric call.
17793 Coupling metrics are program-wide (or project-wide) metrics, so to
17794 get a valid result, you should call @command{gnatmetric} for
17795 the whole set of sources that make up your program. It can be done
17796 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17797 option (see See @ref{The GNAT Driver and Project Files} for details.
17798
17799 By default, all the coupling metrics are disabled. You can use the following
17800 switches to specify the coupling metrics to be computed and reported:
17801
17802 @table @option
17803
17804 @ifclear vms
17805 @cindex @option{--package@var{x}} (@command{gnatmetric})
17806 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17807 @cindex @option{--category@var{x}} (@command{gnatmetric})
17808 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17809 @end ifclear
17810
17811 @ifset vms
17812 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17813 @end ifset
17814
17815 @item ^--coupling-all^/COUPLING_METRICS=ALL^
17816 Report all the coupling metrics
17817
17818 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
17819 Do not report any of  metrics
17820
17821 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
17822 Report package efferent coupling
17823
17824 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
17825 Do not report package efferent coupling
17826
17827 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
17828 Report package afferent coupling
17829
17830 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
17831 Do not report package afferent coupling
17832
17833 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
17834 Report category efferent coupling
17835
17836 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
17837 Do not report category efferent coupling
17838
17839 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
17840 Report category afferent coupling
17841
17842 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
17843 Do not report category afferent coupling
17844
17845 @end table
17846
17847 @node Other gnatmetric Switches
17848 @subsection Other @code{gnatmetric} Switches
17849
17850 @noindent
17851 Additional @command{gnatmetric} switches are as follows:
17852
17853 @table @option
17854 @item ^-files @var{filename}^/FILES=@var{filename}^
17855 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17856 Take the argument source files from the specified file. This file should be an
17857 ordinary text file containing file names separated by spaces or
17858 line breaks. You can use this switch more then once in the same call to
17859 @command{gnatmetric}. You also can combine this switch with
17860 an explicit list of files.
17861
17862 @item ^-v^/VERBOSE^
17863 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17864 Verbose mode;
17865 @command{gnatmetric} generates version information and then
17866 a trace of sources being processed.
17867
17868 @item ^-dv^/DEBUG_OUTPUT^
17869 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17870 Debug mode;
17871 @command{gnatmetric} generates various messages useful to understand what
17872 happens during the metrics computation
17873
17874 @item ^-q^/QUIET^
17875 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17876 Quiet mode.
17877 @end table
17878
17879 @node Generate project-wide metrics
17880 @subsection Generate project-wide metrics
17881
17882 In order to compute metrics on all units of a given project, you can use
17883 the @command{gnat} driver along with the @option{-P} option:
17884 @smallexample
17885    gnat metric -Pproj
17886 @end smallexample
17887
17888 @noindent
17889 If the project @code{proj} depends upon other projects, you can compute
17890 the metrics on the project closure using the @option{-U} option:
17891 @smallexample
17892    gnat metric -Pproj -U
17893 @end smallexample
17894
17895 @noindent
17896 Finally, if not all the units are relevant to a particular main
17897 program in the project closure, you can generate metrics for the set
17898 of units needed to create a given main program (unit closure) using
17899 the @option{-U} option followed by the name of the main unit:
17900 @smallexample
17901    gnat metric -Pproj -U main
17902 @end smallexample
17903
17904
17905 @c ***********************************
17906 @node File Name Krunching Using gnatkr
17907 @chapter File Name Krunching Using @code{gnatkr}
17908 @findex gnatkr
17909
17910 @noindent
17911 This chapter discusses the method used by the compiler to shorten
17912 the default file names chosen for Ada units so that they do not
17913 exceed the maximum length permitted. It also describes the
17914 @code{gnatkr} utility that can be used to determine the result of
17915 applying this shortening.
17916 @menu
17917 * About gnatkr::
17918 * Using gnatkr::
17919 * Krunching Method::
17920 * Examples of gnatkr Usage::
17921 @end menu
17922
17923 @node About gnatkr
17924 @section About @code{gnatkr}
17925
17926 @noindent
17927 The default file naming rule in GNAT
17928 is that the file name must be derived from
17929 the unit name. The exact default rule is as follows:
17930 @itemize @bullet
17931 @item
17932 Take the unit name and replace all dots by hyphens.
17933 @item
17934 If such a replacement occurs in the
17935 second character position of a name, and the first character is
17936 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17937 then replace the dot by the character
17938 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17939 instead of a minus.
17940 @end itemize
17941 The reason for this exception is to avoid clashes
17942 with the standard names for children of System, Ada, Interfaces,
17943 and GNAT, which use the prefixes
17944 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17945 respectively.
17946
17947 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17948 switch of the compiler activates a ``krunching''
17949 circuit that limits file names to nn characters (where nn is a decimal
17950 integer). For example, using OpenVMS,
17951 where the maximum file name length is
17952 39, the value of nn is usually set to 39, but if you want to generate
17953 a set of files that would be usable if ported to a system with some
17954 different maximum file length, then a different value can be specified.
17955 The default value of 39 for OpenVMS need not be specified.
17956
17957 The @code{gnatkr} utility can be used to determine the krunched name for
17958 a given file, when krunched to a specified maximum length.
17959
17960 @node Using gnatkr
17961 @section Using @code{gnatkr}
17962
17963 @noindent
17964 The @code{gnatkr} command has the form
17965
17966 @ifclear vms
17967 @smallexample
17968 $ gnatkr @var{name} @ovar{length}
17969 @end smallexample
17970 @end ifclear
17971
17972 @ifset vms
17973 @smallexample
17974 $ gnatkr @var{name} /COUNT=nn
17975 @end smallexample
17976 @end ifset
17977
17978 @noindent
17979 @var{name} is the uncrunched file name, derived from the name of the unit
17980 in the standard manner described in the previous section (i.e., in particular
17981 all dots are replaced by hyphens). The file name may or may not have an
17982 extension (defined as a suffix of the form period followed by arbitrary
17983 characters other than period). If an extension is present then it will
17984 be preserved in the output. For example, when krunching @file{hellofile.ads}
17985 to eight characters, the result will be hellofil.ads.
17986
17987 Note: for compatibility with previous versions of @code{gnatkr} dots may
17988 appear in the name instead of hyphens, but the last dot will always be
17989 taken as the start of an extension. So if @code{gnatkr} is given an argument
17990 such as @file{Hello.World.adb} it will be treated exactly as if the first
17991 period had been a hyphen, and for example krunching to eight characters
17992 gives the result @file{hellworl.adb}.
17993
17994 Note that the result is always all lower case (except on OpenVMS where it is
17995 all upper case). Characters of the other case are folded as required.
17996
17997 @var{length} represents the length of the krunched name. The default
17998 when no argument is given is ^8^39^ characters. A length of zero stands for
17999 unlimited, in other words do not chop except for system files where the
18000 implied crunching length is always eight characters.
18001
18002 @noindent
18003 The output is the krunched name. The output has an extension only if the
18004 original argument was a file name with an extension.
18005
18006 @node Krunching Method
18007 @section Krunching Method
18008
18009 @noindent
18010 The initial file name is determined by the name of the unit that the file
18011 contains. The name is formed by taking the full expanded name of the
18012 unit and replacing the separating dots with hyphens and
18013 using ^lowercase^uppercase^
18014 for all letters, except that a hyphen in the second character position is
18015 replaced by a ^tilde^dollar sign^ if the first character is
18016 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
18017 The extension is @code{.ads} for a
18018 spec and @code{.adb} for a body.
18019 Krunching does not affect the extension, but the file name is shortened to
18020 the specified length by following these rules:
18021
18022 @itemize @bullet
18023 @item
18024 The name is divided into segments separated by hyphens, tildes or
18025 underscores and all hyphens, tildes, and underscores are
18026 eliminated. If this leaves the name short enough, we are done.
18027
18028 @item
18029 If the name is too long, the longest segment is located (left-most
18030 if there are two of equal length), and shortened by dropping
18031 its last character. This is repeated until the name is short enough.
18032
18033 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
18034 to fit the name into 8 characters as required by some operating systems.
18035
18036 @smallexample
18037 our-strings-wide_fixed 22
18038 our strings wide fixed 19
18039 our string  wide fixed 18
18040 our strin   wide fixed 17
18041 our stri    wide fixed 16
18042 our stri    wide fixe  15
18043 our str     wide fixe  14
18044 our str     wid  fixe  13
18045 our str     wid  fix   12
18046 ou  str     wid  fix   11
18047 ou  st      wid  fix   10
18048 ou  st      wi   fix   9
18049 ou  st      wi   fi    8
18050 Final file name: oustwifi.adb
18051 @end smallexample
18052
18053 @item
18054 The file names for all predefined units are always krunched to eight
18055 characters. The krunching of these predefined units uses the following
18056 special prefix replacements:
18057
18058 @table @file
18059 @item ada-
18060 replaced by @file{^a^A^-}
18061
18062 @item gnat-
18063 replaced by @file{^g^G^-}
18064
18065 @item interfaces-
18066 replaced by @file{^i^I^-}
18067
18068 @item system-
18069 replaced by @file{^s^S^-}
18070 @end table
18071
18072 These system files have a hyphen in the second character position. That
18073 is why normal user files replace such a character with a
18074 ^tilde^dollar sign^, to
18075 avoid confusion with system file names.
18076
18077 As an example of this special rule, consider
18078 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
18079
18080 @smallexample
18081 ada-strings-wide_fixed 22
18082 a-  strings wide fixed 18
18083 a-  string  wide fixed 17
18084 a-  strin   wide fixed 16
18085 a-  stri    wide fixed 15
18086 a-  stri    wide fixe  14
18087 a-  str     wide fixe  13
18088 a-  str     wid  fixe  12
18089 a-  str     wid  fix   11
18090 a-  st      wid  fix   10
18091 a-  st      wi   fix   9
18092 a-  st      wi   fi    8
18093 Final file name: a-stwifi.adb
18094 @end smallexample
18095 @end itemize
18096
18097 Of course no file shortening algorithm can guarantee uniqueness over all
18098 possible unit names, and if file name krunching is used then it is your
18099 responsibility to ensure that no name clashes occur. The utility
18100 program @code{gnatkr} is supplied for conveniently determining the
18101 krunched name of a file.
18102
18103 @node Examples of gnatkr Usage
18104 @section Examples of @code{gnatkr} Usage
18105
18106 @smallexample
18107 @iftex
18108 @leftskip=0cm
18109 @end iftex
18110 @ifclear vms
18111 $ gnatkr very_long_unit_name.ads      --> velounna.ads
18112 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
18113 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
18114 $ gnatkr grandparent-parent-child     --> grparchi
18115 @end ifclear
18116 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
18117 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
18118 @end smallexample
18119
18120 @node Preprocessing Using gnatprep
18121 @chapter Preprocessing Using @code{gnatprep}
18122 @findex gnatprep
18123
18124 @noindent
18125 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
18126 preprocessing.
18127 Although designed for use with GNAT, @code{gnatprep} does not depend on any
18128 special GNAT features.
18129 For further discussion of conditional compilation in general, see
18130 @ref{Conditional Compilation}.
18131
18132 @menu
18133 * Preprocessing Symbols::
18134 * Using gnatprep::
18135 * Switches for gnatprep::
18136 * Form of Definitions File::
18137 * Form of Input Text for gnatprep::
18138 @end menu
18139
18140 @node Preprocessing Symbols
18141 @section Preprocessing Symbols
18142
18143 @noindent
18144 Preprocessing symbols are defined in definition files and referred to in
18145 sources to be preprocessed. A Preprocessing symbol is an identifier, following
18146 normal Ada (case-insensitive) rules for its syntax, with the restriction that
18147 all characters need to be in the ASCII set (no accented letters).
18148
18149 @node Using gnatprep
18150 @section Using @code{gnatprep}
18151
18152 @noindent
18153 To call @code{gnatprep} use
18154
18155 @smallexample
18156 $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
18157 @end smallexample
18158
18159 @noindent
18160 where
18161 @table @var
18162 @item switches
18163 is an optional sequence of switches as described in the next section.
18164
18165 @item infile
18166 is the full name of the input file, which is an Ada source
18167 file containing preprocessor directives.
18168
18169 @item outfile
18170 is the full name of the output file, which is an Ada source
18171 in standard Ada form. When used with GNAT, this file name will
18172 normally have an ads or adb suffix.
18173
18174 @item deffile
18175 is the full name of a text file containing definitions of
18176 preprocessing symbols to be referenced by the preprocessor. This argument is
18177 optional, and can be replaced by the use of the @option{-D} switch.
18178
18179 @end table
18180
18181 @node Switches for gnatprep
18182 @section Switches for @code{gnatprep}
18183
18184 @table @option
18185 @c !sort!
18186
18187 @item ^-b^/BLANK_LINES^
18188 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
18189 Causes both preprocessor lines and the lines deleted by
18190 preprocessing to be replaced by blank lines in the output source file,
18191 preserving line numbers in the output file.
18192
18193 @item ^-c^/COMMENTS^
18194 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
18195 Causes both preprocessor lines and the lines deleted
18196 by preprocessing to be retained in the output source as comments marked
18197 with the special string @code{"--! "}. This option will result in line numbers
18198 being preserved in the output file.
18199
18200 @item ^-C^/REPLACE_IN_COMMENTS^
18201 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
18202 Causes comments to be scanned. Normally comments are ignored by gnatprep.
18203 If this option is specified, then comments are scanned and any $symbol
18204 substitutions performed as in program text. This is particularly useful
18205 when structured comments are used (e.g., when writing programs in the
18206 SPARK dialect of Ada). Note that this switch is not available when
18207 doing integrated preprocessing (it would be useless in this context
18208 since comments are ignored by the compiler in any case).
18209
18210 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
18211 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
18212 Defines a new preprocessing symbol, associated with value. If no value is given
18213 on the command line, then symbol is considered to be @code{True}. This switch
18214 can be used in place of a definition file.
18215
18216 @ifset vms
18217 @item /REMOVE
18218 @cindex @option{/REMOVE} (@command{gnatprep})
18219 This is the default setting which causes lines deleted by preprocessing
18220 to be entirely removed from the output file.
18221 @end ifset
18222
18223 @item ^-r^/REFERENCE^
18224 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
18225 Causes a @code{Source_Reference} pragma to be generated that
18226 references the original input file, so that error messages will use
18227 the file name of this original file. The use of this switch implies
18228 that preprocessor lines are not to be removed from the file, so its
18229 use will force @option{^-b^/BLANK_LINES^} mode if
18230 @option{^-c^/COMMENTS^}
18231 has not been specified explicitly.
18232
18233 Note that if the file to be preprocessed contains multiple units, then
18234 it will be necessary to @code{gnatchop} the output file from
18235 @code{gnatprep}. If a @code{Source_Reference} pragma is present
18236 in the preprocessed file, it will be respected by
18237 @code{gnatchop ^-r^/REFERENCE^}
18238 so that the final chopped files will correctly refer to the original
18239 input source file for @code{gnatprep}.
18240
18241 @item ^-s^/SYMBOLS^
18242 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
18243 Causes a sorted list of symbol names and values to be
18244 listed on the standard output file.
18245
18246 @item ^-u^/UNDEFINED^
18247 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
18248 Causes undefined symbols to be treated as having the value FALSE in the context
18249 of a preprocessor test. In the absence of this option, an undefined symbol in
18250 a @code{#if} or @code{#elsif} test will be treated as an error.
18251
18252 @end table
18253
18254 @ifclear vms
18255 @noindent
18256 Note: if neither @option{-b} nor @option{-c} is present,
18257 then preprocessor lines and
18258 deleted lines are completely removed from the output, unless -r is
18259 specified, in which case -b is assumed.
18260 @end ifclear
18261
18262 @node Form of Definitions File
18263 @section Form of Definitions File
18264
18265 @noindent
18266 The definitions file contains lines of the form
18267
18268 @smallexample
18269 symbol := value
18270 @end smallexample
18271
18272 @noindent
18273 where symbol is a preprocessing symbol, and value is one of the following:
18274
18275 @itemize @bullet
18276 @item
18277 Empty, corresponding to a null substitution
18278 @item
18279 A string literal using normal Ada syntax
18280 @item
18281 Any sequence of characters from the set
18282 (letters, digits, period, underline).
18283 @end itemize
18284
18285 @noindent
18286 Comment lines may also appear in the definitions file, starting with
18287 the usual @code{--},
18288 and comments may be added to the definitions lines.
18289
18290 @node Form of Input Text for gnatprep
18291 @section Form of Input Text for @code{gnatprep}
18292
18293 @noindent
18294 The input text may contain preprocessor conditional inclusion lines,
18295 as well as general symbol substitution sequences.
18296
18297 The preprocessor conditional inclusion commands have the form
18298
18299 @smallexample
18300 @group
18301 @cartouche
18302 #if @i{expression} @r{[}then@r{]}
18303    lines
18304 #elsif @i{expression} @r{[}then@r{]}
18305    lines
18306 #elsif @i{expression} @r{[}then@r{]}
18307    lines
18308 @dots{}
18309 #else
18310    lines
18311 #end if;
18312 @end cartouche
18313 @end group
18314 @end smallexample
18315
18316 @noindent
18317 In this example, @i{expression} is defined by the following grammar:
18318 @smallexample
18319 @i{expression} ::=  <symbol>
18320 @i{expression} ::=  <symbol> = "<value>"
18321 @i{expression} ::=  <symbol> = <symbol>
18322 @i{expression} ::=  <symbol> 'Defined
18323 @i{expression} ::=  not @i{expression}
18324 @i{expression} ::=  @i{expression} and @i{expression}
18325 @i{expression} ::=  @i{expression} or @i{expression}
18326 @i{expression} ::=  @i{expression} and then @i{expression}
18327 @i{expression} ::=  @i{expression} or else @i{expression}
18328 @i{expression} ::=  ( @i{expression} )
18329 @end smallexample
18330
18331 The following restriction exists: it is not allowed to have "and" or "or"
18332 following "not" in the same expression without parentheses. For example, this
18333 is not allowed:
18334
18335 @smallexample
18336    not X or Y
18337 @end smallexample
18338
18339 This should be one of the following:
18340
18341 @smallexample
18342    (not X) or Y
18343    not (X or Y)
18344 @end smallexample
18345
18346 @noindent
18347 For the first test (@i{expression} ::= <symbol>) the symbol must have
18348 either the value true or false, that is to say the right-hand of the
18349 symbol definition must be one of the (case-insensitive) literals
18350 @code{True} or @code{False}. If the value is true, then the
18351 corresponding lines are included, and if the value is false, they are
18352 excluded.
18353
18354 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
18355 the symbol has been defined in the definition file or by a @option{-D}
18356 switch on the command line. Otherwise, the test is false.
18357
18358 The equality tests are case insensitive, as are all the preprocessor lines.
18359
18360 If the symbol referenced is not defined in the symbol definitions file,
18361 then the effect depends on whether or not switch @option{-u}
18362 is specified. If so, then the symbol is treated as if it had the value
18363 false and the test fails. If this switch is not specified, then
18364 it is an error to reference an undefined symbol. It is also an error to
18365 reference a symbol that is defined with a value other than @code{True}
18366 or @code{False}.
18367
18368 The use of the @code{not} operator inverts the sense of this logical test.
18369 The @code{not} operator cannot be combined with the @code{or} or @code{and}
18370 operators, without parentheses. For example, "if not X or Y then" is not
18371 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
18372
18373 The @code{then} keyword is optional as shown
18374
18375 The @code{#} must be the first non-blank character on a line, but
18376 otherwise the format is free form. Spaces or tabs may appear between
18377 the @code{#} and the keyword. The keywords and the symbols are case
18378 insensitive as in normal Ada code. Comments may be used on a
18379 preprocessor line, but other than that, no other tokens may appear on a
18380 preprocessor line. Any number of @code{elsif} clauses can be present,
18381 including none at all. The @code{else} is optional, as in Ada.
18382
18383 The @code{#} marking the start of a preprocessor line must be the first
18384 non-blank character on the line, i.e., it must be preceded only by
18385 spaces or horizontal tabs.
18386
18387 Symbol substitution outside of preprocessor lines is obtained by using
18388 the sequence
18389
18390 @smallexample
18391 $symbol
18392 @end smallexample
18393
18394 @noindent
18395 anywhere within a source line, except in a comment or within a
18396 string literal. The identifier
18397 following the @code{$} must match one of the symbols defined in the symbol
18398 definition file, and the result is to substitute the value of the
18399 symbol in place of @code{$symbol} in the output file.
18400
18401 Note that although the substitution of strings within a string literal
18402 is not possible, it is possible to have a symbol whose defined value is
18403 a string literal. So instead of setting XYZ to @code{hello} and writing:
18404
18405 @smallexample
18406 Header : String := "$XYZ";
18407 @end smallexample
18408
18409 @noindent
18410 you should set XYZ to @code{"hello"} and write:
18411
18412 @smallexample
18413 Header : String := $XYZ;
18414 @end smallexample
18415
18416 @noindent
18417 and then the substitution will occur as desired.
18418
18419 @ifset vms
18420 @node The GNAT Run-Time Library Builder gnatlbr
18421 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18422 @findex gnatlbr
18423 @cindex Library builder
18424
18425 @noindent
18426 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18427 supplied configuration pragmas.
18428
18429 @menu
18430 * Running gnatlbr::
18431 * Switches for gnatlbr::
18432 * Examples of gnatlbr Usage::
18433 @end menu
18434
18435 @node Running gnatlbr
18436 @section Running @code{gnatlbr}
18437
18438 @noindent
18439 The @code{gnatlbr} command has the form
18440
18441 @smallexample
18442 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18443 @end smallexample
18444
18445 @node Switches for gnatlbr
18446 @section Switches for @code{gnatlbr}
18447
18448 @noindent
18449 @code{gnatlbr} recognizes the following switches:
18450
18451 @table @option
18452 @c !sort!
18453 @item /CREATE=directory
18454 @cindex @code{/CREATE} (@code{gnatlbr})
18455 Create the new run-time library in the specified directory.
18456
18457 @item /SET=directory
18458 @cindex @code{/SET} (@code{gnatlbr})
18459 Make the library in the specified directory the current run-time library.
18460
18461 @item /DELETE=directory
18462 @cindex @code{/DELETE} (@code{gnatlbr})
18463 Delete the run-time library in the specified directory.
18464
18465 @item /CONFIG=file
18466 @cindex @code{/CONFIG} (@code{gnatlbr})
18467 With /CREATE: Use the configuration pragmas in the specified file when
18468 building the library.
18469
18470 With /SET: Use the configuration pragmas in the specified file when
18471 compiling.
18472
18473 @end table
18474
18475 @node Examples of gnatlbr Usage
18476 @section Example of @code{gnatlbr} Usage
18477
18478 @smallexample
18479 Contents of VAXFLOAT.ADC:
18480 pragma Float_Representation (VAX_Float);
18481
18482 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18483
18484 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18485
18486 @end smallexample
18487 @end ifset
18488
18489 @node The GNAT Library Browser gnatls
18490 @chapter The GNAT Library Browser @code{gnatls}
18491 @findex gnatls
18492 @cindex Library browser
18493
18494 @noindent
18495 @code{gnatls} is a tool that outputs information about compiled
18496 units. It gives the relationship between objects, unit names and source
18497 files. It can also be used to check the source dependencies of a unit
18498 as well as various characteristics.
18499
18500 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18501 driver (see @ref{The GNAT Driver and Project Files}).
18502
18503 @menu
18504 * Running gnatls::
18505 * Switches for gnatls::
18506 * Examples of gnatls Usage::
18507 @end menu
18508
18509 @node Running gnatls
18510 @section Running @code{gnatls}
18511
18512 @noindent
18513 The @code{gnatls} command has the form
18514
18515 @smallexample
18516 $ gnatls switches @var{object_or_ali_file}
18517 @end smallexample
18518
18519 @noindent
18520 The main argument is the list of object or @file{ali} files
18521 (@pxref{The Ada Library Information Files})
18522 for which information is requested.
18523
18524 In normal mode, without additional option, @code{gnatls} produces a
18525 four-column listing. Each line represents information for a specific
18526 object. The first column gives the full path of the object, the second
18527 column gives the name of the principal unit in this object, the third
18528 column gives the status of the source and the fourth column gives the
18529 full path of the source representing this unit.
18530 Here is a simple example of use:
18531
18532 @smallexample
18533 $ gnatls *.o
18534 ^./^[]^demo1.o            demo1            DIF demo1.adb
18535 ^./^[]^demo2.o            demo2             OK demo2.adb
18536 ^./^[]^hello.o            h1                OK hello.adb
18537 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
18538 ^./^[]^instr.o            instr             OK instr.adb
18539 ^./^[]^tef.o              tef              DIF tef.adb
18540 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
18541 ^./^[]^tgef.o             tgef             DIF tgef.adb
18542 @end smallexample
18543
18544 @noindent
18545 The first line can be interpreted as follows: the main unit which is
18546 contained in
18547 object file @file{demo1.o} is demo1, whose main source is in
18548 @file{demo1.adb}. Furthermore, the version of the source used for the
18549 compilation of demo1 has been modified (DIF). Each source file has a status
18550 qualifier which can be:
18551
18552 @table @code
18553 @item OK (unchanged)
18554 The version of the source file used for the compilation of the
18555 specified unit corresponds exactly to the actual source file.
18556
18557 @item MOK (slightly modified)
18558 The version of the source file used for the compilation of the
18559 specified unit differs from the actual source file but not enough to
18560 require recompilation. If you use gnatmake with the qualifier
18561 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18562 MOK will not be recompiled.
18563
18564 @item DIF (modified)
18565 No version of the source found on the path corresponds to the source
18566 used to build this object.
18567
18568 @item ??? (file not found)
18569 No source file was found for this unit.
18570
18571 @item HID (hidden,  unchanged version not first on PATH)
18572 The version of the source that corresponds exactly to the source used
18573 for compilation has been found on the path but it is hidden by another
18574 version of the same source that has been modified.
18575
18576 @end table
18577
18578 @node Switches for gnatls
18579 @section Switches for @code{gnatls}
18580
18581 @noindent
18582 @code{gnatls} recognizes the following switches:
18583
18584 @table @option
18585 @c !sort!
18586 @cindex @option{--version} @command{gnatls}
18587 Display Copyright and version, then exit disregarding all other options.
18588
18589 @item --help
18590 @cindex @option{--help} @command{gnatls}
18591 If @option{--version} was not used, display usage, then exit disregarding
18592 all other options.
18593
18594 @item ^-a^/ALL_UNITS^
18595 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18596 Consider all units, including those of the predefined Ada library.
18597 Especially useful with @option{^-d^/DEPENDENCIES^}.
18598
18599 @item ^-d^/DEPENDENCIES^
18600 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18601 List sources from which specified units depend on.
18602
18603 @item ^-h^/OUTPUT=OPTIONS^
18604 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18605 Output the list of options.
18606
18607 @item ^-o^/OUTPUT=OBJECTS^
18608 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18609 Only output information about object files.
18610
18611 @item ^-s^/OUTPUT=SOURCES^
18612 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18613 Only output information about source files.
18614
18615 @item ^-u^/OUTPUT=UNITS^
18616 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18617 Only output information about compilation units.
18618
18619 @item ^-files^/FILES^=@var{file}
18620 @cindex @option{^-files^/FILES^} (@code{gnatls})
18621 Take as arguments the files listed in text file @var{file}.
18622 Text file @var{file} may contain empty lines that are ignored.
18623 Each nonempty line should contain the name of an existing file.
18624 Several such switches may be specified simultaneously.
18625
18626 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18627 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18628 @itemx ^-I^/SEARCH=^@var{dir}
18629 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
18630 @itemx -nostdinc
18631 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18632 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18633 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18634 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18635 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18636 flags (@pxref{Switches for gnatmake}).
18637
18638 @item --RTS=@var{rts-path}
18639 @cindex @option{--RTS} (@code{gnatls})
18640 Specifies the default location of the runtime library. Same meaning as the
18641 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18642
18643 @item ^-v^/OUTPUT=VERBOSE^
18644 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18645 Verbose mode. Output the complete source, object and project paths. Do not use
18646 the default column layout but instead use long format giving as much as
18647 information possible on each requested units, including special
18648 characteristics such as:
18649
18650 @table @code
18651 @item  Preelaborable
18652 The unit is preelaborable in the Ada sense.
18653
18654 @item No_Elab_Code
18655 No elaboration code has been produced by the compiler for this unit.
18656
18657 @item Pure
18658 The unit is pure in the Ada sense.
18659
18660 @item Elaborate_Body
18661 The unit contains a pragma Elaborate_Body.
18662
18663 @item Remote_Types
18664 The unit contains a pragma Remote_Types.
18665
18666 @item Shared_Passive
18667 The unit contains a pragma Shared_Passive.
18668
18669 @item Predefined
18670 This unit is part of the predefined environment and cannot be modified
18671 by the user.
18672
18673 @item Remote_Call_Interface
18674 The unit contains a pragma Remote_Call_Interface.
18675
18676 @end table
18677
18678 @end table
18679
18680 @node Examples of gnatls Usage
18681 @section Example of @code{gnatls} Usage
18682 @ifclear vms
18683
18684 @noindent
18685 Example of using the verbose switch. Note how the source and
18686 object paths are affected by the -I switch.
18687
18688 @smallexample
18689 $ gnatls -v -I.. demo1.o
18690
18691 GNATLS 5.03w (20041123-34)
18692 Copyright 1997-2004 Free Software Foundation, Inc.
18693
18694 Source Search Path:
18695    <Current_Directory>
18696    ../
18697    /home/comar/local/adainclude/
18698
18699 Object Search Path:
18700    <Current_Directory>
18701    ../
18702    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18703
18704 Project Search Path:
18705    <Current_Directory>
18706    /home/comar/local/lib/gnat/
18707
18708 ./demo1.o
18709    Unit =>
18710      Name   => demo1
18711      Kind   => subprogram body
18712      Flags  => No_Elab_Code
18713      Source => demo1.adb    modified
18714 @end smallexample
18715
18716 @noindent
18717 The following is an example of use of the dependency list.
18718 Note the use of the -s switch
18719 which gives a straight list of source files. This can be useful for
18720 building specialized scripts.
18721
18722 @smallexample
18723 $ gnatls -d demo2.o
18724 ./demo2.o   demo2        OK demo2.adb
18725                          OK gen_list.ads
18726                          OK gen_list.adb
18727                          OK instr.ads
18728                          OK instr-child.ads
18729
18730 $ gnatls -d -s -a demo1.o
18731 demo1.adb
18732 /home/comar/local/adainclude/ada.ads
18733 /home/comar/local/adainclude/a-finali.ads
18734 /home/comar/local/adainclude/a-filico.ads
18735 /home/comar/local/adainclude/a-stream.ads
18736 /home/comar/local/adainclude/a-tags.ads
18737 gen_list.ads
18738 gen_list.adb
18739 /home/comar/local/adainclude/gnat.ads
18740 /home/comar/local/adainclude/g-io.ads
18741 instr.ads
18742 /home/comar/local/adainclude/system.ads
18743 /home/comar/local/adainclude/s-exctab.ads
18744 /home/comar/local/adainclude/s-finimp.ads
18745 /home/comar/local/adainclude/s-finroo.ads
18746 /home/comar/local/adainclude/s-secsta.ads
18747 /home/comar/local/adainclude/s-stalib.ads
18748 /home/comar/local/adainclude/s-stoele.ads
18749 /home/comar/local/adainclude/s-stratt.ads
18750 /home/comar/local/adainclude/s-tasoli.ads
18751 /home/comar/local/adainclude/s-unstyp.ads
18752 /home/comar/local/adainclude/unchconv.ads
18753 @end smallexample
18754 @end ifclear
18755
18756 @ifset vms
18757 @smallexample
18758 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18759
18760 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18761 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18762 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18763 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18764 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18765 demo1.adb
18766 gen_list.ads
18767 gen_list.adb
18768 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18769 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18770 instr.ads
18771 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18772 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18773 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18774 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18775 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18776 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18777 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18778 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18779 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18780 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18781 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18782 @end smallexample
18783 @end ifset
18784
18785 @node Cleaning Up Using gnatclean
18786 @chapter Cleaning Up Using @code{gnatclean}
18787 @findex gnatclean
18788 @cindex Cleaning tool
18789
18790 @noindent
18791 @code{gnatclean} is a tool that allows the deletion of files produced by the
18792 compiler, binder and linker, including ALI files, object files, tree files,
18793 expanded source files, library files, interface copy source files, binder
18794 generated files and executable files.
18795
18796 @menu
18797 * Running gnatclean::
18798 * Switches for gnatclean::
18799 @c * Examples of gnatclean Usage::
18800 @end menu
18801
18802 @node Running gnatclean
18803 @section Running @code{gnatclean}
18804
18805 @noindent
18806 The @code{gnatclean} command has the form:
18807
18808 @smallexample
18809 $ gnatclean switches @var{names}
18810 @end smallexample
18811
18812 @noindent
18813 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18814 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18815 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18816
18817 @noindent
18818 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18819 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18820 the linker. In informative-only mode, specified by switch
18821 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18822 normal mode is listed, but no file is actually deleted.
18823
18824 @node Switches for gnatclean
18825 @section Switches for @code{gnatclean}
18826
18827 @noindent
18828 @code{gnatclean} recognizes the following switches:
18829
18830 @table @option
18831 @c !sort!
18832 @cindex @option{--version} @command{gnatclean}
18833 Display Copyright and version, then exit disregarding all other options.
18834
18835 @item --help
18836 @cindex @option{--help} @command{gnatclean}
18837 If @option{--version} was not used, display usage, then exit disregarding
18838 all other options.
18839
18840 @item ^-c^/COMPILER_FILES_ONLY^
18841 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18842 Only attempt to delete the files produced by the compiler, not those produced
18843 by the binder or the linker. The files that are not to be deleted are library
18844 files, interface copy files, binder generated files and executable files.
18845
18846 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18847 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18848 Indicate that ALI and object files should normally be found in directory
18849 @var{dir}.
18850
18851 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18852 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18853 When using project files, if some errors or warnings are detected during
18854 parsing and verbose mode is not in effect (no use of switch
18855 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18856 file, rather than its simple file name.
18857
18858 @item ^-h^/HELP^
18859 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18860 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18861
18862 @item ^-n^/NODELETE^
18863 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18864 Informative-only mode. Do not delete any files. Output the list of the files
18865 that would have been deleted if this switch was not specified.
18866
18867 @item ^-P^/PROJECT_FILE=^@var{project}
18868 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18869 Use project file @var{project}. Only one such switch can be used.
18870 When cleaning a project file, the files produced by the compilation of the
18871 immediate sources or inherited sources of the project files are to be
18872 deleted. This is not depending on the presence or not of executable names
18873 on the command line.
18874
18875 @item ^-q^/QUIET^
18876 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18877 Quiet output. If there are no errors, do not output anything, except in
18878 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18879 (switch ^-n^/NODELETE^).
18880
18881 @item ^-r^/RECURSIVE^
18882 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18883 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18884 clean all imported and extended project files, recursively. If this switch
18885 is not specified, only the files related to the main project file are to be
18886 deleted. This switch has no effect if no project file is specified.
18887
18888 @item ^-v^/VERBOSE^
18889 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18890 Verbose mode.
18891
18892 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18893 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18894 Indicates the verbosity of the parsing of GNAT project files.
18895 @xref{Switches Related to Project Files}.
18896
18897 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18898 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18899 Indicates that external variable @var{name} has the value @var{value}.
18900 The Project Manager will use this value for occurrences of
18901 @code{external(name)} when parsing the project file.
18902 @xref{Switches Related to Project Files}.
18903
18904 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18905 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18906 When searching for ALI and object files, look in directory
18907 @var{dir}.
18908
18909 @item ^-I^/SEARCH=^@var{dir}
18910 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18911 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18912
18913 @item ^-I-^/NOCURRENT_DIRECTORY^
18914 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18915 @cindex Source files, suppressing search
18916 Do not look for ALI or object files in the directory
18917 where @code{gnatclean} was invoked.
18918
18919 @end table
18920
18921 @c @node Examples of gnatclean Usage
18922 @c @section Examples of @code{gnatclean} Usage
18923
18924 @ifclear vms
18925 @node GNAT and Libraries
18926 @chapter GNAT and Libraries
18927 @cindex Library, building, installing, using
18928
18929 @noindent
18930 This chapter describes how to build and use libraries with GNAT, and also shows
18931 how to recompile the GNAT run-time library. You should be familiar with the
18932 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18933 chapter.
18934
18935 @menu
18936 * Introduction to Libraries in GNAT::
18937 * General Ada Libraries::
18938 * Stand-alone Ada Libraries::
18939 * Rebuilding the GNAT Run-Time Library::
18940 @end menu
18941
18942 @node Introduction to Libraries in GNAT
18943 @section Introduction to Libraries in GNAT
18944
18945 @noindent
18946 A library is, conceptually, a collection of objects which does not have its
18947 own main thread of execution, but rather provides certain services to the
18948 applications that use it. A library can be either statically linked with the
18949 application, in which case its code is directly included in the application,
18950 or, on platforms that support it, be dynamically linked, in which case
18951 its code is shared by all applications making use of this library.
18952
18953 GNAT supports both types of libraries.
18954 In the static case, the compiled code can be provided in different ways. The
18955 simplest approach is to provide directly the set of objects resulting from
18956 compilation of the library source files. Alternatively, you can group the
18957 objects into an archive using whatever commands are provided by the operating
18958 system. For the latter case, the objects are grouped into a shared library.
18959
18960 In the GNAT environment, a library has three types of components:
18961 @itemize @bullet
18962 @item
18963 Source files.
18964 @item
18965 @file{ALI} files.
18966 @xref{The Ada Library Information Files}.
18967 @item
18968 Object files, an archive or a shared library.
18969 @end itemize
18970
18971 @noindent
18972 A GNAT library may expose all its source files, which is useful for
18973 documentation purposes. Alternatively, it may expose only the units needed by
18974 an external user to make use of the library. That is to say, the specs
18975 reflecting the library services along with all the units needed to compile
18976 those specs, which can include generic bodies or any body implementing an
18977 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18978 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18979
18980 All compilation units comprising an application, including those in a library,
18981 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18982 computes the elaboration order from the @file{ALI} files and this is why they
18983 constitute a mandatory part of GNAT libraries.
18984 @emph{Stand-alone libraries} are the exception to this rule because a specific
18985 library elaboration routine is produced independently of the application(s)
18986 using the library.
18987
18988 @node General Ada Libraries
18989 @section General Ada Libraries
18990
18991 @menu
18992 * Building a library::
18993 * Installing a library::
18994 * Using a library::
18995 @end menu
18996
18997 @node Building a library
18998 @subsection Building a library
18999
19000 @noindent
19001 The easiest way to build a library is to use the Project Manager,
19002 which supports a special type of project called a @emph{Library Project}
19003 (@pxref{Library Projects}).
19004
19005 A project is considered a library project, when two project-level attributes
19006 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
19007 control different aspects of library configuration, additional optional
19008 project-level attributes can be specified:
19009 @table @code
19010 @item Library_Kind
19011 This attribute controls whether the library is to be static or dynamic
19012
19013 @item Library_Version
19014 This attribute specifies the library version; this value is used
19015 during dynamic linking of shared libraries to determine if the currently
19016 installed versions of the binaries are compatible.
19017
19018 @item Library_Options
19019 @item Library_GCC
19020 These attributes specify additional low-level options to be used during
19021 library generation, and redefine the actual application used to generate
19022 library.
19023 @end table
19024
19025 @noindent
19026 The GNAT Project Manager takes full care of the library maintenance task,
19027 including recompilation of the source files for which objects do not exist
19028 or are not up to date, assembly of the library archive, and installation of
19029 the library (i.e., copying associated source, object and @file{ALI} files
19030 to the specified location).
19031
19032 Here is a simple library project file:
19033 @smallexample @c ada
19034 project My_Lib is
19035    for Source_Dirs use ("src1", "src2");
19036    for Object_Dir use "obj";
19037    for Library_Name use "mylib";
19038    for Library_Dir use "lib";
19039    for Library_Kind use "dynamic";
19040 end My_lib;
19041 @end smallexample
19042
19043 @noindent
19044 and the compilation command to build and install the library:
19045
19046 @smallexample @c ada
19047   $ gnatmake -Pmy_lib
19048 @end smallexample
19049
19050 @noindent
19051 It is not entirely trivial to perform manually all the steps required to
19052 produce a library. We recommend that you use the GNAT Project Manager
19053 for this task. In special cases where this is not desired, the necessary
19054 steps are discussed below.
19055
19056 There are various possibilities for compiling the units that make up the
19057 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
19058 with a conventional script. For simple libraries, it is also possible to create
19059 a dummy main program which depends upon all the packages that comprise the
19060 interface of the library. This dummy main program can then be given to
19061 @command{gnatmake}, which will ensure that all necessary objects are built.
19062
19063 After this task is accomplished, you should follow the standard procedure
19064 of the underlying operating system to produce the static or shared library.
19065
19066 Here is an example of such a dummy program:
19067 @smallexample @c ada
19068 @group
19069 with My_Lib.Service1;
19070 with My_Lib.Service2;
19071 with My_Lib.Service3;
19072 procedure My_Lib_Dummy is
19073 begin
19074    null;
19075 end;
19076 @end group
19077 @end smallexample
19078
19079 @noindent
19080 Here are the generic commands that will build an archive or a shared library.
19081
19082 @smallexample
19083 # compiling the library
19084 $ gnatmake -c my_lib_dummy.adb
19085
19086 # we don't need the dummy object itself
19087 $ rm my_lib_dummy.o my_lib_dummy.ali
19088
19089 # create an archive with the remaining objects
19090 $ ar rc libmy_lib.a *.o
19091 # some systems may require "ranlib" to be run as well
19092
19093 # or create a shared library
19094 $ gcc -shared -o libmy_lib.so *.o
19095 # some systems may require the code to have been compiled with -fPIC
19096
19097 # remove the object files that are now in the library
19098 $ rm *.o
19099
19100 # Make the ALI files read-only so that gnatmake will not try to
19101 # regenerate the objects that are in the library
19102 $ chmod -w *.ali
19103 @end smallexample
19104
19105 @noindent
19106 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
19107 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
19108 be accessed by the directive @option{-l@var{xxx}} at link time.
19109
19110 @node Installing a library
19111 @subsection Installing a library
19112 @cindex @code{ADA_PROJECT_PATH}
19113 @cindex @code{GPR_PROJECT_PATH}
19114
19115 @noindent
19116 If you use project files, library installation is part of the library build
19117 process. Thus no further action is needed in order to make use of the
19118 libraries that are built as part of the general application build. A usable
19119 version of the library is installed in the directory specified by the
19120 @code{Library_Dir} attribute of the library project file.
19121
19122 You may want to install a library in a context different from where the library
19123 is built. This situation arises with third party suppliers, who may want
19124 to distribute a library in binary form where the user is not expected to be
19125 able to recompile the library. The simplest option in this case is to provide
19126 a project file slightly different from the one used to build the library, by
19127 using the @code{externally_built} attribute. For instance, the project
19128 file used to build the library in the previous section can be changed into the
19129 following one when the library is installed:
19130
19131 @smallexample @c projectfile
19132 project My_Lib is
19133    for Source_Dirs use ("src1", "src2");
19134    for Library_Name use "mylib";
19135    for Library_Dir use "lib";
19136    for Library_Kind use "dynamic";
19137    for Externally_Built use "true";
19138 end My_lib;
19139 @end smallexample
19140
19141 @noindent
19142 This project file assumes that the directories @file{src1},
19143 @file{src2}, and @file{lib} exist in
19144 the directory containing the project file. The @code{externally_built}
19145 attribute makes it clear to the GNAT builder that it should not attempt to
19146 recompile any of the units from this library. It allows the library provider to
19147 restrict the source set to the minimum necessary for clients to make use of the
19148 library as described in the first section of this chapter. It is the
19149 responsibility of the library provider to install the necessary sources, ALI
19150 files and libraries in the directories mentioned in the project file. For
19151 convenience, the user's library project file should be installed in a location
19152 that will be searched automatically by the GNAT
19153 builder. These are the directories referenced in the @env{GPR_PROJECT_PATH}
19154 environment variable (@pxref{Importing Projects}), and also the default GNAT
19155 library location that can be queried with @command{gnatls -v} and is usually of
19156 the form $gnat_install_root/lib/gnat.
19157
19158 When project files are not an option, it is also possible, but not recommended,
19159 to install the library so that the sources needed to use the library are on the
19160 Ada source path and the ALI files & libraries be on the Ada Object path (see
19161 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
19162 administrator can place general-purpose libraries in the default compiler
19163 paths, by specifying the libraries' location in the configuration files
19164 @file{ada_source_path} and @file{ada_object_path}. These configuration files
19165 must be located in the GNAT installation tree at the same place as the gcc spec
19166 file. The location of the gcc spec file can be determined as follows:
19167 @smallexample
19168 $ gcc -v
19169 @end smallexample
19170
19171 @noindent
19172 The configuration files mentioned above have a simple format: each line
19173 must contain one unique directory name.
19174 Those names are added to the corresponding path
19175 in their order of appearance in the file. The names can be either absolute
19176 or relative; in the latter case, they are relative to where theses files
19177 are located.
19178
19179 The files @file{ada_source_path} and @file{ada_object_path} might not be
19180 present in a
19181 GNAT installation, in which case, GNAT will look for its run-time library in
19182 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
19183 objects and @file{ALI} files). When the files exist, the compiler does not
19184 look in @file{adainclude} and @file{adalib}, and thus the
19185 @file{ada_source_path} file
19186 must contain the location for the GNAT run-time sources (which can simply
19187 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
19188 contain the location for the GNAT run-time objects (which can simply
19189 be @file{adalib}).
19190
19191 You can also specify a new default path to the run-time library at compilation
19192 time with the switch @option{--RTS=rts-path}. You can thus choose / change
19193 the run-time library you want your program to be compiled with. This switch is
19194 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
19195 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
19196
19197 It is possible to install a library before or after the standard GNAT
19198 library, by reordering the lines in the configuration files. In general, a
19199 library must be installed before the GNAT library if it redefines
19200 any part of it.
19201
19202 @node Using a library
19203 @subsection Using a library
19204
19205 @noindent Once again, the project facility greatly simplifies the use of
19206 libraries. In this context, using a library is just a matter of adding a
19207 @code{with} clause in the user project. For instance, to make use of the
19208 library @code{My_Lib} shown in examples in earlier sections, you can
19209 write:
19210
19211 @smallexample @c projectfile
19212 with "my_lib";
19213 project My_Proj is
19214   @dots{}
19215 end My_Proj;
19216 @end smallexample
19217
19218 Even if you have a third-party, non-Ada library, you can still use GNAT's
19219 Project Manager facility to provide a wrapper for it. For example, the
19220 following project, when @code{with}ed by your main project, will link with the
19221 third-party library @file{liba.a}:
19222
19223 @smallexample @c projectfile
19224 @group
19225 project Liba is
19226    for Externally_Built use "true";
19227    for Source_Files use ();
19228    for Library_Dir use "lib";
19229    for Library_Name use "a";
19230    for Library_Kind use "static";
19231 end Liba;
19232 @end group
19233 @end smallexample
19234 This is an alternative to the use of @code{pragma Linker_Options}. It is
19235 especially interesting in the context of systems with several interdependent
19236 static libraries where finding a proper linker order is not easy and best be
19237 left to the tools having visibility over project dependence information.
19238
19239 @noindent
19240 In order to use an Ada library manually, you need to make sure that this
19241 library is on both your source and object path
19242 (see @ref{Search Paths and the Run-Time Library (RTL)}
19243 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
19244 in an archive or a shared library, you need to specify the desired
19245 library at link time.
19246
19247 For example, you can use the library @file{mylib} installed in
19248 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
19249
19250 @smallexample
19251 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
19252   -largs -lmy_lib
19253 @end smallexample
19254
19255 @noindent
19256 This can be expressed more simply:
19257 @smallexample
19258 $ gnatmake my_appl
19259 @end smallexample
19260 @noindent
19261 when the following conditions are met:
19262 @itemize @bullet
19263 @item
19264 @file{/dir/my_lib_src} has been added by the user to the environment
19265 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
19266 @file{ada_source_path}
19267 @item
19268 @file{/dir/my_lib_obj} has been added by the user to the environment
19269 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
19270 @file{ada_object_path}
19271 @item
19272 a pragma @code{Linker_Options} has been added to one of the sources.
19273 For example:
19274
19275 @smallexample @c ada
19276 pragma Linker_Options ("-lmy_lib");
19277 @end smallexample
19278 @end itemize
19279
19280 @node Stand-alone Ada Libraries
19281 @section Stand-alone Ada Libraries
19282 @cindex Stand-alone library, building, using
19283
19284 @menu
19285 * Introduction to Stand-alone Libraries::
19286 * Building a Stand-alone Library::
19287 * Creating a Stand-alone Library to be used in a non-Ada context::
19288 * Restrictions in Stand-alone Libraries::
19289 @end menu
19290
19291 @node Introduction to Stand-alone Libraries
19292 @subsection Introduction to Stand-alone Libraries
19293
19294 @noindent
19295 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
19296 necessary code to
19297 elaborate the Ada units that are included in the library. In contrast with
19298 an ordinary library, which consists of all sources, objects and @file{ALI}
19299 files of the
19300 library, a SAL may specify a restricted subset of compilation units
19301 to serve as a library interface. In this case, the fully
19302 self-sufficient set of files will normally consist of an objects
19303 archive, the sources of interface units' specs, and the @file{ALI}
19304 files of interface units.
19305 If an interface spec contains a generic unit or an inlined subprogram,
19306 the body's
19307 source must also be provided; if the units that must be provided in the source
19308 form depend on other units, the source and @file{ALI} files of those must
19309 also be provided.
19310
19311 The main purpose of a SAL is to minimize the recompilation overhead of client
19312 applications when a new version of the library is installed. Specifically,
19313 if the interface sources have not changed, client applications do not need to
19314 be recompiled. If, furthermore, a SAL is provided in the shared form and its
19315 version, controlled by @code{Library_Version} attribute, is not changed,
19316 then the clients do not need to be relinked.
19317
19318 SALs also allow the library providers to minimize the amount of library source
19319 text exposed to the clients.  Such ``information hiding'' might be useful or
19320 necessary for various reasons.
19321
19322 Stand-alone libraries are also well suited to be used in an executable whose
19323 main routine is not written in Ada.
19324
19325 @node Building a Stand-alone Library
19326 @subsection Building a Stand-alone Library
19327
19328 @noindent
19329 GNAT's Project facility provides a simple way of building and installing
19330 stand-alone libraries; see @ref{Stand-alone Library Projects}.
19331 To be a Stand-alone Library Project, in addition to the two attributes
19332 that make a project a Library Project (@code{Library_Name} and
19333 @code{Library_Dir}; see @ref{Library Projects}), the attribute
19334 @code{Library_Interface} must be defined.  For example:
19335
19336 @smallexample @c projectfile
19337 @group
19338    for Library_Dir use "lib_dir";
19339    for Library_Name use "dummy";
19340    for Library_Interface use ("int1", "int1.child");
19341 @end group
19342 @end smallexample
19343
19344 @noindent
19345 Attribute @code{Library_Interface} has a non-empty string list value,
19346 each string in the list designating a unit contained in an immediate source
19347 of the project file.
19348
19349 When a Stand-alone Library is built, first the binder is invoked to build
19350 a package whose name depends on the library name
19351 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
19352 This binder-generated package includes initialization and
19353 finalization procedures whose
19354 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
19355 in the example
19356 above). The object corresponding to this package is included in the library.
19357
19358 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
19359 calling of these procedures if a static SAL is built, or if a shared SAL
19360 is built
19361 with the project-level attribute @code{Library_Auto_Init} set to
19362 @code{"false"}.
19363
19364 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
19365 (those that are listed in attribute @code{Library_Interface}) are copied to
19366 the Library Directory. As a consequence, only the Interface Units may be
19367 imported from Ada units outside of the library. If other units are imported,
19368 the binding phase will fail.
19369
19370 The attribute @code{Library_Src_Dir} may be specified for a
19371 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
19372 single string value. Its value must be the path (absolute or relative to the
19373 project directory) of an existing directory. This directory cannot be the
19374 object directory or one of the source directories, but it can be the same as
19375 the library directory. The sources of the Interface
19376 Units of the library that are needed by an Ada client of the library will be
19377 copied to the designated directory, called the Interface Copy directory.
19378 These sources include the specs of the Interface Units, but they may also
19379 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
19380 are used, or when there is a generic unit in the spec. Before the sources
19381 are copied to the Interface Copy directory, an attempt is made to delete all
19382 files in the Interface Copy directory.
19383
19384 Building stand-alone libraries by hand is somewhat tedious, but for those
19385 occasions when it is necessary here are the steps that you need to perform:
19386 @itemize @bullet
19387 @item
19388 Compile all library sources.
19389
19390 @item
19391 Invoke the binder with the switch @option{-n} (No Ada main program),
19392 with all the @file{ALI} files of the interfaces, and
19393 with the switch @option{-L} to give specific names to the @code{init}
19394 and @code{final} procedures.  For example:
19395 @smallexample
19396   gnatbind -n int1.ali int2.ali -Lsal1
19397 @end smallexample
19398
19399 @item
19400 Compile the binder generated file:
19401 @smallexample
19402   gcc -c b~int2.adb
19403 @end smallexample
19404
19405 @item
19406 Link the dynamic library with all the necessary object files,
19407 indicating to the linker the names of the @code{init} (and possibly
19408 @code{final}) procedures for automatic initialization (and finalization).
19409 The built library should be placed in a directory different from
19410 the object directory.
19411
19412 @item
19413 Copy the @code{ALI} files of the interface to the library directory,
19414 add in this copy an indication that it is an interface to a SAL
19415 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19416 with letter ``P'') and make the modified copy of the @file{ALI} file
19417 read-only.
19418 @end itemize
19419
19420 @noindent
19421 Using SALs is not different from using other libraries
19422 (see @ref{Using a library}).
19423
19424 @node Creating a Stand-alone Library to be used in a non-Ada context
19425 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19426
19427 @noindent
19428 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19429 a non-Ada context.
19430
19431 The only extra step required is to ensure that library interface subprograms
19432 are compatible with the main program, by means of @code{pragma Export}
19433 or @code{pragma Convention}.
19434
19435 Here is an example of simple library interface for use with C main program:
19436
19437 @smallexample @c ada
19438 package My_Package is
19439
19440    procedure Do_Something;
19441    pragma Export (C, Do_Something, "do_something");
19442
19443    procedure Do_Something_Else;
19444    pragma Export (C, Do_Something_Else, "do_something_else");
19445
19446 end My_Package;
19447 @end smallexample
19448
19449 @noindent
19450 On the foreign language side, you must provide a ``foreign'' view of the
19451 library interface; remember that it should contain elaboration routines in
19452 addition to interface subprograms.
19453
19454 The example below shows the content of @code{mylib_interface.h} (note
19455 that there is no rule for the naming of this file, any name can be used)
19456 @smallexample
19457 /* the library elaboration procedure */
19458 extern void mylibinit (void);
19459
19460 /* the library finalization procedure */
19461 extern void mylibfinal (void);
19462
19463 /* the interface exported by the library */
19464 extern void do_something (void);
19465 extern void do_something_else (void);
19466 @end smallexample
19467
19468 @noindent
19469 Libraries built as explained above can be used from any program, provided
19470 that the elaboration procedures (named @code{mylibinit} in the previous
19471 example) are called before the library services are used. Any number of
19472 libraries can be used simultaneously, as long as the elaboration
19473 procedure of each library is called.
19474
19475 Below is an example of a C program that uses the @code{mylib} library.
19476
19477 @smallexample
19478 #include "mylib_interface.h"
19479
19480 int
19481 main (void)
19482 @{
19483    /* First, elaborate the library before using it */
19484    mylibinit ();
19485
19486    /* Main program, using the library exported entities */
19487    do_something ();
19488    do_something_else ();
19489
19490    /* Library finalization at the end of the program */
19491    mylibfinal ();
19492    return 0;
19493 @}
19494 @end smallexample
19495
19496 @noindent
19497 Note that invoking any library finalization procedure generated by
19498 @code{gnatbind} shuts down the Ada run-time environment.
19499 Consequently, the
19500 finalization of all Ada libraries must be performed at the end of the program.
19501 No call to these libraries or to the Ada run-time library should be made
19502 after the finalization phase.
19503
19504 @node Restrictions in Stand-alone Libraries
19505 @subsection Restrictions in Stand-alone Libraries
19506
19507 @noindent
19508 The pragmas listed below should be used with caution inside libraries,
19509 as they can create incompatibilities with other Ada libraries:
19510 @itemize @bullet
19511 @item pragma @code{Locking_Policy}
19512 @item pragma @code{Queuing_Policy}
19513 @item pragma @code{Task_Dispatching_Policy}
19514 @item pragma @code{Unreserve_All_Interrupts}
19515 @end itemize
19516
19517 @noindent
19518 When using a library that contains such pragmas, the user must make sure
19519 that all libraries use the same pragmas with the same values. Otherwise,
19520 @code{Program_Error} will
19521 be raised during the elaboration of the conflicting
19522 libraries. The usage of these pragmas and its consequences for the user
19523 should therefore be well documented.
19524
19525 Similarly, the traceback in the exception occurrence mechanism should be
19526 enabled or disabled in a consistent manner across all libraries.
19527 Otherwise, Program_Error will be raised during the elaboration of the
19528 conflicting libraries.
19529
19530 If the @code{Version} or @code{Body_Version}
19531 attributes are used inside a library, then you need to
19532 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19533 libraries, so that version identifiers can be properly computed.
19534 In practice these attributes are rarely used, so this is unlikely
19535 to be a consideration.
19536
19537 @node  Rebuilding the GNAT Run-Time Library
19538 @section Rebuilding the GNAT Run-Time Library
19539 @cindex GNAT Run-Time Library, rebuilding
19540 @cindex Building the GNAT Run-Time Library
19541 @cindex Rebuilding the GNAT Run-Time Library
19542 @cindex Run-Time Library, rebuilding
19543
19544 @noindent
19545 It may be useful to recompile the GNAT library in various contexts, the
19546 most important one being the use of partition-wide configuration pragmas
19547 such as @code{Normalize_Scalars}. A special Makefile called
19548 @code{Makefile.adalib} is provided to that effect and can be found in
19549 the directory containing the GNAT library. The location of this
19550 directory depends on the way the GNAT environment has been installed and can
19551 be determined by means of the command:
19552
19553 @smallexample
19554 $ gnatls -v
19555 @end smallexample
19556
19557 @noindent
19558 The last entry in the object search path usually contains the
19559 gnat library. This Makefile contains its own documentation and in
19560 particular the set of instructions needed to rebuild a new library and
19561 to use it.
19562
19563 @node Using the GNU make Utility
19564 @chapter Using the GNU @code{make} Utility
19565 @findex make
19566
19567 @noindent
19568 This chapter offers some examples of makefiles that solve specific
19569 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19570 make, make, GNU @code{make}}), nor does it try to replace the
19571 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19572
19573 All the examples in this section are specific to the GNU version of
19574 make. Although @command{make} is a standard utility, and the basic language
19575 is the same, these examples use some advanced features found only in
19576 @code{GNU make}.
19577
19578 @menu
19579 * Using gnatmake in a Makefile::
19580 * Automatically Creating a List of Directories::
19581 * Generating the Command Line Switches::
19582 * Overcoming Command Line Length Limits::
19583 @end menu
19584
19585 @node Using gnatmake in a Makefile
19586 @section Using gnatmake in a Makefile
19587 @findex makefile
19588 @cindex GNU make
19589
19590 @noindent
19591 Complex project organizations can be handled in a very powerful way by
19592 using GNU make combined with gnatmake. For instance, here is a Makefile
19593 which allows you to build each subsystem of a big project into a separate
19594 shared library. Such a makefile allows you to significantly reduce the link
19595 time of very big applications while maintaining full coherence at
19596 each step of the build process.
19597
19598 The list of dependencies are handled automatically by
19599 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19600 the appropriate directories.
19601
19602 Note that you should also read the example on how to automatically
19603 create the list of directories
19604 (@pxref{Automatically Creating a List of Directories})
19605 which might help you in case your project has a lot of subdirectories.
19606
19607 @smallexample
19608 @iftex
19609 @leftskip=0cm
19610 @font@heightrm=cmr8
19611 @heightrm
19612 @end iftex
19613 ## This Makefile is intended to be used with the following directory
19614 ## configuration:
19615 ##  - The sources are split into a series of csc (computer software components)
19616 ##    Each of these csc is put in its own directory.
19617 ##    Their name are referenced by the directory names.
19618 ##    They will be compiled into shared library (although this would also work
19619 ##    with static libraries
19620 ##  - The main program (and possibly other packages that do not belong to any
19621 ##    csc is put in the top level directory (where the Makefile is).
19622 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
19623 ##                    \_ second_csc (sources) __ lib (will contain the library)
19624 ##                    \_ @dots{}
19625 ## Although this Makefile is build for shared library, it is easy to modify
19626 ## to build partial link objects instead (modify the lines with -shared and
19627 ## gnatlink below)
19628 ##
19629 ## With this makefile, you can change any file in the system or add any new
19630 ## file, and everything will be recompiled correctly (only the relevant shared
19631 ## objects will be recompiled, and the main program will be re-linked).
19632
19633 # The list of computer software component for your project. This might be
19634 # generated automatically.
19635 CSC_LIST=aa bb cc
19636
19637 # Name of the main program (no extension)
19638 MAIN=main
19639
19640 # If we need to build objects with -fPIC, uncomment the following line
19641 #NEED_FPIC=-fPIC
19642
19643 # The following variable should give the directory containing libgnat.so
19644 # You can get this directory through 'gnatls -v'. This is usually the last
19645 # directory in the Object_Path.
19646 GLIB=@dots{}
19647
19648 # The directories for the libraries
19649 # (This macro expands the list of CSC to the list of shared libraries, you
19650 # could simply use the expanded form:
19651 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19652 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19653
19654 $@{MAIN@}: objects $@{LIB_DIR@}
19655     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19656     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19657
19658 objects::
19659     # recompile the sources
19660     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19661
19662 # Note: In a future version of GNAT, the following commands will be simplified
19663 # by a new tool, gnatmlib
19664 $@{LIB_DIR@}:
19665     mkdir -p $@{dir $@@ @}
19666     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19667     cd $@{dir $@@ @} && cp -f ../*.ali .
19668
19669 # The dependencies for the modules
19670 # Note that we have to force the expansion of *.o, since in some cases
19671 # make won't be able to do it itself.
19672 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19673 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19674 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19675
19676 # Make sure all of the shared libraries are in the path before starting the
19677 # program
19678 run::
19679     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19680
19681 clean::
19682     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19683     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19684     $@{RM@} $@{CSC_LIST:%=%/*.o@}
19685     $@{RM@} *.o *.ali $@{MAIN@}
19686 @end smallexample
19687
19688 @node Automatically Creating a List of Directories
19689 @section Automatically Creating a List of Directories
19690
19691 @noindent
19692 In most makefiles, you will have to specify a list of directories, and
19693 store it in a variable. For small projects, it is often easier to
19694 specify each of them by hand, since you then have full control over what
19695 is the proper order for these directories, which ones should be
19696 included.
19697
19698 However, in larger projects, which might involve hundreds of
19699 subdirectories, it might be more convenient to generate this list
19700 automatically.
19701
19702 The example below presents two methods. The first one, although less
19703 general, gives you more control over the list. It involves wildcard
19704 characters, that are automatically expanded by @command{make}. Its
19705 shortcoming is that you need to explicitly specify some of the
19706 organization of your project, such as for instance the directory tree
19707 depth, whether some directories are found in a separate tree, @enddots{}
19708
19709 The second method is the most general one. It requires an external
19710 program, called @command{find}, which is standard on all Unix systems. All
19711 the directories found under a given root directory will be added to the
19712 list.
19713
19714 @smallexample
19715 @iftex
19716 @leftskip=0cm
19717 @font@heightrm=cmr8
19718 @heightrm
19719 @end iftex
19720 # The examples below are based on the following directory hierarchy:
19721 # All the directories can contain any number of files
19722 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
19723 #                       ->  ab
19724 #                       ->  ac
19725 #                ->  b  ->  ba  ->  baa
19726 #                       ->  bb
19727 #                       ->  bc
19728 # This Makefile creates a variable called DIRS, that can be reused any time
19729 # you need this list (see the other examples in this section)
19730
19731 # The root of your project's directory hierarchy
19732 ROOT_DIRECTORY=.
19733
19734 ####
19735 # First method: specify explicitly the list of directories
19736 # This allows you to specify any subset of all the directories you need.
19737 ####
19738
19739 DIRS := a/aa/ a/ab/ b/ba/
19740
19741 ####
19742 # Second method: use wildcards
19743 # Note that the argument(s) to wildcard below should end with a '/'.
19744 # Since wildcards also return file names, we have to filter them out
19745 # to avoid duplicate directory names.
19746 # We thus use make's @code{dir} and @code{sort} functions.
19747 # It sets DIRs to the following value (note that the directories aaa and baa
19748 # are not given, unless you change the arguments to wildcard).
19749 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19750 ####
19751
19752 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19753                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19754
19755 ####
19756 # Third method: use an external program
19757 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19758 # This is the most complete command: it sets DIRs to the following value:
19759 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19760 ####
19761
19762 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19763
19764 @end smallexample
19765
19766 @node Generating the Command Line Switches
19767 @section Generating the Command Line Switches
19768
19769 @noindent
19770 Once you have created the list of directories as explained in the
19771 previous section (@pxref{Automatically Creating a List of Directories}),
19772 you can easily generate the command line arguments to pass to gnatmake.
19773
19774 For the sake of completeness, this example assumes that the source path
19775 is not the same as the object path, and that you have two separate lists
19776 of directories.
19777
19778 @smallexample
19779 # see "Automatically creating a list of directories" to create
19780 # these variables
19781 SOURCE_DIRS=
19782 OBJECT_DIRS=
19783
19784 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19785 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19786
19787 all:
19788         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19789 @end smallexample
19790
19791 @node Overcoming Command Line Length Limits
19792 @section Overcoming Command Line Length Limits
19793
19794 @noindent
19795 One problem that might be encountered on big projects is that many
19796 operating systems limit the length of the command line. It is thus hard to give
19797 gnatmake the list of source and object directories.
19798
19799 This example shows how you can set up environment variables, which will
19800 make @command{gnatmake} behave exactly as if the directories had been
19801 specified on the command line, but have a much higher length limit (or
19802 even none on most systems).
19803
19804 It assumes that you have created a list of directories in your Makefile,
19805 using one of the methods presented in
19806 @ref{Automatically Creating a List of Directories}.
19807 For the sake of completeness, we assume that the object
19808 path (where the ALI files are found) is different from the sources patch.
19809
19810 Note a small trick in the Makefile below: for efficiency reasons, we
19811 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19812 expanded immediately by @code{make}. This way we overcome the standard
19813 make behavior which is to expand the variables only when they are
19814 actually used.
19815
19816 On Windows, if you are using the standard Windows command shell, you must
19817 replace colons with semicolons in the assignments to these variables.
19818
19819 @smallexample
19820 @iftex
19821 @leftskip=0cm
19822 @font@heightrm=cmr8
19823 @heightrm
19824 @end iftex
19825 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19826 # This is the same thing as putting the -I arguments on the command line.
19827 # (the equivalent of using -aI on the command line would be to define
19828 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19829 # You can of course have different values for these variables.
19830 #
19831 # Note also that we need to keep the previous values of these variables, since
19832 # they might have been set before running 'make' to specify where the GNAT
19833 # library is installed.
19834
19835 # see "Automatically creating a list of directories" to create these
19836 # variables
19837 SOURCE_DIRS=
19838 OBJECT_DIRS=
19839
19840 empty:=
19841 space:=$@{empty@} $@{empty@}
19842 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19843 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19844 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19845 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19846 export ADA_INCLUDE_PATH
19847 export ADA_OBJECT_PATH
19848
19849 all:
19850         gnatmake main_unit
19851 @end smallexample
19852 @end ifclear
19853
19854 @node Memory Management Issues
19855 @chapter Memory Management Issues
19856
19857 @noindent
19858 This chapter describes some useful memory pools provided in the GNAT library
19859 and in particular the GNAT Debug Pool facility, which can be used to detect
19860 incorrect uses of access values (including ``dangling references'').
19861 @ifclear vms
19862 It also describes the @command{gnatmem} tool, which can be used to track down
19863 ``memory leaks''.
19864 @end ifclear
19865
19866 @menu
19867 * Some Useful Memory Pools::
19868 * The GNAT Debug Pool Facility::
19869 @ifclear vms
19870 * The gnatmem Tool::
19871 @end ifclear
19872 @end menu
19873
19874 @node Some Useful Memory Pools
19875 @section Some Useful Memory Pools
19876 @findex Memory Pool
19877 @cindex storage, pool
19878
19879 @noindent
19880 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19881 storage pool. Allocations use the standard system call @code{malloc} while
19882 deallocations use the standard system call @code{free}. No reclamation is
19883 performed when the pool goes out of scope. For performance reasons, the
19884 standard default Ada allocators/deallocators do not use any explicit storage
19885 pools but if they did, they could use this storage pool without any change in
19886 behavior. That is why this storage pool is used  when the user
19887 manages to make the default implicit allocator explicit as in this example:
19888 @smallexample @c ada
19889    type T1 is access Something;
19890     -- no Storage pool is defined for T2
19891    type T2 is access Something_Else;
19892    for T2'Storage_Pool use T1'Storage_Pool;
19893    -- the above is equivalent to
19894    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19895 @end smallexample
19896
19897 @noindent
19898 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19899 pool. The allocation strategy is similar to @code{Pool_Local}'s
19900 except that the all
19901 storage allocated with this pool is reclaimed when the pool object goes out of
19902 scope. This pool provides a explicit mechanism similar to the implicit one
19903 provided by several Ada 83 compilers for allocations performed through a local
19904 access type and whose purpose was to reclaim memory when exiting the
19905 scope of a given local access. As an example, the following program does not
19906 leak memory even though it does not perform explicit deallocation:
19907
19908 @smallexample @c ada
19909 with System.Pool_Local;
19910 procedure Pooloc1 is
19911    procedure Internal is
19912       type A is access Integer;
19913       X : System.Pool_Local.Unbounded_Reclaim_Pool;
19914       for A'Storage_Pool use X;
19915       v : A;
19916    begin
19917       for I in  1 .. 50 loop
19918          v := new Integer;
19919       end loop;
19920    end Internal;
19921 begin
19922    for I in  1 .. 100 loop
19923       Internal;
19924    end loop;
19925 end Pooloc1;
19926 @end smallexample
19927
19928 @noindent
19929 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19930 @code{Storage_Size} is specified for an access type.
19931 The whole storage for the pool is
19932 allocated at once, usually on the stack at the point where the access type is
19933 elaborated. It is automatically reclaimed when exiting the scope where the
19934 access type is defined. This package is not intended to be used directly by the
19935 user and it is implicitly used for each such declaration:
19936
19937 @smallexample @c ada
19938    type T1 is access Something;
19939    for T1'Storage_Size use 10_000;
19940 @end smallexample
19941
19942 @node The GNAT Debug Pool Facility
19943 @section The GNAT Debug Pool Facility
19944 @findex Debug Pool
19945 @cindex storage, pool, memory corruption
19946
19947 @noindent
19948 The use of unchecked deallocation and unchecked conversion can easily
19949 lead to incorrect memory references. The problems generated by such
19950 references are usually difficult to tackle because the symptoms can be
19951 very remote from the origin of the problem. In such cases, it is
19952 very helpful to detect the problem as early as possible. This is the
19953 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19954
19955 In order to use the GNAT specific debugging pool, the user must
19956 associate a debug pool object with each of the access types that may be
19957 related to suspected memory problems. See Ada Reference Manual 13.11.
19958 @smallexample @c ada
19959 type Ptr is access Some_Type;
19960 Pool : GNAT.Debug_Pools.Debug_Pool;
19961 for Ptr'Storage_Pool use Pool;
19962 @end smallexample
19963
19964 @noindent
19965 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19966 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19967 allow the user to redefine allocation and deallocation strategies. They
19968 also provide a checkpoint for each dereference, through the use of
19969 the primitive operation @code{Dereference} which is implicitly called at
19970 each dereference of an access value.
19971
19972 Once an access type has been associated with a debug pool, operations on
19973 values of the type may raise four distinct exceptions,
19974 which correspond to four potential kinds of memory corruption:
19975 @itemize @bullet
19976 @item
19977 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19978 @item
19979 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19980 @item
19981 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19982 @item
19983 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19984 @end itemize
19985
19986 @noindent
19987 For types associated with a Debug_Pool, dynamic allocation is performed using
19988 the standard GNAT allocation routine. References to all allocated chunks of
19989 memory are kept in an internal dictionary. Several deallocation strategies are
19990 provided, whereupon the user can choose to release the memory to the system,
19991 keep it allocated for further invalid access checks, or fill it with an easily
19992 recognizable pattern for debug sessions. The memory pattern is the old IBM
19993 hexadecimal convention: @code{16#DEADBEEF#}.
19994
19995 See the documentation in the file g-debpoo.ads for more information on the
19996 various strategies.
19997
19998 Upon each dereference, a check is made that the access value denotes a
19999 properly allocated memory location. Here is a complete example of use of
20000 @code{Debug_Pools}, that includes typical instances of  memory corruption:
20001 @smallexample @c ada
20002 @iftex
20003 @leftskip=0cm
20004 @end iftex
20005 with Gnat.Io; use Gnat.Io;
20006 with Unchecked_Deallocation;
20007 with Unchecked_Conversion;
20008 with GNAT.Debug_Pools;
20009 with System.Storage_Elements;
20010 with Ada.Exceptions; use Ada.Exceptions;
20011 procedure Debug_Pool_Test is
20012
20013    type T is access Integer;
20014    type U is access all T;
20015
20016    P : GNAT.Debug_Pools.Debug_Pool;
20017    for T'Storage_Pool use P;
20018
20019    procedure Free is new Unchecked_Deallocation (Integer, T);
20020    function UC is new Unchecked_Conversion (U, T);
20021    A, B : aliased T;
20022
20023    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
20024
20025 begin
20026    Info (P);
20027    A := new Integer;
20028    B := new Integer;
20029    B := A;
20030    Info (P);
20031    Free (A);
20032    begin
20033       Put_Line (Integer'Image(B.all));
20034    exception
20035       when E : others => Put_Line ("raised: " & Exception_Name (E));
20036    end;
20037    begin
20038       Free (B);
20039    exception
20040       when E : others => Put_Line ("raised: " & Exception_Name (E));
20041    end;
20042    B := UC(A'Access);
20043    begin
20044       Put_Line (Integer'Image(B.all));
20045    exception
20046       when E : others => Put_Line ("raised: " & Exception_Name (E));
20047    end;
20048    begin
20049       Free (B);
20050    exception
20051       when E : others => Put_Line ("raised: " & Exception_Name (E));
20052    end;
20053    Info (P);
20054 end Debug_Pool_Test;
20055 @end smallexample
20056
20057 @noindent
20058 The debug pool mechanism provides the following precise diagnostics on the
20059 execution of this erroneous program:
20060 @smallexample
20061 Debug Pool info:
20062   Total allocated bytes :  0
20063   Total deallocated bytes :  0
20064   Current Water Mark:  0
20065   High Water Mark:  0
20066
20067 Debug Pool info:
20068   Total allocated bytes :  8
20069   Total deallocated bytes :  0
20070   Current Water Mark:  8
20071   High Water Mark:  8
20072
20073 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
20074 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
20075 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
20076 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
20077 Debug Pool info:
20078   Total allocated bytes :  8
20079   Total deallocated bytes :  4
20080   Current Water Mark:  4
20081   High Water Mark:  8
20082 @end smallexample
20083
20084 @ifclear vms
20085 @node The gnatmem Tool
20086 @section The @command{gnatmem} Tool
20087 @findex gnatmem
20088
20089 @noindent
20090 The @code{gnatmem} utility monitors dynamic allocation and
20091 deallocation activity in a program, and displays information about
20092 incorrect deallocations and possible sources of memory leaks.
20093 It is designed to work in association with a static runtime library
20094 only and in this context provides three types of information:
20095 @itemize @bullet
20096 @item
20097 General information concerning memory management, such as the total
20098 number of allocations and deallocations, the amount of allocated
20099 memory and the high water mark, i.e.@: the largest amount of allocated
20100 memory in the course of program execution.
20101
20102 @item
20103 Backtraces for all incorrect deallocations, that is to say deallocations
20104 which do not correspond to a valid allocation.
20105
20106 @item
20107 Information on each allocation that is potentially the origin of a memory
20108 leak.
20109 @end itemize
20110
20111 @menu
20112 * Running gnatmem::
20113 * Switches for gnatmem::
20114 * Example of gnatmem Usage::
20115 @end menu
20116
20117 @node Running gnatmem
20118 @subsection Running @code{gnatmem}
20119
20120 @noindent
20121 @code{gnatmem} makes use of the output created by the special version of
20122 allocation and deallocation routines that record call information. This
20123 allows to obtain accurate dynamic memory usage history at a minimal cost to
20124 the execution speed. Note however, that @code{gnatmem} is not supported on
20125 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
20126 Solaris and Windows NT/2000/XP (x86).
20127
20128 @noindent
20129 The @code{gnatmem} command has the form
20130
20131 @smallexample
20132    $ gnatmem @ovar{switches} user_program
20133 @end smallexample
20134
20135 @noindent
20136 The program must have been linked with the instrumented version of the
20137 allocation and deallocation routines. This is done by linking with the
20138 @file{libgmem.a} library. For correct symbolic backtrace information,
20139 the user program should be compiled with debugging options
20140 (see @ref{Switches for gcc}). For example to build @file{my_program}:
20141
20142 @smallexample
20143 $ gnatmake -g my_program -largs -lgmem
20144 @end smallexample
20145
20146 @noindent
20147 As library @file{libgmem.a} contains an alternate body for package
20148 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
20149 when an executable is linked with library @file{libgmem.a}. It is then not
20150 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
20151
20152 @noindent
20153 When @file{my_program} is executed, the file @file{gmem.out} is produced.
20154 This file contains information about all allocations and deallocations
20155 performed by the program. It is produced by the instrumented allocations and
20156 deallocations routines and will be used by @code{gnatmem}.
20157
20158 In order to produce symbolic backtrace information for allocations and
20159 deallocations performed by the GNAT run-time library, you need to use a
20160 version of that library that has been compiled with the @option{-g} switch
20161 (see @ref{Rebuilding the GNAT Run-Time Library}).
20162
20163 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
20164 examine. If the location of @file{gmem.out} file was not explicitly supplied by
20165 @option{-i} switch, gnatmem will assume that this file can be found in the
20166 current directory. For example, after you have executed @file{my_program},
20167 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
20168
20169 @smallexample
20170 $ gnatmem my_program
20171 @end smallexample
20172
20173 @noindent
20174 This will produce the output with the following format:
20175
20176 *************** debut cc
20177 @smallexample
20178 $ gnatmem my_program
20179
20180 Global information
20181 ------------------
20182    Total number of allocations        :  45
20183    Total number of deallocations      :   6
20184    Final Water Mark (non freed mem)   :  11.29 Kilobytes
20185    High Water Mark                    :  11.40 Kilobytes
20186
20187 .
20188 .
20189 .
20190 Allocation Root # 2
20191 -------------------
20192  Number of non freed allocations    :  11
20193  Final Water Mark (non freed mem)   :   1.16 Kilobytes
20194  High Water Mark                    :   1.27 Kilobytes
20195  Backtrace                          :
20196    my_program.adb:23 my_program.alloc
20197 .
20198 .
20199 .
20200 @end smallexample
20201
20202 The first block of output gives general information. In this case, the
20203 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
20204 Unchecked_Deallocation routine occurred.
20205
20206 @noindent
20207 Subsequent paragraphs display  information on all allocation roots.
20208 An allocation root is a specific point in the execution of the program
20209 that generates some dynamic allocation, such as a ``@code{@b{new}}''
20210 construct. This root is represented by an execution backtrace (or subprogram
20211 call stack). By default the backtrace depth for allocations roots is 1, so
20212 that a root corresponds exactly to a source location. The backtrace can
20213 be made deeper, to make the root more specific.
20214
20215 @node Switches for gnatmem
20216 @subsection Switches for @code{gnatmem}
20217
20218 @noindent
20219 @code{gnatmem} recognizes the following switches:
20220
20221 @table @option
20222
20223 @item -q
20224 @cindex @option{-q} (@code{gnatmem})
20225 Quiet. Gives the minimum output needed to identify the origin of the
20226 memory leaks. Omits statistical information.
20227
20228 @item @var{N}
20229 @cindex @var{N} (@code{gnatmem})
20230 N is an integer literal (usually between 1 and 10) which controls the
20231 depth of the backtraces defining allocation root. The default value for
20232 N is 1. The deeper the backtrace, the more precise the localization of
20233 the root. Note that the total number of roots can depend on this
20234 parameter. This parameter must be specified @emph{before} the name of the
20235 executable to be analyzed, to avoid ambiguity.
20236
20237 @item -b n
20238 @cindex @option{-b} (@code{gnatmem})
20239 This switch has the same effect as just depth parameter.
20240
20241 @item -i @var{file}
20242 @cindex @option{-i} (@code{gnatmem})
20243 Do the @code{gnatmem} processing starting from @file{file}, rather than
20244 @file{gmem.out} in the current directory.
20245
20246 @item -m n
20247 @cindex @option{-m} (@code{gnatmem})
20248 This switch causes @code{gnatmem} to mask the allocation roots that have less
20249 than n leaks. The default value is 1. Specifying the value of 0 will allow to
20250 examine even the roots that didn't result in leaks.
20251
20252 @item -s order
20253 @cindex @option{-s} (@code{gnatmem})
20254 This switch causes @code{gnatmem} to sort the allocation roots according to the
20255 specified order of sort criteria, each identified by a single letter. The
20256 currently supported criteria are @code{n, h, w} standing respectively for
20257 number of unfreed allocations, high watermark, and final watermark
20258 corresponding to a specific root. The default order is @code{nwh}.
20259
20260 @end table
20261
20262 @node Example of gnatmem Usage
20263 @subsection Example of @code{gnatmem} Usage
20264
20265 @noindent
20266 The following example shows the use of @code{gnatmem}
20267 on a simple memory-leaking program.
20268 Suppose that we have the following Ada program:
20269
20270 @smallexample @c ada
20271 @group
20272 @cartouche
20273 with Unchecked_Deallocation;
20274 procedure Test_Gm is
20275
20276    type T is array (1..1000) of Integer;
20277    type Ptr is access T;
20278    procedure Free is new Unchecked_Deallocation (T, Ptr);
20279    A : Ptr;
20280
20281    procedure My_Alloc is
20282    begin
20283       A := new T;
20284    end My_Alloc;
20285
20286    procedure My_DeAlloc is
20287       B : Ptr := A;
20288    begin
20289       Free (B);
20290    end My_DeAlloc;
20291
20292 begin
20293    My_Alloc;
20294    for I in 1 .. 5 loop
20295       for J in I .. 5 loop
20296          My_Alloc;
20297       end loop;
20298       My_Dealloc;
20299    end loop;
20300 end;
20301 @end cartouche
20302 @end group
20303 @end smallexample
20304
20305 @noindent
20306 The program needs to be compiled with debugging option and linked with
20307 @code{gmem} library:
20308
20309 @smallexample
20310 $ gnatmake -g test_gm -largs -lgmem
20311 @end smallexample
20312
20313 @noindent
20314 Then we execute the program as usual:
20315
20316 @smallexample
20317 $ test_gm
20318 @end smallexample
20319
20320 @noindent
20321 Then @code{gnatmem} is invoked simply with
20322 @smallexample
20323 $ gnatmem test_gm
20324 @end smallexample
20325
20326 @noindent
20327 which produces the following output (result may vary on different platforms):
20328
20329 @smallexample
20330 Global information
20331 ------------------
20332    Total number of allocations        :  18
20333    Total number of deallocations      :   5
20334    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20335    High Water Mark                    :  56.90 Kilobytes
20336
20337 Allocation Root # 1
20338 -------------------
20339  Number of non freed allocations    :  11
20340  Final Water Mark (non freed mem)   :  42.97 Kilobytes
20341  High Water Mark                    :  46.88 Kilobytes
20342  Backtrace                          :
20343    test_gm.adb:11 test_gm.my_alloc
20344
20345 Allocation Root # 2
20346 -------------------
20347  Number of non freed allocations    :   1
20348  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20349  High Water Mark                    :  10.02 Kilobytes
20350  Backtrace                          :
20351    s-secsta.adb:81 system.secondary_stack.ss_init
20352
20353 Allocation Root # 3
20354 -------------------
20355  Number of non freed allocations    :   1
20356  Final Water Mark (non freed mem)   :  12 Bytes
20357  High Water Mark                    :  12 Bytes
20358  Backtrace                          :
20359    s-secsta.adb:181 system.secondary_stack.ss_init
20360 @end smallexample
20361
20362 @noindent
20363 Note that the GNAT run time contains itself a certain number of
20364 allocations that have no  corresponding deallocation,
20365 as shown here for root #2 and root
20366 #3. This is a normal behavior when the number of non-freed allocations
20367 is one, it allocates dynamic data structures that the run time needs for
20368 the complete lifetime of the program. Note also that there is only one
20369 allocation root in the user program with a single line back trace:
20370 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
20371 program shows that 'My_Alloc' is called at 2 different points in the
20372 source (line 21 and line 24). If those two allocation roots need to be
20373 distinguished, the backtrace depth parameter can be used:
20374
20375 @smallexample
20376 $ gnatmem 3 test_gm
20377 @end smallexample
20378
20379 @noindent
20380 which will give the following output:
20381
20382 @smallexample
20383 Global information
20384 ------------------
20385    Total number of allocations        :  18
20386    Total number of deallocations      :   5
20387    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20388    High Water Mark                    :  56.90 Kilobytes
20389
20390 Allocation Root # 1
20391 -------------------
20392  Number of non freed allocations    :  10
20393  Final Water Mark (non freed mem)   :  39.06 Kilobytes
20394  High Water Mark                    :  42.97 Kilobytes
20395  Backtrace                          :
20396    test_gm.adb:11 test_gm.my_alloc
20397    test_gm.adb:24 test_gm
20398    b_test_gm.c:52 main
20399
20400 Allocation Root # 2
20401 -------------------
20402  Number of non freed allocations    :   1
20403  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20404  High Water Mark                    :  10.02 Kilobytes
20405  Backtrace                          :
20406    s-secsta.adb:81  system.secondary_stack.ss_init
20407    s-secsta.adb:283 <system__secondary_stack___elabb>
20408    b_test_gm.c:33   adainit
20409
20410 Allocation Root # 3
20411 -------------------
20412  Number of non freed allocations    :   1
20413  Final Water Mark (non freed mem)   :   3.91 Kilobytes
20414  High Water Mark                    :   3.91 Kilobytes
20415  Backtrace                          :
20416    test_gm.adb:11 test_gm.my_alloc
20417    test_gm.adb:21 test_gm
20418    b_test_gm.c:52 main
20419
20420 Allocation Root # 4
20421 -------------------
20422  Number of non freed allocations    :   1
20423  Final Water Mark (non freed mem)   :  12 Bytes
20424  High Water Mark                    :  12 Bytes
20425  Backtrace                          :
20426    s-secsta.adb:181 system.secondary_stack.ss_init
20427    s-secsta.adb:283 <system__secondary_stack___elabb>
20428    b_test_gm.c:33   adainit
20429 @end smallexample
20430
20431 @noindent
20432 The allocation root #1 of the first example has been split in 2 roots #1
20433 and #3 thanks to the more precise associated backtrace.
20434
20435 @end ifclear
20436
20437 @node Stack Related Facilities
20438 @chapter Stack Related Facilities
20439
20440 @noindent
20441 This chapter describes some useful tools associated with stack
20442 checking and analysis. In
20443 particular, it deals with dynamic and static stack usage measurements.
20444
20445 @menu
20446 * Stack Overflow Checking::
20447 * Static Stack Usage Analysis::
20448 * Dynamic Stack Usage Analysis::
20449 @end menu
20450
20451 @node Stack Overflow Checking
20452 @section Stack Overflow Checking
20453 @cindex Stack Overflow Checking
20454 @cindex -fstack-check
20455
20456 @noindent
20457 For most operating systems, @command{gcc} does not perform stack overflow
20458 checking by default. This means that if the main environment task or
20459 some other task exceeds the available stack space, then unpredictable
20460 behavior will occur. Most native systems offer some level of protection by
20461 adding a guard page at the end of each task stack. This mechanism is usually
20462 not enough for dealing properly with stack overflow situations because
20463 a large local variable could ``jump'' above the guard page.
20464 Furthermore, when the
20465 guard page is hit, there may not be any space left on the stack for executing
20466 the exception propagation code. Enabling stack checking avoids
20467 such situations.
20468
20469 To activate stack checking, compile all units with the gcc option
20470 @option{-fstack-check}. For example:
20471
20472 @smallexample
20473 gcc -c -fstack-check package1.adb
20474 @end smallexample
20475
20476 @noindent
20477 Units compiled with this option will generate extra instructions to check
20478 that any use of the stack (for procedure calls or for declaring local
20479 variables in declare blocks) does not exceed the available stack space.
20480 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20481
20482 For declared tasks, the stack size is controlled by the size
20483 given in an applicable @code{Storage_Size} pragma or by the value specified
20484 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20485 the default size as defined in the GNAT runtime otherwise.
20486
20487 For the environment task, the stack size depends on
20488 system defaults and is unknown to the compiler. Stack checking
20489 may still work correctly if a fixed
20490 size stack is allocated, but this cannot be guaranteed.
20491 @ifclear vms
20492 To ensure that a clean exception is signalled for stack
20493 overflow, set the environment variable
20494 @env{GNAT_STACK_LIMIT} to indicate the maximum
20495 stack area that can be used, as in:
20496 @cindex GNAT_STACK_LIMIT
20497
20498 @smallexample
20499 SET GNAT_STACK_LIMIT 1600
20500 @end smallexample
20501
20502 @noindent
20503 The limit is given in kilobytes, so the above declaration would
20504 set the stack limit of the environment task to 1.6 megabytes.
20505 Note that the only purpose of this usage is to limit the amount
20506 of stack used by the environment task. If it is necessary to
20507 increase the amount of stack for the environment task, then this
20508 is an operating systems issue, and must be addressed with the
20509 appropriate operating systems commands.
20510 @end ifclear
20511 @ifset vms
20512 To have a fixed size stack in the environment task, the stack must be put
20513 in the P0 address space and its size specified.  Use these switches to
20514 create a p0 image:
20515
20516 @smallexample
20517 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20518 @end smallexample
20519
20520 @noindent
20521 The quotes are required to keep case.  The number after @samp{STACK=} is the
20522 size of the environmental task stack in pagelets (512 bytes).  In this example
20523 the stack size is about 2 megabytes.
20524
20525 @noindent
20526 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20527 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
20528 more details about the @option{/p0image} qualifier and the @option{stack}
20529 option.
20530 @end ifset
20531
20532 @node Static Stack Usage Analysis
20533 @section Static Stack Usage Analysis
20534 @cindex Static Stack Usage Analysis
20535 @cindex -fstack-usage
20536
20537 @noindent
20538 A unit compiled with @option{-fstack-usage} will generate an extra file
20539 that specifies
20540 the maximum amount of stack used, on a per-function basis.
20541 The file has the same
20542 basename as the target object file with a @file{.su} extension.
20543 Each line of this file is made up of three fields:
20544
20545 @itemize
20546 @item
20547 The name of the function.
20548 @item
20549 A number of bytes.
20550 @item
20551 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20552 @end itemize
20553
20554 The second field corresponds to the size of the known part of the function
20555 frame.
20556
20557 The qualifier @code{static} means that the function frame size
20558 is purely static.
20559 It usually means that all local variables have a static size.
20560 In this case, the second field is a reliable measure of the function stack
20561 utilization.
20562
20563 The qualifier @code{dynamic} means that the function frame size is not static.
20564 It happens mainly when some local variables have a dynamic size. When this
20565 qualifier appears alone, the second field is not a reliable measure
20566 of the function stack analysis. When it is qualified with  @code{bounded}, it
20567 means that the second field is a reliable maximum of the function stack
20568 utilization.
20569
20570 @node Dynamic Stack Usage Analysis
20571 @section Dynamic Stack Usage Analysis
20572
20573 @noindent
20574 It is possible to measure the maximum amount of stack used by a task, by
20575 adding a switch to @command{gnatbind}, as:
20576
20577 @smallexample
20578 $ gnatbind -u0 file
20579 @end smallexample
20580
20581 @noindent
20582 With this option, at each task termination, its stack usage is  output on
20583 @file{stderr}.
20584 It is not always convenient to output the stack usage when the program
20585 is still running. Hence, it is possible to delay this output until program
20586 termination. for a given number of tasks specified as the argument of the
20587 @option{-u} option. For instance:
20588
20589 @smallexample
20590 $ gnatbind -u100 file
20591 @end smallexample
20592
20593 @noindent
20594 will buffer the stack usage information of the first 100 tasks to terminate and
20595 output this info at program termination. Results are displayed in four
20596 columns:
20597
20598 @noindent
20599 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
20600
20601 @noindent
20602 where:
20603
20604 @table @emph
20605 @item Index
20606 is a number associated with each task.
20607
20608 @item Task Name
20609 is the name of the task analyzed.
20610
20611 @item Stack Size
20612 is the maximum size for the stack.
20613
20614 @item Stack Usage
20615 is the measure done by the stack analyzer. In order to prevent overflow, the stack
20616 is not entirely analyzed, and it's not possible to know exactly how
20617 much has actually been used. The report thus contains the theoretical stack usage
20618 (Value) and the possible variation (Variation) around this value.
20619
20620 @end table
20621
20622 @noindent
20623 The environment task stack, e.g., the stack that contains the main unit, is
20624 only processed when the environment variable GNAT_STACK_LIMIT is set.
20625
20626
20627 @c *********************************
20628 @c *            GNATCHECK          *
20629 @c *********************************
20630 @node Verifying Properties Using gnatcheck
20631 @chapter Verifying Properties Using @command{gnatcheck}
20632 @findex gnatcheck
20633 @cindex @command{gnatcheck}
20634
20635 @noindent
20636 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20637 of Ada source files according to a given set of semantic rules.
20638 @cindex ASIS
20639
20640 In order to check compliance with a given rule, @command{gnatcheck} has to
20641 semantically analyze the Ada sources.
20642 Therefore, checks can only be performed on
20643 legal Ada units. Moreover, when a unit depends semantically upon units located
20644 outside the current directory, the source search path has to be provided when
20645 calling @command{gnatcheck}, either through a specified project file or
20646 through @command{gnatcheck} switches as described below.
20647
20648 A number of rules are predefined in @command{gnatcheck} and are described
20649 later in this chapter.
20650 You can also add new rules, by modifying the @command{gnatcheck} code and
20651 rebuilding the tool. In order to add a simple rule making some local checks,
20652 a small amount of straightforward ASIS-based programming is usually needed.
20653
20654 Project support for @command{gnatcheck} is provided by the GNAT
20655 driver (see @ref{The GNAT Driver and Project Files}).
20656
20657 Invoking @command{gnatcheck} on the command line has the form:
20658
20659 @smallexample
20660 $ gnatcheck @ovar{switches}  @{@var{filename}@}
20661       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20662       @r{[}-cargs @var{gcc_switches}@r{]} @r{[}-rules @var{rule_options}@r{]}
20663 @end smallexample
20664
20665 @noindent
20666 where
20667 @itemize @bullet
20668 @item
20669 @var{switches} specify the general tool options
20670
20671 @item
20672 Each @var{filename} is the name (including the extension) of a source
20673 file to process. ``Wildcards'' are allowed, and
20674 the file name may contain path information.
20675
20676 @item
20677 Each @var{arg_list_filename} is the name (including the extension) of a text
20678 file containing the names of the source files to process, separated by spaces
20679 or line breaks.
20680
20681 @item
20682 @var{gcc_switches} is a list of switches for
20683 @command{gcc}. They will be passed on to all compiler invocations made by
20684 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20685 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20686 and use the @option{-gnatec} switch to set the configuration file.
20687
20688 @item
20689 @var{rule_options} is a list of options for controlling a set of
20690 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20691 @end itemize
20692
20693 @noindent
20694 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be
20695 supplied.
20696
20697 @menu
20698 * Format of the Report File::
20699 * General gnatcheck Switches::
20700 * gnatcheck Rule Options::
20701 * Adding the Results of Compiler Checks to gnatcheck Output::
20702 * Project-Wide Checks::
20703 * Rule exemption::
20704 * Predefined Rules::
20705 @end menu
20706
20707 @node Format of the Report File
20708 @section Format of the Report File
20709 @cindex Report file (for @code{gnatcheck})
20710
20711 @noindent
20712 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20713 rule violations.
20714 It also creates a text file  that
20715 contains the complete report of the last gnatcheck run. By default this file
20716 is named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the
20717 current directory; the @option{^-o^/OUTPUT^} option can be used to change the
20718 name and/or location of the report file. This report contains:
20719 @itemize @bullet
20720 @item date and time of @command{gnatcheck} run, the version of
20721 the tool that has generated this report and the full parameters
20722 of the  @command{gnatcheck} invocation;
20723 @item list of enabled rules;
20724 @item total number of detected violations;
20725 @item list of source files where rule violations have been detected;
20726 @item list of source files where no violations have been detected.
20727 @end itemize
20728
20729 @node General gnatcheck Switches
20730 @section General @command{gnatcheck} Switches
20731
20732 @noindent
20733 The following switches control the general @command{gnatcheck} behavior
20734
20735 @table @option
20736 @c !sort!
20737 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20738 @item ^-a^/ALL^
20739 Process all units including those with read-only ALI files such as
20740 those from the GNAT Run-Time library.
20741
20742 @ifclear vms
20743 @ignore
20744 @cindex @option{-d} (@command{gnatcheck})
20745 @item -d
20746 Debug mode
20747 @end ignore
20748
20749 @cindex @option{-dd} (@command{gnatcheck})
20750 @item -dd
20751 Progress indicator mode (for use in GPS).
20752 @end ifclear
20753
20754 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20755 @item ^-h^/HELP^
20756 List the predefined and user-defined rules. For more details see
20757 @ref{Predefined Rules}.
20758
20759 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20760 @item ^-l^/LOCS^
20761 Use full source locations references in the report file. For a construct from
20762 a generic instantiation a full source location is a chain from the location
20763 of this construct in the generic unit to the place where this unit is
20764 instantiated.
20765
20766 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
20767 @item ^-log^/LOG^
20768 Duplicate all the output sent to @file{stderr} into a log file. The log file
20769 is named @file{gnatcheck.log} and is located in the current directory.
20770
20771 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20772 @item ^-m@i{nnnn}^/DIAGNOSTIC_LIMIT=@i{nnnn}^
20773 Maximum number of diagnostics to be sent to @file{stdout}, where @i{nnnn} is in
20774 the range 0@dots{}1000;
20775 the default value is 500. Zero means that there is no limitation on
20776 the number of diagnostic messages to be output.
20777
20778 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20779 @item ^-q^/QUIET^
20780 Quiet mode. All the diagnostics about rule violations are placed in the
20781 @command{gnatcheck} report file only, without duplication on @file{stdout}.
20782
20783 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20784 @item ^-s^/SHORT^
20785 Short format of the report file (no version information, no list of applied
20786 rules, no list of checked sources is included)
20787
20788 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
20789 @item ^-s1^/COMPILER_STYLE^
20790 Include the compiler-style section in the report file
20791
20792 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
20793 @item ^-s2^/BY_RULES^
20794 Include the section containing diagnostics ordered by rules in the report file
20795
20796 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
20797 @item ^-s3^/BY_FILES_BY_RULES^
20798 Include the section containing diagnostics ordered by files and then by rules
20799 in the report file
20800
20801 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
20802 @item ^-t^/TIME^
20803 Print out execution time.
20804
20805 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20806 @item ^-v^/VERBOSE^
20807 Verbose mode; @command{gnatcheck} generates version information and then
20808 a trace of sources being processed.
20809
20810 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
20811 @item ^-o ^/OUTPUT=^@var{report_file}
20812 Set name of report file file to @var{report_file} .
20813
20814 @end table
20815
20816 @noindent
20817 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20818 @option{^-s2^/BY_RULES^} or
20819 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20820 then the  @command{gnatcheck} report file will only contain sections
20821 explicitly denoted by these options.
20822
20823 @node gnatcheck Rule Options
20824 @section @command{gnatcheck} Rule Options
20825
20826 @noindent
20827 The following options control the processing performed by
20828 @command{gnatcheck}.
20829
20830 @table @option
20831 @cindex @option{+ALL} (@command{gnatcheck})
20832 @item +ALL
20833 Turn all the rule checks ON.
20834
20835 @cindex @option{-ALL} (@command{gnatcheck})
20836 @item -ALL
20837 Turn all the rule checks OFF.
20838
20839 @cindex @option{+R} (@command{gnatcheck})
20840 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20841 Turn on the check for a specified rule with the specified parameter, if any.
20842 @var{rule_id} must be the identifier of one of the currently implemented rules
20843 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20844 are not case-sensitive. The @var{param} item must
20845 be a string representing a valid parameter(s) for the specified rule.
20846 If it contains any space characters then this string must be enclosed in
20847 quotation marks.
20848
20849 @cindex @option{-R} (@command{gnatcheck})
20850 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20851 Turn off the check for a specified rule with the specified parameter, if any.
20852
20853 @cindex @option{-from} (@command{gnatcheck})
20854 @item -from=@var{rule_option_filename}
20855 Read the rule options from the text file @var{rule_option_filename}, referred as
20856 ``rule file'' below.
20857
20858 @end table
20859
20860 @noindent
20861 The default behavior is that all the rule checks are disabled.
20862
20863 A rule file is a text file containing a set of rule options.
20864 @cindex Rule file (for @code{gnatcheck})
20865 The file may contain empty lines and Ada-style comments (comment
20866 lines and end-of-line comments). The rule file has free format; that is,
20867 you do not have to start a new rule option on a new line.
20868
20869 A rule file may contain other @option{-from=@var{rule_option_filename}}
20870 options, each such option being replaced with the content of the
20871 corresponding rule file during the rule files processing. In case a
20872 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20873 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20874 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20875 the processing of rule files is interrupted and a part of their content
20876 is ignored.
20877
20878
20879 @node Adding the Results of Compiler Checks to gnatcheck Output
20880 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20881
20882 @noindent
20883 The @command{gnatcheck} tool can include in the generated diagnostic messages
20884 and in
20885 the report file the results of the checks performed by the compiler. Though
20886 disabled by default, this effect may be obtained by using @option{+R} with
20887 the following rule identifiers and parameters:
20888
20889 @table @option
20890 @item Restrictions
20891 To record restrictions violations (which are performed by the compiler if the
20892 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20893 use the @code{Restrictions} rule
20894 with the same parameters as pragma
20895 @code{Restrictions} or @code{Restriction_Warnings}.
20896
20897 @item Style_Checks
20898 To record compiler style checks (@pxref{Style Checking}), use the
20899 @code{Style_Checks} rule.
20900 This rule takes a parameter in one of the following forms:
20901 @itemize
20902 @item
20903 @code{All_Checks},
20904 which enables the standard style checks corresponding to the @option{-gnatyy}
20905 GNAT style check option, or
20906
20907 @item
20908 a string with the same
20909 structure and semantics as the @code{string_LITERAL} parameter of the
20910 GNAT pragma @code{Style_Checks}
20911 (for further information about this pragma,
20912 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
20913 @end itemize
20914
20915 @noindent
20916 For example, the
20917 @code{+RStyle_Checks:O} rule option activates
20918 the compiler style check that corresponds to
20919 @code{-gnatyO} style check option.
20920
20921 @item Warnings
20922 To record compiler warnings (@pxref{Warning Message Control}), use the
20923 @code{Warnings} rule with a parameter that is a valid
20924 @i{static_string_expression} argument of the GNAT pragma @code{Warnings}
20925 (for further information about this pragma,
20926 @pxref{Pragma Warnings,,,gnat_rm, GNAT Reference Manual}).
20927 Note that in case of gnatcheck
20928 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20929 all the specific warnings, but not suppresses the warning mode,
20930 and 'e' parameter, corresponding to @option{-gnatwe} that means
20931 "treat warnings as errors", does not have any effect.
20932
20933 @end table
20934
20935 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20936 option with the corresponding restriction name as a parameter. @code{-R} is
20937 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20938 warnings and style checks, use the corresponding warning and style options.
20939
20940 @node Project-Wide Checks
20941 @section Project-Wide Checks
20942 @cindex Project-wide checks (for @command{gnatcheck})
20943
20944 @noindent
20945 In order to perform checks on all units of a given project, you can use
20946 the GNAT driver along with the @option{-P} option:
20947 @smallexample
20948    gnat check -Pproj -rules -from=my_rules
20949 @end smallexample
20950
20951 @noindent
20952 If the project @code{proj} depends upon other projects, you can perform
20953 checks on the project closure using the @option{-U} option:
20954 @smallexample
20955    gnat check -Pproj -U -rules -from=my_rules
20956 @end smallexample
20957
20958 @noindent
20959 Finally, if not all the units are relevant to a particular main
20960 program in the project closure, you can perform checks for the set
20961 of units needed to create a given main program (unit closure) using
20962 the @option{-U} option followed by the name of the main unit:
20963 @smallexample
20964    gnat check -Pproj -U main -rules -from=my_rules
20965 @end smallexample
20966
20967
20968 @node Rule exemption
20969 @section Rule exemption
20970 @cindex Rule exemption (for @command{gnatcheck})
20971
20972 @noindent
20973 One of the most useful applications of @command{gnatcheck} is to
20974 automate the enforcement of project-specific coding standards,
20975 for example in safety-critical systems where particular features
20976 must be restricted in order to simplify the certification effort.
20977 However, it may sometimes be appropriate to violate a coding standard rule,
20978 and in such cases the rationale for the violation should be provided
20979 in the source program itself so that the individuals
20980 reviewing or maintaining the program can immediately understand the intent.
20981
20982 The @command{gnatcheck} tool supports this practice with the notion of
20983 a ``rule exemption'' covering a specific source code section. Normally
20984 rule violation messages are issued both on @file{stderr}
20985 and in a report file. In contrast, exempted violations are not listed on
20986 @file{stderr}; thus users invoking @command{gnatcheck} interactively
20987 (e.g. in its GPS interface) do not need to pay attention to known and
20988 justified violations. However, exempted violations along with their
20989 justification are documented in a special section of the report file that
20990 @command{gnatcheck} generates.
20991
20992 @menu
20993 * Using pragma Annotate to Control Rule Exemption::
20994 * gnatcheck Annotations Rules::
20995 @end menu
20996
20997 @node Using pragma Annotate to Control Rule Exemption
20998 @subsection Using pragma @code{Annotate} to Control Rule Exemption
20999 @cindex Using pragma Annotate to control rule exemption
21000
21001 @noindent
21002 Rule exemption is controlled by pragma @code{Annotate} when its first
21003 argument is ``gnatcheck''. The syntax of @command{gnatcheck}'s
21004 exemption control annotations is as follows:
21005
21006 @smallexample @c ada
21007 @group
21008 pragma Annotate (gnatcheck, @i{exemption_control}, @i{Rule_Name}, [@i{justification}]);
21009
21010 @i{exemption_control} ::= "Exempt_On" | "Exempt_Off"
21011
21012 @i{Rule_Name}         ::= string_literal
21013
21014 @i{justification}     ::= string_literal
21015 @end group
21016 @end smallexample
21017
21018 @noindent
21019 When a @command{gnatcheck} annotation has more then four arguments,
21020 @command{gnatcheck} issues a warning and ignores the additional arguments.
21021 If the additional arguments do not follow the syntax above,
21022 @command{gnatcheck} emits a warning and ignores the annotation.
21023
21024 The @i{@code{Rule_Name}} argument should be the name of some existing
21025 @command{gnatcheck} rule.
21026 Otherwise a warning message is generated and the pragma is
21027 ignored. If @code{Rule_Name} denotes a rule that is not activated by the given
21028 @command{gnatcheck} call, the pragma is ignored and no warning is issued.
21029
21030 A source code section where an exemption is active for a given rule is
21031 delimited by an @code{exempt_on} and @code{exempt_off} annotation pair:
21032
21033 @smallexample @c ada
21034 pragma Annotate (gnatcheck, "Exempt_On", Rule_Name, "justification");
21035 -- source code section
21036 pragma Annotate (gnatcheck, "Exempt_Off", Rule_Name);
21037 @end smallexample
21038
21039
21040 @node gnatcheck Annotations Rules
21041 @subsection @command{gnatcheck} Annotations Rules
21042 @cindex @command{gnatcheck} annotations rules
21043
21044 @itemize @bullet
21045
21046 @item
21047 An ``Exempt_Off'' annotation can only appear after a corresponding
21048 ``Exempt_On'' annotation.
21049
21050 @item
21051 Exempted source code sections are only based on the source location of the
21052 annotations. Any source construct between the two
21053 annotations is part of the exempted source code section.
21054
21055 @item
21056 Exempted source code sections for different rules are independent. They can
21057 be nested or intersect with one another without limitation.
21058 Creating nested or intersecting source code sections for the same rule is
21059 not allowed.
21060
21061 @item
21062 Malformed exempted source code sections are reported by a warning, and
21063 the corresponding rule exemptions are ignored.
21064
21065 @item
21066 When an exempted source code section does not contain at least one violation
21067 of the exempted rule, a warning is emitted on @file{stderr}.
21068
21069 @item
21070 If an ``Exempt_On'' annotation pragma does not have a matching
21071 ``Exempt_Off'' annotation pragma in the same compilation unit, then the
21072 exemption for the given rule is ignored and a warning is issued.
21073 @end itemize
21074
21075
21076 @node Predefined Rules
21077 @section Predefined Rules
21078 @cindex Predefined rules (for @command{gnatcheck})
21079
21080 @ignore
21081 @c (Jan 2007) Since the global rules are still under development and are not
21082 @c documented, there is no point in explaining the difference between
21083 @c global and local rules
21084 @noindent
21085 A rule in @command{gnatcheck} is either local or global.
21086 A @emph{local rule} is a rule that applies to a well-defined section
21087 of a program and that can be checked by analyzing only this section.
21088 A @emph{global rule} requires analysis of some global properties of the
21089 whole program (mostly related to the program call graph).
21090 As of @value{NOW}, the implementation of global rules should be
21091 considered to be at a preliminary stage. You can use the
21092 @option{+GLOBAL} option to enable all the global rules, and the
21093 @option{-GLOBAL} rule option to disable all the global rules.
21094
21095 All the global rules in the list below are
21096 so indicated by marking them ``GLOBAL''.
21097 This +GLOBAL and -GLOBAL options are not
21098 included in the list of gnatcheck options above, because at the moment they
21099 are considered as a temporary debug options.
21100
21101 @command{gnatcheck} performs rule checks for generic
21102 instances only for global rules.  This limitation may be relaxed in a later
21103 release.
21104 @end ignore
21105
21106 @noindent
21107 The following subsections document the rules implemented in
21108 @command{gnatcheck}.
21109 The subsection title is the same as the rule identifier, which may be
21110 used as a parameter of the @option{+R} or @option{-R} options.
21111
21112
21113 @menu
21114 * Abstract_Type_Declarations::
21115 * Anonymous_Arrays::
21116 * Anonymous_Subtypes::
21117 * Blocks::
21118 * Boolean_Relational_Operators::
21119 @ignore
21120 * Ceiling_Violations::
21121 @end ignore
21122 * Complex_Inlined_Subprograms::
21123 * Controlled_Type_Declarations::
21124 * Declarations_In_Blocks::
21125 * Deep_Inheritance_Hierarchies::
21126 * Deeply_Nested_Generics::
21127 * Deeply_Nested_Inlining::
21128 @ignore
21129 * Deeply_Nested_Local_Inlining::
21130 @end ignore
21131 * Default_Parameters::
21132 * Direct_Calls_To_Primitives::
21133 * Discriminated_Records::
21134 * Enumeration_Ranges_In_CASE_Statements::
21135 * Exceptions_As_Control_Flow::
21136 * Exits_From_Conditional_Loops::
21137 * EXIT_Statements_With_No_Loop_Name::
21138 * Expanded_Loop_Exit_Names::
21139 * Explicit_Full_Discrete_Ranges::
21140 * Float_Equality_Checks::
21141 * Forbidden_Attributes::
21142 * Forbidden_Pragmas::
21143 * Function_Style_Procedures::
21144 * Generics_In_Subprograms::
21145 * GOTO_Statements::
21146 * Implicit_IN_Mode_Parameters::
21147 * Implicit_SMALL_For_Fixed_Point_Types::
21148 * Improperly_Located_Instantiations::
21149 * Improper_Returns::
21150 * Library_Level_Subprograms::
21151 * Local_Packages::
21152 @ignore
21153 * Improperly_Called_Protected_Entries::
21154 @end ignore
21155 * Metrics::
21156 * Misnamed_Controlling_Parameters::
21157 * Misnamed_Identifiers::
21158 * Multiple_Entries_In_Protected_Definitions::
21159 * Name_Clashes::
21160 * Non_Qualified_Aggregates::
21161 * Non_Short_Circuit_Operators::
21162 * Non_SPARK_Attributes::
21163 * Non_Tagged_Derived_Types::
21164 * Non_Visible_Exceptions::
21165 * Numeric_Literals::
21166 * OTHERS_In_Aggregates::
21167 * OTHERS_In_CASE_Statements::
21168 * OTHERS_In_Exception_Handlers::
21169 * Outer_Loop_Exits::
21170 * Overloaded_Operators::
21171 * Overly_Nested_Control_Structures::
21172 * Parameters_Out_Of_Order::
21173 * Positional_Actuals_For_Defaulted_Generic_Parameters::
21174 * Positional_Actuals_For_Defaulted_Parameters::
21175 * Positional_Components::
21176 * Positional_Generic_Parameters::
21177 * Positional_Parameters::
21178 * Predefined_Numeric_Types::
21179 * Raising_External_Exceptions::
21180 * Raising_Predefined_Exceptions::
21181 * Separate_Numeric_Error_Handlers::
21182 @ignore
21183 * Recursion::
21184 * Side_Effect_Functions::
21185 @end ignore
21186 * Slices::
21187 * Too_Many_Parents::
21188 * Unassigned_OUT_Parameters::
21189 * Uncommented_BEGIN_In_Package_Bodies::
21190 * Unconditional_Exits::
21191 * Unconstrained_Array_Returns::
21192 * Universal_Ranges::
21193 * Unnamed_Blocks_And_Loops::
21194 @ignore
21195 * Unused_Subprograms::
21196 @end ignore
21197 * USE_PACKAGE_Clauses::
21198 * Visible_Components::
21199 * Volatile_Objects_Without_Address_Clauses::
21200 @end menu
21201
21202
21203 @node Abstract_Type_Declarations
21204 @subsection @code{Abstract_Type_Declarations}
21205 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
21206
21207 @noindent
21208 Flag all declarations of abstract types. For an abstract private
21209 type, both the private and full type declarations are flagged.
21210
21211 This rule has no parameters.
21212
21213
21214 @node Anonymous_Arrays
21215 @subsection @code{Anonymous_Arrays}
21216 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
21217
21218 @noindent
21219 Flag all anonymous array type definitions (by Ada semantics these can only
21220 occur in object declarations).
21221
21222 This rule has no parameters.
21223
21224 @node Anonymous_Subtypes
21225 @subsection @code{Anonymous_Subtypes}
21226 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
21227
21228 @noindent
21229 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
21230 any instance of a subtype indication with a constraint, other than one
21231 that occurs immediately within a subtype declaration. Any use of a range
21232 other than as a constraint used immediately within a subtype declaration
21233 is considered as an anonymous subtype.
21234
21235 An effect of this rule is that @code{for} loops such as the following are
21236 flagged (since @code{1..N} is formally a ``range''):
21237
21238 @smallexample @c ada
21239 for I in 1 .. N loop
21240    @dots{}
21241 end loop;
21242 @end smallexample
21243
21244 @noindent
21245 Declaring an explicit subtype solves the problem:
21246
21247 @smallexample @c ada
21248 subtype S is Integer range 1..N;
21249 @dots{}
21250 for I in S loop
21251    @dots{}
21252 end loop;
21253 @end smallexample
21254
21255 @noindent
21256 This rule has no parameters.
21257
21258 @node Blocks
21259 @subsection @code{Blocks}
21260 @cindex @code{Blocks} rule (for @command{gnatcheck})
21261
21262 @noindent
21263 Flag each block statement.
21264
21265 This rule has no parameters.
21266
21267 @node Boolean_Relational_Operators
21268 @subsection @code{Boolean_Relational_Operators}
21269 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
21270
21271 @noindent
21272 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
21273 ``>='', ``='' and ``/='') for the predefined Boolean type.
21274 (This rule is useful in enforcing the SPARK language restrictions.)
21275
21276 Calls to predefined relational operators of any type derived from
21277 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
21278 with these designators, and uses of operators that are renamings
21279 of the predefined relational operators for @code{Standard.Boolean},
21280 are likewise not detected.
21281
21282 This rule has no parameters.
21283
21284 @ignore
21285 @node Ceiling_Violations
21286 @subsection @code{Ceiling5_Violations} (under construction, GLOBAL)
21287 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
21288
21289 @noindent
21290 Flag invocations of a protected operation by a task whose priority exceeds
21291 the protected object's ceiling.
21292
21293 As of @value{NOW}, this rule has the following limitations:
21294
21295 @itemize @bullet
21296
21297 @item
21298  We consider only pragmas Priority and Interrupt_Priority as means to define
21299   a task/protected operation priority. We do not consider the effect of using
21300   Ada.Dynamic_Priorities.Set_Priority procedure;
21301
21302 @item
21303  We consider only base task priorities, and no priority inheritance. That is,
21304   we do not make a difference between calls issued during task activation and
21305   execution of the sequence of statements from task body;
21306
21307 @item
21308  Any situation when the priority of protected operation caller is set by a
21309   dynamic expression (that is, the corresponding Priority or
21310   Interrupt_Priority pragma has a non-static expression as an argument) we
21311   treat as a priority inconsistency (and, therefore, detect this situation).
21312 @end itemize
21313
21314 @noindent
21315 At the moment the notion of the main subprogram is not implemented in
21316 gnatcheck, so any pragma Priority in a library level subprogram body (in case
21317 if this subprogram can be a main subprogram of a partition) changes the
21318 priority of an environment task. So if we have more then one such pragma in
21319 the set of processed sources, the pragma that is processed last, defines the
21320 priority of an environment task.
21321
21322 This rule has no parameters.
21323 @end ignore
21324
21325 @node Controlled_Type_Declarations
21326 @subsection @code{Controlled_Type_Declarations}
21327 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
21328
21329 @noindent
21330 Flag all declarations of controlled types. A declaration of a private type
21331 is flagged if its full declaration declares a controlled type. A declaration
21332 of a derived type is flagged if its ancestor type is controlled. Subtype
21333 declarations are not checked. A declaration of a type that itself is not a
21334 descendant of a type declared in @code{Ada.Finalization} but has a controlled
21335 component is not checked.
21336
21337 This rule has no parameters.
21338
21339
21340 @node Complex_Inlined_Subprograms
21341 @subsection @code{Complex_Inlined_Subprograms}
21342 @cindex @code{Complex_Inlined_Subprograms} rule (for @command{gnatcheck})
21343
21344 @noindent
21345 Flags a subprogram (or generic subprogram) if
21346 pragma Inline is applied to the subprogram and at least one of the following
21347 conditions is met:
21348
21349 @itemize @bullet
21350 @item
21351 it contains at least one complex declaration such as a subprogram body,
21352 package, task, protected declaration, or a generic instantiation
21353 (except instantiation of @code{Ada.Unchecked_Conversion});
21354
21355 @item
21356 it contains at least one complex statement such as a loop, a case
21357 or a if statement, or a short circuit control form;
21358
21359 @item
21360 the number of statements exceeds
21361 a value specified by the @option{N} rule parameter;
21362 @end itemize
21363
21364 @noindent
21365 This rule has the following (mandatory) parameter for the @option{+R} option:
21366
21367 @table @emph
21368 @item N
21369 Positive integer specifying the maximum allowed total number of statements
21370 in the subprogram body.
21371 @end table
21372
21373
21374 @node Declarations_In_Blocks
21375 @subsection @code{Declarations_In_Blocks}
21376 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
21377
21378 @noindent
21379 Flag all block statements containing local declarations. A @code{declare}
21380 block with an empty @i{declarative_part} or with a @i{declarative part}
21381 containing only pragmas and/or @code{use} clauses is not flagged.
21382
21383 This rule has no parameters.
21384
21385
21386 @node Deep_Inheritance_Hierarchies
21387 @subsection @code{Deep_Inheritance_Hierarchies}
21388 @cindex @code{Deep_Inheritance_Hierarchies} rule (for @command{gnatcheck})
21389
21390 @noindent
21391 Flags a tagged derived type declaration or an interface type declaration if
21392 its depth (in its inheritance
21393 hierarchy) exceeds the value specified by the @option{N} rule parameter.
21394
21395 The inheritance depth of a tagged type or interface type is defined as 0 for
21396 a type  with no parent and no progenitor, and otherwise as 1 + max of the
21397 depths of the immediate parent and immediate progenitors.
21398
21399 This rule does not flag private extension
21400 declarations. In the case of a private extension, the corresponding full
21401 declaration is checked.
21402
21403 This rule has the following (mandatory) parameter for the @option{+R} option:
21404
21405 @table @emph
21406 @item N
21407 Integer not less than -1 specifying the maximal allowed depth of any inheritance
21408 hierarchy. If the rule parameter is set to -1, the rule flags all the declarations
21409 of tagged and interface types.
21410 @end table
21411
21412
21413 @node Deeply_Nested_Generics
21414 @subsection @code{Deeply_Nested_Generics}
21415 @cindex @code{Deeply_Nested_Generics} rule (for @command{gnatcheck})
21416
21417 @noindent
21418 Flags a generic declaration nested in another generic declaration if
21419 the nesting level of the inner generic exceeds
21420 a value specified by the @option{N} rule parameter.
21421 The nesting level is the number of generic declaratons that enclose the given
21422 (generic) declaration. Formal packages are not flagged by this rule.
21423
21424 This rule has the following (mandatory) parameters for the @option{+R} option:
21425
21426 @table @emph
21427 @item N
21428 Positive integer specifying the maximal allowed nesting level
21429 for a generic declaration.
21430 @end table
21431
21432 @node Deeply_Nested_Inlining
21433 @subsection @code{Deeply_Nested_Inlining}
21434 @cindex @code{Deeply_Nested_Inlining} rule (for @command{gnatcheck})
21435
21436 @noindent
21437 Flags a subprogram (or generic subprogram) if
21438 pragma Inline has been applied to the subprogram but the subprogram
21439 calls to another inlined subprogram that results in nested inlining
21440 with nesting depth exceeding the value specified by the
21441 @option{N} rule parameter.
21442
21443 This rule requires the global analysis of all the compilation units that
21444 are @command{gnatcheck} arguments; such analysis may affect the tool's
21445 performance.
21446
21447 This rule has the following (mandatory) parameter for the @option{+R} option:
21448
21449 @table @emph
21450 @item N
21451 Positive integer specifying the maximal allowed level of nested inlining.
21452 @end table
21453
21454
21455 @ignore
21456 @node Deeply_Nested_Local_Inlining
21457 @subsection @code{Deeply_Nested_Local_Inlining}
21458 @cindex @code{Deeply_Nested_Local_Inlining} rule (for @command{gnatcheck})
21459
21460 @noindent
21461 Flags a subprogram body if a pragma @code{Inline} is applied to the
21462 corresponding subprogram (or generic subprogram) and the body contains a call
21463 to another inlined subprogram that results in nested inlining with nesting
21464 depth more then a value specified by the @option{N} rule parameter.
21465 This rule is similar to @code{Deeply_Nested_Inlining} rule, but it
21466 assumes that calls to subprograms in
21467 with'ed units are not inlided, so all the analysis of the depth of inlining is
21468 limited by the compilation unit where the subprogram body is located and the
21469 units it depends semantically upon. Such analysis may be usefull for the case
21470 when neiter @option{-gnatn} nor @option{-gnatN} option is used when building
21471 the executable.
21472
21473 This rule has the following (mandatory) parameters for the @option{+R} option:
21474
21475 @table @emph
21476 @item N
21477 Positive integer specifying the maximal allowed level of nested inlining.
21478 @end table
21479
21480 @end ignore
21481
21482 @node Default_Parameters
21483 @subsection @code{Default_Parameters}
21484 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
21485
21486 @noindent
21487 Flag all default expressions for subprogram parameters. Parameter
21488 declarations of formal and generic subprograms are also checked.
21489
21490 This rule has no parameters.
21491
21492
21493 @node Direct_Calls_To_Primitives
21494 @subsection @code{Direct_Calls_To_Primitives}
21495 @cindex @code{Direct_Calls_To_Primitives} rule (for @command{gnatcheck})
21496
21497 @noindent
21498 Flags any non-dispatching call to a dispatching primitive operation, except
21499 for the common idiom where a primitive subprogram for a tagged type
21500 directly calls the same primitive subprogram of the type's immediate ancestor.
21501
21502 This rule has no parameters.
21503
21504
21505 @node Discriminated_Records
21506 @subsection @code{Discriminated_Records}
21507 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
21508
21509 @noindent
21510 Flag all declarations of record types with discriminants. Only the
21511 declarations of record and record extension types are checked. Incomplete,
21512 formal, private, derived and private extension type declarations are not
21513 checked. Task and protected type declarations also are not checked.
21514
21515 This rule has no parameters.
21516
21517
21518 @node Enumeration_Ranges_In_CASE_Statements
21519 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
21520 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
21521
21522 @noindent
21523 Flag each use of a range of enumeration literals as a choice in a
21524 @code{case} statement.
21525 All forms for specifying a range (explicit ranges
21526 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
21527 An enumeration range is
21528 flagged even if contains exactly one enumeration value or no values at all. A
21529 type derived from an enumeration type is considered as an enumeration type.
21530
21531 This rule helps prevent maintenance problems arising from adding an
21532 enumeration value to a type and having it implicitly handled by an existing
21533 @code{case} statement with an enumeration range that includes the new literal.
21534
21535 This rule has no parameters.
21536
21537
21538 @node Exceptions_As_Control_Flow
21539 @subsection @code{Exceptions_As_Control_Flow}
21540 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
21541
21542 @noindent
21543 Flag each place where an exception is explicitly raised and handled in the
21544 same subprogram body. A @code{raise} statement in an exception handler,
21545 package body, task body or entry body is not flagged.
21546
21547 The rule has no parameters.
21548
21549 @node Exits_From_Conditional_Loops
21550 @subsection @code{Exits_From_Conditional_Loops}
21551 @cindex @code{Exits_From_Conditional_Loops} (for @command{gnatcheck})
21552
21553 @noindent
21554 Flag any exit statement if it transfers the control out of a @code{for} loop
21555 or a @code{while} loop. This includes cases when the @code{exit} statement
21556 applies to a @code{FOR} or @code{while} loop, and cases when it is enclosed
21557 in some @code{for} or @code{while} loop, but transfers the control from some
21558 outer (inconditional) @code{loop} statement.
21559
21560 The rule has no parameters.
21561
21562
21563 @node EXIT_Statements_With_No_Loop_Name
21564 @subsection @code{EXIT_Statements_With_No_Loop_Name}
21565 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
21566
21567 @noindent
21568 Flag each @code{exit} statement that does not specify the name of the loop
21569 being exited.
21570
21571 The rule has no parameters.
21572
21573
21574 @node Expanded_Loop_Exit_Names
21575 @subsection @code{Expanded_Loop_Exit_Names}
21576 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
21577
21578 @noindent
21579 Flag all expanded loop names in @code{exit} statements.
21580
21581 This rule has no parameters.
21582
21583 @node Explicit_Full_Discrete_Ranges
21584 @subsection @code{Explicit_Full_Discrete_Ranges}
21585 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
21586
21587 @noindent
21588 Flag each discrete range that has the form @code{A'First .. A'Last}.
21589
21590 This rule has no parameters.
21591
21592 @node Float_Equality_Checks
21593 @subsection @code{Float_Equality_Checks}
21594 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
21595
21596 @noindent
21597 Flag all calls to the predefined equality operations for floating-point types.
21598 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
21599 User-defined equality operations are not flagged, nor are ``@code{=}''
21600 and ``@code{/=}'' operations for fixed-point types.
21601
21602 This rule has no parameters.
21603
21604
21605 @node Forbidden_Attributes
21606 @subsection @code{Forbidden_Attributes}
21607 @cindex @code{Forbidden_Attributes} rule (for @command{gnatcheck})
21608
21609 @noindent
21610 Flag each use of the specified attributes. The attributes to be detected are
21611 named in the rule's parameters.
21612
21613 This rule has the following parameters:
21614
21615 @itemize @bullet
21616 @item For the @option{+R} option
21617
21618 @table @asis
21619 @item @emph{Attribute_Designator}
21620 Adds the specified attribute to the set of attributes to be detected and sets
21621 the detection checks for all the specified attributes ON.
21622 If @emph{Attribute_Designator}
21623 does not denote any attribute defined in the Ada standard
21624 or in
21625 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
21626 Manual}, it is treated as the name of unknown attribute.
21627
21628 @item @code{GNAT}
21629 All the GNAT-specific attributes are detected; this sets
21630 the detection checks for all the specified attributes ON.
21631
21632 @item @code{ALL}
21633 All attributes are detected; this sets the rule ON.
21634 @end table
21635
21636 @item For the @option{-R} option
21637 @table @asis
21638 @item @emph{Attribute_Designator}
21639 Removes the specified attribute from the set of attributes to be
21640 detected without affecting detection checks for
21641 other attributes. If @emph{Attribute_Designator} does not correspond to any
21642 attribute defined in the Ada standard or in
21643 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference Manual},
21644 this option is treated as turning OFF detection of all unknown attributes.
21645
21646 @item GNAT
21647 Turn OFF detection of all GNAT-specific attributes
21648
21649 @item ALL
21650 Clear the list of the attributes to be detected and
21651 turn the rule OFF.
21652 @end table
21653 @end itemize
21654
21655 @noindent
21656 Parameters are not case sensitive. If @emph{Attribute_Designator} does not
21657 have the syntax of an Ada identifier and therefore can not be considered as a
21658 (part of an) attribute designator, a diagnostic message is generated and the
21659 corresponding parameter is ignored. (If an attribute allows a static
21660 expression to be a part of the attribute designator, this expression is
21661 ignored by this rule.)
21662
21663 When more then one parameter is given in the same rule option, the parameters
21664 must be separated by commas.
21665
21666 If more then one option for this rule is specified for the gnatcheck call, a
21667 new option overrides the previous one(s).
21668
21669 The @option{+R} option with no parameters turns the rule ON, with the set of
21670 attributes to be detected defined by the previous rule options.
21671 (By default this set is empty, so if the only option specified for the rule is
21672 @option{+RForbidden_Attributes} (with
21673 no parameter), then the rule is enabled, but it does not detect anything).
21674 The @option{-R} option with no parameter turns the rule OFF, but it does not
21675 affect the set of attributes to be detected.
21676
21677
21678 @node Forbidden_Pragmas
21679 @subsection @code{Forbidden_Pragmas}
21680 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
21681
21682 @noindent
21683 Flag each use of the specified pragmas.  The pragmas to be detected
21684 are named in the rule's  parameters.
21685
21686 This rule has the following parameters:
21687
21688 @itemize @bullet
21689 @item For the @option{+R} option
21690
21691 @table @asis
21692 @item @emph{Pragma_Name}
21693 Adds the specified pragma to the set of pragmas to be
21694 checked and sets the checks for all the specified pragmas
21695 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
21696 does not correspond to any pragma name defined in the Ada
21697 standard or to the name of a GNAT-specific pragma defined
21698 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21699 Manual}, it is treated as the name of unknown pragma.
21700
21701 @item @code{GNAT}
21702 All the GNAT-specific pragmas are detected; this sets
21703 the checks for all the specified pragmas ON.
21704
21705 @item @code{ALL}
21706 All pragmas are detected; this sets the rule ON.
21707 @end table
21708
21709 @item For the @option{-R} option
21710 @table @asis
21711 @item @emph{Pragma_Name}
21712 Removes the specified pragma from the set of pragmas to be
21713 checked without affecting checks for
21714 other pragmas. @emph{Pragma_Name} is treated as a name
21715 of a pragma. If it does not correspond to any pragma
21716 defined in the Ada standard or to any name defined in
21717 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21718 this option is treated as turning OFF detection of all unknown pragmas.
21719
21720 @item GNAT
21721 Turn OFF detection of all GNAT-specific pragmas
21722
21723 @item ALL
21724 Clear the list of the pragmas to be detected and
21725 turn the rule OFF.
21726 @end table
21727 @end itemize
21728
21729 @noindent
21730 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
21731 the syntax of an Ada identifier and therefore can not be considered
21732 as a pragma name, a diagnostic message is generated and the corresponding
21733 parameter is ignored.
21734
21735 When more then one parameter is given in the same rule option, the parameters
21736 must be separated by a comma.
21737
21738 If more then one option for this rule is specified for the @command{gnatcheck}
21739 call, a new option overrides the previous one(s).
21740
21741 The @option{+R} option with no parameters turns the rule ON with the set of
21742 pragmas to be detected defined by the previous rule options.
21743 (By default this set is empty, so if the only option specified for the rule is
21744 @option{+RForbidden_Pragmas} (with
21745 no parameter), then the rule is enabled, but it does not detect anything).
21746 The @option{-R} option with no parameter turns the rule OFF, but it does not
21747 affect the set of pragmas to be detected.
21748
21749
21750
21751
21752 @node Function_Style_Procedures
21753 @subsection @code{Function_Style_Procedures}
21754 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
21755
21756 @noindent
21757 Flag each procedure that can be rewritten as a function. A procedure can be
21758 converted into a function if it has exactly one parameter of mode @code{out}
21759 and no parameters of mode @code{in out}. Procedure declarations,
21760 formal procedure declarations, and generic procedure declarations are always
21761 checked. Procedure
21762 bodies and body stubs are flagged only if they do not have corresponding
21763 separate declarations. Procedure renamings and procedure instantiations are
21764 not flagged.
21765
21766 If a procedure can be rewritten as a function, but its @code{out} parameter is
21767 of a limited type, it is not flagged.
21768
21769 Protected procedures are not flagged. Null procedures also are not flagged.
21770
21771 This rule has no parameters.
21772
21773
21774 @node Generics_In_Subprograms
21775 @subsection @code{Generics_In_Subprograms}
21776 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21777
21778 @noindent
21779 Flag each declaration of a generic unit in a subprogram. Generic
21780 declarations in the bodies of generic subprograms are also flagged.
21781 A generic unit nested in another generic unit is not flagged.
21782 If a generic unit is
21783 declared in a local package that is declared in a subprogram body, the
21784 generic unit is flagged.
21785
21786 This rule has no parameters.
21787
21788
21789 @node GOTO_Statements
21790 @subsection @code{GOTO_Statements}
21791 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21792
21793 @noindent
21794 Flag each occurrence of a @code{goto} statement.
21795
21796 This rule has no parameters.
21797
21798
21799 @node Implicit_IN_Mode_Parameters
21800 @subsection @code{Implicit_IN_Mode_Parameters}
21801 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21802
21803 @noindent
21804 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21805 Note that @code{access} parameters, although they technically behave
21806 like @code{in} parameters, are not flagged.
21807
21808 This rule has no parameters.
21809
21810
21811 @node Implicit_SMALL_For_Fixed_Point_Types
21812 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21813 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21814
21815 @noindent
21816 Flag each fixed point type declaration that lacks an explicit
21817 representation  clause to define its @code{'Small} value.
21818 Since @code{'Small} can be  defined only for ordinary fixed point types,
21819 decimal fixed point type declarations are not checked.
21820
21821 This rule has no parameters.
21822
21823
21824 @node Improperly_Located_Instantiations
21825 @subsection @code{Improperly_Located_Instantiations}
21826 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21827
21828 @noindent
21829 Flag all generic instantiations in library-level package specs
21830 (including library generic packages) and in all subprogram bodies.
21831
21832 Instantiations in task and entry bodies are not flagged. Instantiations in the
21833 bodies of protected subprograms are flagged.
21834
21835 This rule has no parameters.
21836
21837
21838
21839 @node Improper_Returns
21840 @subsection @code{Improper_Returns}
21841 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21842
21843 @noindent
21844 Flag each explicit @code{return} statement in procedures, and
21845 multiple @code{return} statements in functions.
21846 Diagnostic messages are generated for all @code{return} statements
21847 in a procedure (thus each procedure must be written so that it
21848 returns implicitly at the end of its statement part),
21849 and for all @code{return} statements in a function after the first one.
21850 This rule supports the stylistic convention that each subprogram
21851 should have no more than one point of normal return.
21852
21853 This rule has no parameters.
21854
21855
21856 @node Library_Level_Subprograms
21857 @subsection @code{Library_Level_Subprograms}
21858 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21859
21860 @noindent
21861 Flag all library-level subprograms (including generic subprogram instantiations).
21862
21863 This rule has no parameters.
21864
21865
21866 @node Local_Packages
21867 @subsection @code{Local_Packages}
21868 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21869
21870 @noindent
21871 Flag all local packages declared in package and generic package
21872 specs.
21873 Local packages in bodies are not flagged.
21874
21875 This rule has no parameters.
21876
21877 @ignore
21878 @node Improperly_Called_Protected_Entries
21879 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21880 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21881
21882 @noindent
21883 Flag each protected entry that can be called from more than one task.
21884
21885 This rule has no parameters.
21886 @end ignore
21887
21888 @node Metrics
21889 @subsection @code{Metrics}
21890 @cindex @code{Metrics} rule (for @command{gnatcheck})
21891
21892 @noindent
21893 There is a set of checks based on computing a metric value and comparing the
21894 result with the specified upper (or lower, depending on a specific metric)
21895 value specified for a given metric. A construct is flagged if a given metric
21896 is applicable (can be computed) for it and the computed value is greater
21897 then (lover then) the specified upper (lower) bound.
21898
21899 The name of any metric-based rule consists of the prefix @code{Metrics_}
21900 followed by the name of the corresponding metric (see the table below).
21901 For @option{+R} option, each metric-based rule has a numeric parameter
21902 specifying the bound (integer or real, depending on a metric), @option{-R}
21903 option for metric rules does not have a parameter.
21904
21905 The following table shows the metric names for that the corresponding
21906 metrics-based checks are supported by gnatcheck, including the
21907 constraint that must be satisfied by the bound that is specified for the check
21908 and what bound - upper (U) or lower (L) - should be specified.
21909
21910 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21911 @ifnothtml
21912 @headitem Check Name @tab Description @tab Bounds Value
21913 @end ifnothtml
21914 @ifhtml
21915 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21916 @end ifhtml
21917 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21918 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21919 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21920 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21921 @end multitable
21922
21923 @noindent
21924 The meaning and the computed values for all these metrics are exactly
21925 the same as for the corresponding metrics in @command{gnatmetric}.
21926
21927 @emph{Example:} the rule
21928 @smallexample
21929 +RMetrics_Cyclomatic_Complexity : 7
21930 @end smallexample
21931 @noindent
21932 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21933
21934 To turn OFF the check for cyclomatic complexity metric, use the following option:
21935 @smallexample
21936 -RMetrics_Cyclomatic_Complexity
21937 @end smallexample
21938
21939
21940 @node Misnamed_Controlling_Parameters
21941 @subsection @code{Misnamed_Controlling_Parameters}
21942 @cindex @code{Misnamed_Controlling_Parameters} rule (for @command{gnatcheck})
21943
21944 @noindent
21945 Flags a declaration of a dispatching operation, if the first parameter is
21946 not a controlling one and its name is not @code{This} (the check for
21947 parameter name is not case-sensitive). Declarations of dispatching functions
21948 with controlling result and no controlling parameter are never flagged.
21949
21950 A subprogram body declaration, subprogram renaming declaration or subprogram
21951 body stub is flagged only if it is not a completion of a prior subprogram
21952 declaration.
21953
21954 This rule has no parameters.
21955
21956
21957
21958 @node Misnamed_Identifiers
21959 @subsection @code{Misnamed_Identifiers}
21960 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21961
21962 @noindent
21963 Flag the declaration of each identifier that does not have a suffix
21964 corresponding to the kind of entity being declared.
21965 The following declarations are checked:
21966
21967 @itemize @bullet
21968 @item
21969 type declarations
21970
21971 @item
21972 subtype declarations
21973
21974 @item
21975 constant declarations (but not number declarations)
21976
21977 @item
21978 package renaming declarations (but not generic package renaming
21979 declarations)
21980 @end itemize
21981
21982 @noindent
21983 This rule may have parameters. When used without parameters, the rule enforces
21984 the following checks:
21985
21986 @itemize @bullet
21987 @item
21988 type-defining names end with @code{_T}, unless the type is an access type,
21989 in which case the suffix must be @code{_A}
21990 @item
21991 constant names end with @code{_C}
21992 @item
21993 names defining package renamings end with @code{_R}
21994 @end itemize
21995
21996 @noindent
21997 Defining identifiers from incomplete type declarations are never flagged.
21998
21999 For a private type declaration (including private extensions), the defining
22000 identifier from the private type declaration is checked against the type
22001 suffix (even if the corresponding full declaration is an access type
22002 declaration), and the defining identifier from the corresponding full type
22003 declaration is not checked.
22004
22005 @noindent
22006 For a deferred constant, the defining name in the corresponding full constant
22007 declaration is not checked.
22008
22009 Defining names of formal types are not checked.
22010
22011 The rule may have the following parameters:
22012
22013 @itemize @bullet
22014 @item
22015 For the @option{+R} option:
22016 @table @code
22017 @item Default
22018 Sets the default listed above for all the names to be checked.
22019
22020 @item Type_Suffix=@emph{string}
22021 Specifies the suffix for a type name.
22022
22023 @item Access_Suffix=@emph{string}
22024 Specifies the suffix for an access type name. If
22025 this parameter is set, it overrides for access
22026 types the suffix set by the @code{Type_Suffix} parameter.
22027 For access types, @emph{string} may have the following format:
22028 @emph{suffix1(suffix2)}. That means that an access type name
22029 should have the @emph{suffix1} suffix except for the case when
22030 the designated type is also an access type, in this case the
22031 type name should have the @emph{suffix1 & suffix2} suffix.
22032
22033 @item Class_Access_Suffix=@emph{string}
22034 Specifies the suffix for the name of an access type that points to some class-wide
22035 type. If this parameter is set, it overrides for such access
22036 types the suffix set by the @code{Type_Suffix} or @code{Access_Suffix}
22037 parameter.
22038
22039 @item Class_Subtype_Suffix=@emph{string}
22040 Specifies the suffix for the name of a subtype that denotes a class-wide type.
22041
22042 @item Constant_Suffix=@emph{string}
22043 Specifies the suffix for a constant name.
22044
22045 @item Renaming_Suffix=@emph{string}
22046 Specifies the suffix for a package renaming name.
22047 @end table
22048
22049 @item
22050 For the @option{-R} option:
22051 @table @code
22052 @item All_Suffixes
22053 Remove all the suffixes specified for the
22054 identifier suffix checks, whether by default or
22055 as specified by other rule parameters. All the
22056 checks for this rule are disabled as a result.
22057
22058 @item Type_Suffix
22059 Removes the suffix specified for types. This
22060 disables checks for types but does not disable
22061 any other checks for this rule (including the
22062 check for access type names if @code{Access_Suffix} is
22063 set).
22064
22065 @item Access_Suffix
22066 Removes the suffix specified for access types.
22067 This disables checks for access type names but
22068 does not disable any other checks for this rule.
22069 If @code{Type_Suffix} is set, access type names are
22070 checked as ordinary type names.
22071
22072 @item Class_Access_Suffix
22073 Removes the suffix specified for access types pointing to class-wide
22074 type. This disables specific checks for names of access types pointing to
22075 class-wide types but does not disable any other checks for this rule.
22076 If @code{Type_Suffix} is set, access type names are
22077 checked as ordinary type names. If @code{Access_Suffix} is set, these
22078 access types are checked as any other access type name.
22079
22080 @item Class_Subtype_Suffix=@emph{string}
22081 Removes the suffix specified for subtype names.
22082 This disables checks for subtype names but
22083 does not disable any other checks for this rule.
22084
22085 @item Constant_Suffix
22086 Removes the suffix specified for constants. This
22087 disables checks for constant names but does not
22088 disable any other checks for this rule.
22089
22090 @item Renaming_Suffix
22091 Removes the suffix specified for package
22092 renamings. This disables checks for package
22093 renamings but does not disable any other checks
22094 for this rule.
22095 @end table
22096 @end itemize
22097
22098 @noindent
22099 If more than one parameter is used, parameters must be separated by commas.
22100
22101 If more than one  option is specified for the @command{gnatcheck} invocation,
22102 a new option overrides the previous one(s).
22103
22104 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
22105 checks for all the
22106 name suffixes specified by previous options used for this rule.
22107
22108 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
22109 all the checks but keeps
22110 all the suffixes specified by previous options used for this rule.
22111
22112 The @emph{string} value must be a valid suffix for an Ada identifier (after
22113 trimming all the leading and trailing space characters, if any).
22114 Parameters are not case sensitive, except the @emph{string} part.
22115
22116 If any error is detected in a rule parameter, the parameter is ignored.
22117 In such a case the options that are set for the rule are not
22118 specified.
22119
22120
22121
22122 @node Multiple_Entries_In_Protected_Definitions
22123 @subsection @code{Multiple_Entries_In_Protected_Definitions}
22124 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
22125
22126 @noindent
22127 Flag each protected definition (i.e., each protected object/type declaration)
22128 that defines more than one entry.
22129 Diagnostic messages are generated for all the entry declarations
22130 except the first one. An entry family is counted as one entry. Entries from
22131 the private part of the protected definition are also checked.
22132
22133 This rule has no parameters.
22134
22135 @node Name_Clashes
22136 @subsection @code{Name_Clashes}
22137 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
22138
22139 @noindent
22140 Check that certain names are not used as defining identifiers. To activate
22141 this rule, you need to supply a reference to the dictionary file(s) as a rule
22142 parameter(s) (more then one dictionary file can be specified). If no
22143 dictionary file is set, this rule will not cause anything to be flagged.
22144 Only defining occurrences, not references, are checked.
22145 The check is not case-sensitive.
22146
22147 This rule is enabled by default, but without setting any corresponding
22148 dictionary file(s); thus the default effect is to do no checks.
22149
22150 A dictionary file is a plain text file. The maximum line length for this file
22151 is 1024 characters.  If the line is longer then this limit, extra characters
22152 are ignored.
22153
22154 Each line can be either an empty line, a comment line, or a line containing
22155 a list of identifiers separated by space or HT characters.
22156 A comment is an Ada-style comment (from @code{--} to end-of-line).
22157 Identifiers must follow the Ada syntax for identifiers.
22158 A line containing one or more identifiers may end with a comment.
22159
22160 @node Non_Qualified_Aggregates
22161 @subsection @code{Non_Qualified_Aggregates}
22162 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
22163
22164 @noindent
22165 Flag each non-qualified aggregate.
22166 A non-qualified aggregate is an
22167 aggregate that is not the expression of a qualified expression. A
22168 string literal is not considered an aggregate, but an array
22169 aggregate of a string type is considered as a normal aggregate.
22170 Aggregates of anonymous array types are not flagged.
22171
22172 This rule has no parameters.
22173
22174
22175 @node Non_Short_Circuit_Operators
22176 @subsection @code{Non_Short_Circuit_Operators}
22177 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
22178
22179 @noindent
22180 Flag all calls to predefined @code{and} and @code{or} operators for
22181 any boolean type. Calls to
22182 user-defined @code{and} and @code{or} and to operators defined by renaming
22183 declarations are not flagged. Calls to predefined @code{and} and @code{or}
22184 operators for modular types or boolean array types are not flagged.
22185
22186 This rule has no parameters.
22187
22188
22189
22190 @node Non_SPARK_Attributes
22191 @subsection @code{Non_SPARK_Attributes}
22192 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
22193
22194 @noindent
22195 The SPARK language defines the following subset of Ada 95 attribute
22196 designators as those that can be used in SPARK programs. The use of
22197 any other attribute is flagged.
22198
22199 @itemize @bullet
22200 @item @code{'Adjacent}
22201 @item @code{'Aft}
22202 @item @code{'Base}
22203 @item @code{'Ceiling}
22204 @item @code{'Component_Size}
22205 @item @code{'Compose}
22206 @item @code{'Copy_Sign}
22207 @item @code{'Delta}
22208 @item @code{'Denorm}
22209 @item @code{'Digits}
22210 @item @code{'Exponent}
22211 @item @code{'First}
22212 @item @code{'Floor}
22213 @item @code{'Fore}
22214 @item @code{'Fraction}
22215 @item @code{'Last}
22216 @item @code{'Leading_Part}
22217 @item @code{'Length}
22218 @item @code{'Machine}
22219 @item @code{'Machine_Emax}
22220 @item @code{'Machine_Emin}
22221 @item @code{'Machine_Mantissa}
22222 @item @code{'Machine_Overflows}
22223 @item @code{'Machine_Radix}
22224 @item @code{'Machine_Rounds}
22225 @item @code{'Max}
22226 @item @code{'Min}
22227 @item @code{'Model}
22228 @item @code{'Model_Emin}
22229 @item @code{'Model_Epsilon}
22230 @item @code{'Model_Mantissa}
22231 @item @code{'Model_Small}
22232 @item @code{'Modulus}
22233 @item @code{'Pos}
22234 @item @code{'Pred}
22235 @item @code{'Range}
22236 @item @code{'Remainder}
22237 @item @code{'Rounding}
22238 @item @code{'Safe_First}
22239 @item @code{'Safe_Last}
22240 @item @code{'Scaling}
22241 @item @code{'Signed_Zeros}
22242 @item @code{'Size}
22243 @item @code{'Small}
22244 @item @code{'Succ}
22245 @item @code{'Truncation}
22246 @item @code{'Unbiased_Rounding}
22247 @item @code{'Val}
22248 @item @code{'Valid}
22249 @end itemize
22250
22251 @noindent
22252 This rule has no parameters.
22253
22254
22255 @node Non_Tagged_Derived_Types
22256 @subsection @code{Non_Tagged_Derived_Types}
22257 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
22258
22259 @noindent
22260 Flag all derived type declarations that do not have a record extension part.
22261
22262 This rule has no parameters.
22263
22264
22265
22266 @node Non_Visible_Exceptions
22267 @subsection @code{Non_Visible_Exceptions}
22268 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
22269
22270 @noindent
22271 Flag constructs leading to the possibility of propagating an exception
22272 out of the scope in which the exception is declared.
22273 Two cases are detected:
22274
22275 @itemize @bullet
22276 @item
22277 An exception declaration in a subprogram body, task body or block
22278 statement is flagged if the body or statement does not contain a handler for
22279 that exception or a handler with an @code{others} choice.
22280
22281 @item
22282 A @code{raise} statement in an exception handler of a subprogram body,
22283 task body or block statement is flagged if it (re)raises a locally
22284 declared exception.  This may occur under the following circumstances:
22285 @itemize @minus
22286 @item
22287 it explicitly raises a locally declared exception, or
22288 @item
22289 it does not specify an exception name (i.e., it is simply @code{raise;})
22290 and the enclosing handler contains a locally declared exception in its
22291 exception choices.
22292 @end itemize
22293 @end itemize
22294
22295 @noindent
22296 Renamings of local exceptions are not flagged.
22297
22298 This rule has no parameters.
22299
22300
22301 @node Numeric_Literals
22302 @subsection @code{Numeric_Literals}
22303 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
22304
22305 @noindent
22306 Flag each use of a numeric literal in an index expression, and in any
22307 circumstance except for the following:
22308
22309 @itemize @bullet
22310 @item
22311 a literal occurring in the initialization expression for a constant
22312 declaration or a named number declaration, or
22313
22314 @item
22315 an integer literal that is less than or equal to a value
22316 specified by the @option{N} rule parameter.
22317 @end itemize
22318
22319 @noindent
22320 This rule may have the following parameters for the @option{+R} option:
22321
22322 @table @asis
22323 @item @emph{N}
22324 @emph{N} is an integer literal used as the maximal value that is not flagged
22325 (i.e., integer literals not exceeding this value are allowed)
22326
22327 @item @code{ALL}
22328 All integer literals are flagged
22329 @end table
22330
22331 @noindent
22332 If no parameters are set, the maximum unflagged value is 1.
22333
22334 The last specified check limit (or the fact that there is no limit at
22335 all) is used when multiple @option{+R} options appear.
22336
22337 The @option{-R} option for this rule has no parameters.
22338 It disables the rule but retains the last specified maximum unflagged value.
22339 If the @option{+R} option subsequently appears, this value is used as the
22340 threshold for the check.
22341
22342
22343 @node OTHERS_In_Aggregates
22344 @subsection @code{OTHERS_In_Aggregates}
22345 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
22346
22347 @noindent
22348 Flag each use of an @code{others} choice in extension aggregates.
22349 In record and array aggregates, an @code{others} choice is flagged unless
22350 it is used to refer to all components, or to all but one component.
22351
22352 If, in case of a named array aggregate, there are two associations, one
22353 with an @code{others} choice and another with a discrete range, the
22354 @code{others} choice is flagged even if the discrete range specifies
22355 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
22356
22357 This rule has no parameters.
22358
22359 @node OTHERS_In_CASE_Statements
22360 @subsection @code{OTHERS_In_CASE_Statements}
22361 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
22362
22363 @noindent
22364 Flag any use of an @code{others} choice in a @code{case} statement.
22365
22366 This rule has no parameters.
22367
22368 @node OTHERS_In_Exception_Handlers
22369 @subsection @code{OTHERS_In_Exception_Handlers}
22370 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
22371
22372 @noindent
22373 Flag any use of an @code{others} choice in an exception handler.
22374
22375 This rule has no parameters.
22376
22377
22378 @node Outer_Loop_Exits
22379 @subsection @code{Outer_Loop_Exits}
22380 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
22381
22382 @noindent
22383 Flag each @code{exit} statement containing a loop name that is not the name
22384 of the immediately enclosing @code{loop} statement.
22385
22386 This rule has no parameters.
22387
22388
22389 @node Overloaded_Operators
22390 @subsection @code{Overloaded_Operators}
22391 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
22392
22393 @noindent
22394 Flag each function declaration that overloads an operator symbol.
22395 A function body is checked only if the body does not have a
22396 separate spec. Formal functions are also checked. For a
22397 renaming declaration, only renaming-as-declaration is checked
22398
22399 This rule has no parameters.
22400
22401
22402 @node Overly_Nested_Control_Structures
22403 @subsection @code{Overly_Nested_Control_Structures}
22404 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
22405
22406 @noindent
22407 Flag each control structure whose nesting level exceeds the value provided
22408 in the rule parameter.
22409
22410 The control structures checked are the following:
22411
22412 @itemize @bullet
22413 @item    @code{if} statement
22414 @item    @code{case} statement
22415 @item    @code{loop} statement
22416 @item    Selective accept statement
22417 @item    Timed entry call statement
22418 @item    Conditional entry call
22419 @item    Asynchronous select statement
22420 @end itemize
22421
22422 @noindent
22423 The rule has the following parameter for the @option{+R} option:
22424
22425 @table @emph
22426 @item N
22427 Positive integer specifying the maximal control structure nesting
22428 level that is not flagged
22429 @end table
22430
22431 @noindent
22432 If the parameter for the @option{+R} option is not specified or
22433 if it is not a positive integer, @option{+R} option is ignored.
22434
22435 If more then one  option is specified for the gnatcheck call, the later option and
22436 new parameter override the previous one(s).
22437
22438
22439 @node Parameters_Out_Of_Order
22440 @subsection @code{Parameters_Out_Of_Order}
22441 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
22442
22443 @noindent
22444 Flag each subprogram and entry declaration whose formal parameters are not
22445 ordered according to the following scheme:
22446
22447 @itemize @bullet
22448
22449 @item @code{in} and @code{access} parameters first,
22450 then @code{in out} parameters,
22451 and then @code{out} parameters;
22452
22453 @item for @code{in} mode, parameters with default initialization expressions
22454 occur last
22455 @end itemize
22456
22457 @noindent
22458 Only the first violation of the described order is flagged.
22459
22460 The following constructs are checked:
22461
22462 @itemize @bullet
22463 @item   subprogram declarations (including null procedures);
22464 @item   generic subprogram declarations;
22465 @item   formal subprogram declarations;
22466 @item   entry declarations;
22467 @item   subprogram bodies and subprogram body stubs that do not
22468 have separate specifications
22469 @end itemize
22470
22471 @noindent
22472 Subprogram renamings are not checked.
22473
22474 This rule has no parameters.
22475
22476
22477 @node Positional_Actuals_For_Defaulted_Generic_Parameters
22478 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
22479 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
22480
22481 @noindent
22482 Flag each generic actual parameter corresponding to a generic formal
22483 parameter with a default initialization, if positional notation is used.
22484
22485 This rule has no parameters.
22486
22487 @node Positional_Actuals_For_Defaulted_Parameters
22488 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
22489 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
22490
22491 @noindent
22492 Flag each actual parameter to a subprogram or entry call where the
22493 corresponding formal parameter has a default expression, if positional
22494 notation is used.
22495
22496 This rule has no parameters.
22497
22498 @node Positional_Components
22499 @subsection @code{Positional_Components}
22500 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
22501
22502 @noindent
22503 Flag each array, record and extension aggregate that includes positional
22504 notation.
22505
22506 This rule has no parameters.
22507
22508
22509 @node Positional_Generic_Parameters
22510 @subsection @code{Positional_Generic_Parameters}
22511 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
22512
22513 @noindent
22514 Flag each instantiation using positional parameter notation.
22515
22516 This rule has no parameters.
22517
22518
22519 @node Positional_Parameters
22520 @subsection @code{Positional_Parameters}
22521 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
22522
22523 @noindent
22524 Flag each subprogram or entry call using positional parameter notation,
22525 except for the following:
22526
22527 @itemize @bullet
22528 @item
22529 Invocations of prefix or infix operators are not flagged
22530 @item
22531 If the called subprogram or entry has only one formal parameter,
22532 the call is not flagged;
22533 @item
22534 If a subprogram call uses the @emph{Object.Operation} notation, then
22535 @itemize @minus
22536 @item
22537 the first parameter (that is, @emph{Object}) is not flagged;
22538 @item
22539 if the called subprogram has only two parameters, the second parameter
22540 of the call is not flagged;
22541 @end itemize
22542 @end itemize
22543
22544 @noindent
22545 This rule has no parameters.
22546
22547
22548
22549
22550 @node Predefined_Numeric_Types
22551 @subsection @code{Predefined_Numeric_Types}
22552 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
22553
22554 @noindent
22555 Flag each explicit use of the name of any numeric type or subtype defined
22556 in package @code{Standard}.
22557
22558 The rationale for this rule is to detect when the
22559 program may depend on platform-specific characteristics of the implementation
22560 of the predefined numeric types. Note that this rule is over-pessimistic;
22561 for example, a program that uses @code{String} indexing
22562 likely needs a variable of type @code{Integer}.
22563 Another example is the flagging of predefined numeric types with explicit
22564 constraints:
22565
22566 @smallexample @c ada
22567     subtype My_Integer is Integer range Left .. Right;
22568     Vy_Var : My_Integer;
22569 @end smallexample
22570
22571 @noindent
22572 This rule detects only numeric types and subtypes defined in
22573 @code{Standard}. The use of numeric types and subtypes defined in other
22574 predefined packages (such as @code{System.Any_Priority} or
22575 @code{Ada.Text_IO.Count}) is not flagged
22576
22577 This rule has no parameters.
22578
22579
22580
22581 @node Raising_External_Exceptions
22582 @subsection @code{Raising_External_Exceptions}
22583 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
22584
22585 @noindent
22586 Flag any @code{raise} statement, in a program unit declared in a library
22587 package or in a generic library package, for an exception that is
22588 neither a predefined exception nor an exception that is also declared (or
22589 renamed) in the visible part of the package.
22590
22591 This rule has no parameters.
22592
22593
22594
22595 @node Raising_Predefined_Exceptions
22596 @subsection @code{Raising_Predefined_Exceptions}
22597 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
22598
22599 @noindent
22600 Flag each @code{raise} statement that raises a predefined exception
22601 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
22602 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
22603
22604 This rule has no parameters.
22605
22606 @node Separate_Numeric_Error_Handlers
22607 @subsection @code{Separate_Numeric_Error_Handlers}
22608 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
22609
22610 @noindent
22611 Flags each exception handler that contains a choice for
22612 the predefined @code{Constraint_Error} exception, but does not contain
22613 the choice for the predefined @code{Numeric_Error} exception, or
22614 that contains the choice for @code{Numeric_Error}, but does not contain the
22615 choice for @code{Constraint_Error}.
22616
22617 This rule has no parameters.
22618
22619 @ignore
22620 @node Recursion
22621 @subsection @code{Recursion} (under construction, GLOBAL)
22622 @cindex @code{Recursion} rule (for @command{gnatcheck})
22623
22624 @noindent
22625 Flag recursive subprograms (cycles in the call graph). Declarations, and not
22626 calls, of recursive subprograms are detected.
22627
22628 This rule has no parameters.
22629 @end ignore
22630
22631 @ignore
22632 @node Side_Effect_Functions
22633 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
22634 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
22635
22636 @noindent
22637 Flag functions with side effects.
22638
22639 We define a side effect as changing any data object that is not local for the
22640 body of this function.
22641
22642 At the moment, we do NOT consider a side effect any input-output operations
22643 (changing a state or a content of any file).
22644
22645 We do not consider protected functions for this rule (???)
22646
22647 There are the following sources of side effect:
22648
22649 @enumerate
22650 @item Explicit (or direct) side-effect:
22651
22652 @itemize @bullet
22653 @item
22654 direct assignment to a non-local variable;
22655
22656 @item
22657 direct call to an entity that is known to change some data object that is
22658      not local for the body of this function (Note, that if F1 calls F2 and F2
22659      does have a side effect, this does not automatically mean that F1 also
22660      have a side effect, because it may be the case that F2 is declared in
22661      F1's body and it changes some data object that is global for F2, but
22662      local for F1);
22663 @end itemize
22664
22665 @item Indirect side-effect:
22666 @itemize @bullet
22667 @item
22668 Subprogram calls implicitly issued by:
22669 @itemize @bullet
22670 @item
22671 computing initialization expressions from type declarations as a part
22672          of object elaboration or allocator evaluation;
22673 @item
22674 computing implicit parameters of subprogram or entry calls or generic
22675          instantiations;
22676 @end itemize
22677
22678 @item
22679 activation of a task that change some non-local data object (directly or
22680      indirectly);
22681
22682 @item
22683 elaboration code of a package that is a result of a package instantiation;
22684
22685 @item
22686 controlled objects;
22687 @end itemize
22688
22689 @item Situations when we can suspect a side-effect, but the full static check
22690 is either impossible or too hard:
22691 @itemize @bullet
22692 @item
22693 assignment to access variables or to the objects pointed by access
22694      variables;
22695
22696 @item
22697 call to a subprogram pointed by access-to-subprogram value
22698
22699 @item
22700 dispatching calls;
22701 @end itemize
22702 @end enumerate
22703
22704 @noindent
22705 This rule has no parameters.
22706 @end ignore
22707
22708 @node Slices
22709 @subsection @code{Slices}
22710 @cindex @code{Slices} rule (for @command{gnatcheck})
22711
22712 @noindent
22713 Flag all uses of array slicing
22714
22715 This rule has no parameters.
22716
22717
22718 @node Too_Many_Parents
22719 @subsection @code{Too_Many_Parents}
22720 @cindex @code{Too_Many_Parents} rule (for @command{gnatcheck})
22721
22722 @noindent
22723 Flags any type declaration, single task declaration or single protected
22724 declaration that has more then  @option{N} parents,  @option{N} is a parameter
22725 of the rule.
22726 A parent here is either a (sub)type denoted by the subtype mark from the
22727 parent_subtype_indication (in case of a derived type declaration), or
22728 any of the progenitors from the interface list, if any.
22729
22730 This rule has the following (mandatory) parameters for the @option{+R} option:
22731
22732 @table @emph
22733 @item N
22734 Positive integer specifying the maximal allowed number of parents.
22735 @end table
22736
22737
22738 @node Unassigned_OUT_Parameters
22739 @subsection @code{Unassigned_OUT_Parameters}
22740 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
22741
22742 @noindent
22743 Flags procedures' @code{out} parameters that are not assigned, and
22744 identifies the contexts in which the assignments are missing.
22745
22746 An @code{out} parameter is flagged in the statements in the procedure
22747 body's handled sequence of statements (before the procedure body's
22748 @code{exception} part, if any) if this sequence of statements contains
22749 no assignments to the parameter.
22750
22751 An @code{out} parameter is flagged in an exception handler in the exception
22752 part of the procedure body's handled sequence of statements if the handler
22753 contains no assignment to the parameter.
22754
22755 Bodies of generic procedures are also considered.
22756
22757 The following are treated as assignments to an @code{out} parameter:
22758
22759 @itemize @bullet
22760 @item
22761 an assignment statement, with the parameter or some component as the target;
22762
22763 @item
22764 passing the parameter (or one of its components) as an @code{out} or
22765 @code{in out} parameter.
22766 @end itemize
22767
22768 @noindent
22769 This rule does not have any parameters.
22770
22771
22772
22773 @node Uncommented_BEGIN_In_Package_Bodies
22774 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
22775 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
22776
22777 @noindent
22778 Flags each package body with declarations and a statement part that does not
22779 include a trailing comment on the line containing the @code{begin} keyword;
22780 this trailing comment needs to specify the package name and nothing else.
22781 The @code{begin} is not flagged if the package body does not
22782 contain any declarations.
22783
22784 If the @code{begin} keyword is placed on the
22785 same line as the last declaration or the first statement, it is flagged
22786 independently of whether the line contains a trailing comment. The
22787 diagnostic message is attached to the line containing the first statement.
22788
22789 This rule has no parameters.
22790
22791 @node Unconditional_Exits
22792 @subsection @code{Unconditional_Exits}
22793 @cindex @code{Unconditional_Exits} rule (for @command{gnatcheck})
22794
22795 @noindent
22796 Flag unconditional @code{exit} statements.
22797
22798 This rule has no parameters.
22799
22800 @node Unconstrained_Array_Returns
22801 @subsection @code{Unconstrained_Array_Returns}
22802 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
22803
22804 @noindent
22805 Flag each function returning an unconstrained array. Function declarations,
22806 function bodies (and body stubs) having no separate specifications,
22807 and generic function instantiations are checked.
22808 Function calls and function renamings are
22809 not checked.
22810
22811 Generic function declarations, and function declarations in generic
22812 packages are not checked, instead this rule checks the results of
22813 generic instantiations (that is, expanded specification and expanded
22814 body corresponding to an instantiation).
22815
22816 This rule has no parameters.
22817
22818 @node Universal_Ranges
22819 @subsection @code{Universal_Ranges}
22820 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
22821
22822 @noindent
22823 Flag discrete ranges that are a part of an index constraint, constrained
22824 array definition, or @code{for}-loop parameter specification, and whose bounds
22825 are both of type @i{universal_integer}. Ranges that have at least one
22826 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
22827 or an expression of non-universal type) are not flagged.
22828
22829 This rule has no parameters.
22830
22831
22832 @node Unnamed_Blocks_And_Loops
22833 @subsection @code{Unnamed_Blocks_And_Loops}
22834 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
22835
22836 @noindent
22837 Flag each unnamed block statement and loop statement.
22838
22839 The rule has no parameters.
22840
22841
22842
22843 @ignore
22844 @node Unused_Subprograms
22845 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22846 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22847
22848 @noindent
22849 Flag all unused subprograms.
22850
22851 This rule has no parameters.
22852 @end ignore
22853
22854
22855
22856
22857 @node USE_PACKAGE_Clauses
22858 @subsection @code{USE_PACKAGE_Clauses}
22859 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22860
22861 @noindent
22862 Flag all @code{use} clauses for packages; @code{use type} clauses are
22863 not flagged.
22864
22865 This rule has no parameters.
22866
22867
22868 @node Visible_Components
22869 @subsection @code{Visible_Components}
22870 @cindex @code{Visible_Components} rule (for @command{gnatcheck})
22871
22872 @noindent
22873 Flags all the type declarations located in the visible part of a library
22874 package or a library generic package that can declare a visible component. A
22875 type is considered as declaring a visible component if it contains a record
22876 definition by its own or as a part of a record extension. Type declaration is
22877 flagged even if it contains a record definition that defines no components.
22878
22879 Declarations located in private parts of local (generic) packages are not
22880 flagged. Declarations in private packages are not flagged.
22881
22882 This rule has no parameters.
22883
22884
22885 @node Volatile_Objects_Without_Address_Clauses
22886 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22887 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22888
22889 @noindent
22890 Flag each volatile object that does not have an address clause.
22891
22892 The following check is made: if the pragma @code{Volatile} is applied to a
22893 data object or to its type, then an address clause must
22894 be supplied for this object.
22895
22896 This rule does not check the components of data objects,
22897 array components that are volatile as a result of the pragma
22898 @code{Volatile_Components}, or objects that are volatile because
22899 they are atomic as a result of pragmas @code{Atomic} or
22900 @code{Atomic_Components}.
22901
22902 Only variable declarations, and not constant declarations, are checked.
22903
22904 This rule has no parameters.
22905
22906
22907 @c *********************************
22908 @node Creating Sample Bodies Using gnatstub
22909 @chapter Creating Sample Bodies Using @command{gnatstub}
22910 @findex gnatstub
22911
22912 @noindent
22913 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
22914 for library unit declarations.
22915
22916 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
22917 driver (see @ref{The GNAT Driver and Project Files}).
22918
22919 To create a body stub, @command{gnatstub} has to compile the library
22920 unit declaration. Therefore, bodies can be created only for legal
22921 library units. Moreover, if a library unit depends semantically upon
22922 units located outside the current directory, you have to provide
22923 the source search path when calling @command{gnatstub}, see the description
22924 of @command{gnatstub} switches below.
22925
22926 By default, all the program unit body stubs generated by @code{gnatstub}
22927 raise the predefined @code{Program_Error} exception, which will catch
22928 accidental calls of generated stubs. This behavior can be changed with
22929 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
22930
22931 @menu
22932 * Running gnatstub::
22933 * Switches for gnatstub::
22934 @end menu
22935
22936 @node Running gnatstub
22937 @section Running @command{gnatstub}
22938
22939 @noindent
22940 @command{gnatstub} has the command-line interface of the form
22941
22942 @smallexample
22943 $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
22944 @end smallexample
22945
22946 @noindent
22947 where
22948 @table @var
22949 @item filename
22950 is the name of the source file that contains a library unit declaration
22951 for which a body must be created. The file name may contain the path
22952 information.
22953 The file name does not have to follow the GNAT file name conventions. If the
22954 name
22955 does not follow GNAT file naming conventions, the name of the body file must
22956 be provided
22957 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
22958 If the file name follows the GNAT file naming
22959 conventions and the name of the body file is not provided,
22960 @command{gnatstub}
22961 creates the name
22962 of the body file from the argument file name by replacing the @file{.ads}
22963 suffix
22964 with the @file{.adb} suffix.
22965
22966 @item directory
22967 indicates the directory in which the body stub is to be placed (the default
22968 is the
22969 current directory)
22970
22971 @item switches
22972 is an optional sequence of switches as described in the next section
22973 @end table
22974
22975 @node Switches for gnatstub
22976 @section Switches for @command{gnatstub}
22977
22978 @table @option
22979 @c !sort!
22980
22981 @item ^-f^/FULL^
22982 @cindex @option{^-f^/FULL^} (@command{gnatstub})
22983 If the destination directory already contains a file with the name of the
22984 body file
22985 for the argument spec file, replace it with the generated body stub.
22986
22987 @item ^-hs^/HEADER=SPEC^
22988 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
22989 Put the comment header (i.e., all the comments preceding the
22990 compilation unit) from the source of the library unit declaration
22991 into the body stub.
22992
22993 @item ^-hg^/HEADER=GENERAL^
22994 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
22995 Put a sample comment header into the body stub.
22996
22997 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
22998 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
22999 Use the content of the file as the comment header for a generated body stub.
23000
23001 @ifclear vms
23002 @item -IDIR
23003 @cindex @option{-IDIR} (@command{gnatstub})
23004 @itemx -I-
23005 @cindex @option{-I-} (@command{gnatstub})
23006 @end ifclear
23007 @ifset vms
23008 @item /NOCURRENT_DIRECTORY
23009 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
23010 @end ifset
23011 ^These switches have ^This switch has^ the same meaning as in calls to
23012 @command{gcc}.
23013 ^They define ^It defines ^ the source search path in the call to
23014 @command{gcc} issued
23015 by @command{gnatstub} to compile an argument source file.
23016
23017 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
23018 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
23019 This switch has the same meaning as in calls to @command{gcc}.
23020 It defines the additional configuration file to be passed to the call to
23021 @command{gcc} issued
23022 by @command{gnatstub} to compile an argument source file.
23023
23024 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
23025 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
23026 (@var{n} is a non-negative integer). Set the maximum line length in the
23027 body stub to @var{n}; the default is 79. The maximum value that can be
23028 specified is 32767. Note that in the special case of configuration
23029 pragma files, the maximum is always 32767 regardless of whether or
23030 not this switch appears.
23031
23032 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
23033 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
23034 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
23035 the generated body sample to @var{n}.
23036 The default indentation is 3.
23037
23038 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
23039 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
23040 Order local bodies alphabetically. (By default local bodies are ordered
23041 in the same way as the corresponding local specs in the argument spec file.)
23042
23043 @item ^-i^/INDENTATION=^@var{n}
23044 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
23045 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
23046
23047 @item ^-k^/TREE_FILE=SAVE^
23048 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
23049 Do not remove the tree file (i.e., the snapshot of the compiler internal
23050 structures used by @command{gnatstub}) after creating the body stub.
23051
23052 @item ^-l^/LINE_LENGTH=^@var{n}
23053 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
23054 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
23055
23056 @item ^--no-exception^/NO_EXCEPTION^
23057 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
23058 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
23059 This is not always possible for function stubs.
23060
23061 @item ^--no-local-header^/NO_LOCAL_HEADER^
23062 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
23063 Do not place local comment header with unit name before body stub for a
23064 unit.
23065
23066 @item ^-o ^/BODY=^@var{body-name}
23067 @cindex @option{^-o^/BODY^} (@command{gnatstub})
23068 Body file name.  This should be set if the argument file name does not
23069 follow
23070 the GNAT file naming
23071 conventions. If this switch is omitted the default name for the body will be
23072 obtained
23073 from the argument file name according to the GNAT file naming conventions.
23074
23075 @item ^-q^/QUIET^
23076 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
23077 Quiet mode: do not generate a confirmation when a body is
23078 successfully created, and do not generate a message when a body is not
23079 required for an
23080 argument unit.
23081
23082 @item ^-r^/TREE_FILE=REUSE^
23083 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
23084 Reuse the tree file (if it exists) instead of creating it.  Instead of
23085 creating the tree file for the library unit declaration, @command{gnatstub}
23086 tries to find it in the current directory and use it for creating
23087 a body. If the tree file is not found, no body is created. This option
23088 also implies @option{^-k^/SAVE^}, whether or not
23089 the latter is set explicitly.
23090
23091 @item ^-t^/TREE_FILE=OVERWRITE^
23092 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
23093 Overwrite the existing tree file.  If the current directory already
23094 contains the file which, according to the GNAT file naming rules should
23095 be considered as a tree file for the argument source file,
23096 @command{gnatstub}
23097 will refuse to create the tree file needed to create a sample body
23098 unless this option is set.
23099
23100 @item ^-v^/VERBOSE^
23101 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
23102 Verbose mode: generate version information.
23103
23104 @end table
23105
23106 @c *********************************
23107 @node Generating Ada Bindings for C and C++ headers
23108 @chapter Generating Ada Bindings for C and C++ headers
23109 @findex binding
23110
23111 @noindent
23112 GNAT now comes with a new experimental binding generator for C and C++
23113 headers which is intended to do 95% of the tedious work of generating
23114 Ada specs from C or C++ header files. Note that this still is a work in
23115 progress, not designed to generate 100% correct Ada specs.
23116
23117 The code generated is using the Ada 2005 syntax, which makes it
23118 easier to interface with other languages than previous versions of Ada.
23119
23120 @menu
23121 * Running the binding generator::
23122 * Generating bindings for C++ headers::
23123 * Switches::
23124 @end menu
23125
23126 @node Running the binding generator
23127 @section Running the binding generator
23128
23129 @noindent
23130 The binding generator is part of the @command{gcc} compiler and can be
23131 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
23132 spec files for the header files specified on the command line, and all
23133 header files needed by these files transitivitely. For example:
23134
23135 @smallexample
23136 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
23137 $ gcc -c -gnat05 *.ads
23138 @end smallexample
23139
23140 will generate, under GNU/Linux, the following files: @file{time_h.ads},
23141 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
23142 correspond to the files @file{/usr/include/time.h},
23143 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
23144 mode these Ada specs.
23145
23146 The @code{-C} switch tells @command{gcc} to extract comments from headers,
23147 and will attempt to generate corresponding Ada comments.
23148
23149 If you want to generate a single Ada file and not the transitive closure, you
23150 can use instead the @option{-fdump-ada-spec-slim} switch.
23151
23152 Note that we recommend when possible to use the @command{g++} driver to
23153 generate bindings, even for most C headers, since this will in general
23154 generate better Ada specs. For generating bindings for C++ headers, it is
23155 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
23156 is equivalent in this case. If @command{g++} cannot work on your C headers
23157 because of incompatibilities between C and C++, then you can fallback to
23158 @command{gcc} instead.
23159
23160 For an example of better bindings generated from the C++ front-end,
23161 the name of the parameters (when available) are actually ignored by the C
23162 front-end. Consider the following C header:
23163
23164 @smallexample
23165 extern void foo (int variable);
23166 @end smallexample
23167
23168 with the C front-end, @code{variable} is ignored, and the above is handled as:
23169
23170 @smallexample
23171 extern void foo (int);
23172 @end smallexample
23173
23174 generating a generic:
23175
23176 @smallexample
23177 procedure foo (param1 : int);
23178 @end smallexample
23179
23180 with the C++ front-end, the name is available, and we generate:
23181
23182 @smallexample
23183 procedure foo (variable : int);
23184 @end smallexample
23185
23186 In some cases, the generated bindings will be more complete or more meaningful
23187 when defining some macros, which you can do via the @option{-D} switch. This
23188 is for example the case with @file{Xlib.h} under GNU/Linux:
23189
23190 @smallexample
23191 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
23192 @end smallexample
23193
23194 The above will generate more complete bindings than a straight call without
23195 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
23196
23197 In other cases, it is not possible to parse a header file in a stand alone
23198 manner, because other include files need to be included first. In this
23199 case, the solution is to create a small header file including the needed
23200 @code{#include} and possible @code{#define} directives. For example, to
23201 generate Ada bindings for @file{readline/readline.h}, you need to first
23202 include @file{stdio.h}, so you can create a file with the following two
23203 lines in e.g. @file{readline1.h}:
23204
23205 @smallexample
23206 #include <stdio.h>
23207 #include <readline/readline.h>
23208 @end smallexample
23209
23210 and then generate Ada bindings from this file:
23211
23212 @smallexample
23213 $ g++ -c -fdump-ada-spec readline1.h
23214 @end smallexample
23215
23216 @node Generating bindings for C++ headers
23217 @section Generating bindings for C++ headers
23218
23219 @noindent
23220 Generating bindings for C++ headers is done using the same options, always
23221 with the @command{g++} compiler.
23222
23223 In this mode, C++ classes will be mapped to Ada tagged types, constructors
23224 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
23225 multiple inheritance of abstract classes will be mapped to Ada interfaces
23226 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
23227 information on interfacing to C++).
23228
23229 For example, given the following C++ header file:
23230
23231 @smallexample
23232 @group
23233 @cartouche
23234 class Carnivore @{
23235 public:
23236    virtual int Number_Of_Teeth () = 0;
23237 @};
23238
23239 class Domestic @{
23240 public:
23241    virtual void Set_Owner (char* Name) = 0;
23242 @};
23243
23244 class Animal @{
23245 public:
23246   int Age_Count;
23247   virtual void Set_Age (int New_Age);
23248 @};
23249
23250 class Dog : Animal, Carnivore, Domestic @{
23251  public:
23252   int  Tooth_Count;
23253   char *Owner;
23254
23255   virtual int  Number_Of_Teeth ();
23256   virtual void Set_Owner (char* Name);
23257
23258   Dog();
23259 @};
23260 @end cartouche
23261 @end group
23262 @end smallexample
23263
23264 The corresponding Ada code is generated:
23265
23266 @smallexample @c ada
23267 @group
23268 @cartouche
23269   package Class_Carnivore is
23270     type Carnivore is limited interface;
23271     pragma Import (CPP, Carnivore);
23272
23273     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
23274   end;
23275   use Class_Carnivore;
23276
23277   package Class_Domestic is
23278     type Domestic is limited interface;
23279     pragma Import (CPP, Domestic);
23280
23281     procedure Set_Owner
23282       (this : access Domestic;
23283        Name : Interfaces.C.Strings.chars_ptr) is abstract;
23284   end;
23285   use Class_Domestic;
23286
23287   package Class_Animal is
23288     type Animal is tagged limited record
23289       Age_Count : aliased int;
23290     end record;
23291     pragma Import (CPP, Animal);
23292
23293     procedure Set_Age (this : access Animal; New_Age : int);
23294     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
23295   end;
23296   use Class_Animal;
23297
23298   package Class_Dog is
23299     type Dog is new Animal and Carnivore and Domestic with record
23300       Tooth_Count : aliased int;
23301       Owner : Interfaces.C.Strings.chars_ptr;
23302     end record;
23303     pragma Import (CPP, Dog);
23304
23305     function Number_Of_Teeth (this : access Dog) return int;
23306     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
23307
23308     procedure Set_Owner
23309       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
23310     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
23311
23312     function New_Dog return Dog;
23313     pragma CPP_Constructor (New_Dog);
23314     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
23315   end;
23316   use Class_Dog;
23317 @end cartouche
23318 @end group
23319 @end smallexample
23320
23321 @node Switches
23322 @section Switches
23323
23324 @table @option
23325 @item -fdump-ada-spec
23326 @cindex @option{-fdump-ada-spec} (@command{gcc})
23327 Generate Ada spec files for the given header files transitively (including
23328 all header files that these headers depend upon).
23329
23330 @item -fdump-ada-spec-slim
23331 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
23332 Generate Ada spec files for the header files specified on the command line
23333 only.
23334
23335 @item -C
23336 @cindex @option{-C} (@command{gcc})
23337 Extract comments from headers and generate Ada comments in the Ada spec files.
23338 @end table
23339
23340 @node Other Utility Programs
23341 @chapter Other Utility Programs
23342
23343 @noindent
23344 This chapter discusses some other utility programs available in the Ada
23345 environment.
23346
23347 @menu
23348 * Using Other Utility Programs with GNAT::
23349 * The External Symbol Naming Scheme of GNAT::
23350 * Converting Ada Files to html with gnathtml::
23351 * Installing gnathtml::
23352 @ifset vms
23353 * LSE::
23354 * Profiling::
23355 @end ifset
23356 @end menu
23357
23358 @node Using Other Utility Programs with GNAT
23359 @section Using Other Utility Programs with GNAT
23360
23361 @noindent
23362 The object files generated by GNAT are in standard system format and in
23363 particular the debugging information uses this format. This means
23364 programs generated by GNAT can be used with existing utilities that
23365 depend on these formats.
23366
23367 @ifclear vms
23368 In general, any utility program that works with C will also often work with
23369 Ada programs generated by GNAT. This includes software utilities such as
23370 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
23371 as Purify.
23372 @end ifclear
23373
23374 @node The External Symbol Naming Scheme of GNAT
23375 @section The External Symbol Naming Scheme of GNAT
23376
23377 @noindent
23378 In order to interpret the output from GNAT, when using tools that are
23379 originally intended for use with other languages, it is useful to
23380 understand the conventions used to generate link names from the Ada
23381 entity names.
23382
23383 All link names are in all lowercase letters. With the exception of library
23384 procedure names, the mechanism used is simply to use the full expanded
23385 Ada name with dots replaced by double underscores. For example, suppose
23386 we have the following package spec:
23387
23388 @smallexample @c ada
23389 @group
23390 @cartouche
23391 package QRS is
23392    MN : Integer;
23393 end QRS;
23394 @end cartouche
23395 @end group
23396 @end smallexample
23397
23398 @noindent
23399 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
23400 the corresponding link name is @code{qrs__mn}.
23401 @findex Export
23402 Of course if a @code{pragma Export} is used this may be overridden:
23403
23404 @smallexample @c ada
23405 @group
23406 @cartouche
23407 package Exports is
23408    Var1 : Integer;
23409    pragma Export (Var1, C, External_Name => "var1_name");
23410    Var2 : Integer;
23411    pragma Export (Var2, C, Link_Name => "var2_link_name");
23412 end Exports;
23413 @end cartouche
23414 @end group
23415 @end smallexample
23416
23417 @noindent
23418 In this case, the link name for @var{Var1} is whatever link name the
23419 C compiler would assign for the C function @var{var1_name}. This typically
23420 would be either @var{var1_name} or @var{_var1_name}, depending on operating
23421 system conventions, but other possibilities exist. The link name for
23422 @var{Var2} is @var{var2_link_name}, and this is not operating system
23423 dependent.
23424
23425 @findex _main
23426 One exception occurs for library level procedures. A potential ambiguity
23427 arises between the required name @code{_main} for the C main program,
23428 and the name we would otherwise assign to an Ada library level procedure
23429 called @code{Main} (which might well not be the main program).
23430
23431 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
23432 names. So if we have a library level procedure such as
23433
23434 @smallexample @c ada
23435 @group
23436 @cartouche
23437 procedure Hello (S : String);
23438 @end cartouche
23439 @end group
23440 @end smallexample
23441
23442 @noindent
23443 the external name of this procedure will be @var{_ada_hello}.
23444
23445
23446 @node Converting Ada Files to html with gnathtml
23447 @section Converting Ada Files to HTML with @code{gnathtml}
23448
23449 @noindent
23450 This @code{Perl} script allows Ada source files to be browsed using
23451 standard Web browsers. For installation procedure, see the section
23452 @xref{Installing gnathtml}.
23453
23454 Ada reserved keywords are highlighted in a bold font and Ada comments in
23455 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
23456 switch to suppress the generation of cross-referencing information, user
23457 defined variables and types will appear in a different color; you will
23458 be able to click on any identifier and go to its declaration.
23459
23460 The command line is as follow:
23461 @smallexample
23462 $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
23463 @end smallexample
23464
23465 @noindent
23466 You can pass it as many Ada files as you want. @code{gnathtml} will generate
23467 an html file for every ada file, and a global file called @file{index.htm}.
23468 This file is an index of every identifier defined in the files.
23469
23470 The available ^switches^options^ are the following ones:
23471
23472 @table @option
23473 @item -83
23474 @cindex @option{-83} (@code{gnathtml})
23475 Only the Ada 83 subset of keywords will be highlighted.
23476
23477 @item -cc @var{color}
23478 @cindex @option{-cc} (@code{gnathtml})
23479 This option allows you to change the color used for comments. The default
23480 value is green. The color argument can be any name accepted by html.
23481
23482 @item -d
23483 @cindex @option{-d} (@code{gnathtml})
23484 If the Ada files depend on some other files (for instance through
23485 @code{with} clauses, the latter files will also be converted to html.
23486 Only the files in the user project will be converted to html, not the files
23487 in the run-time library itself.
23488
23489 @item -D
23490 @cindex @option{-D} (@code{gnathtml})
23491 This command is the same as @option{-d} above, but @command{gnathtml} will
23492 also look for files in the run-time library, and generate html files for them.
23493
23494 @item -ext @var{extension}
23495 @cindex @option{-ext} (@code{gnathtml})
23496 This option allows you to change the extension of the generated HTML files.
23497 If you do not specify an extension, it will default to @file{htm}.
23498
23499 @item -f
23500 @cindex @option{-f} (@code{gnathtml})
23501 By default, gnathtml will generate html links only for global entities
23502 ('with'ed units, global variables and types,@dots{}).  If you specify
23503 @option{-f} on the command line, then links will be generated for local
23504 entities too.
23505
23506 @item -l @var{number}
23507 @cindex @option{-l} (@code{gnathtml})
23508 If this ^switch^option^ is provided and @var{number} is not 0, then
23509 @code{gnathtml} will number the html files every @var{number} line.
23510
23511 @item -I @var{dir}
23512 @cindex @option{-I} (@code{gnathtml})
23513 Specify a directory to search for library files (@file{.ALI} files) and
23514 source files. You can provide several -I switches on the command line,
23515 and the directories will be parsed in the order of the command line.
23516
23517 @item -o @var{dir}
23518 @cindex @option{-o} (@code{gnathtml})
23519 Specify the output directory for html files. By default, gnathtml will
23520 saved the generated html files in a subdirectory named @file{html/}.
23521
23522 @item -p @var{file}
23523 @cindex @option{-p} (@code{gnathtml})
23524 If you are using Emacs and the most recent Emacs Ada mode, which provides
23525 a full Integrated Development Environment for compiling, checking,
23526 running and debugging applications, you may use @file{.gpr} files
23527 to give the directories where Emacs can find sources and object files.
23528
23529 Using this ^switch^option^, you can tell gnathtml to use these files.
23530 This allows you to get an html version of your application, even if it
23531 is spread over multiple directories.
23532
23533 @item -sc @var{color}
23534 @cindex @option{-sc} (@code{gnathtml})
23535 This ^switch^option^ allows you to change the color used for symbol
23536 definitions.
23537 The default value is red. The color argument can be any name accepted by html.
23538
23539 @item -t @var{file}
23540 @cindex @option{-t} (@code{gnathtml})
23541 This ^switch^option^ provides the name of a file. This file contains a list of
23542 file names to be converted, and the effect is exactly as though they had
23543 appeared explicitly on the command line. This
23544 is the recommended way to work around the command line length limit on some
23545 systems.
23546
23547 @end table
23548
23549 @node Installing gnathtml
23550 @section Installing @code{gnathtml}
23551
23552 @noindent
23553 @code{Perl} needs to be installed on your machine to run this script.
23554 @code{Perl} is freely available for almost every architecture and
23555 Operating System via the Internet.
23556
23557 On Unix systems, you  may want to modify  the  first line of  the script
23558 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
23559 is. The syntax of this line is:
23560 @smallexample
23561 #!full_path_name_to_perl
23562 @end smallexample
23563
23564 @noindent
23565 Alternatively, you may run the script using the following command line:
23566
23567 @smallexample
23568 $ perl gnathtml.pl @ovar{switches} @var{files}
23569 @end smallexample
23570
23571 @ifset vms
23572 @node LSE
23573 @section LSE
23574 @findex LSE
23575
23576 @noindent
23577 The GNAT distribution provides an Ada 95 template for the HP Language
23578 Sensitive Editor (LSE), a component of DECset. In order to
23579 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
23580
23581 @node Profiling
23582 @section Profiling
23583 @findex PCA
23584
23585 @noindent
23586 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
23587 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
23588 the collection phase with the /DEBUG qualifier.
23589
23590 @smallexample
23591 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
23592 $ DEFINE LIB$DEBUG PCA$COLLECTOR
23593 $ RUN/DEBUG <PROGRAM_NAME>
23594 @end smallexample
23595 @noindent
23596 @end ifset
23597
23598 @ifclear vms
23599 @c ******************************
23600 @node Code Coverage and Profiling
23601 @chapter Code Coverage and Profiling
23602 @cindex Code Coverage
23603 @cindex Profiling
23604
23605 @noindent
23606 This chapter describes how to use @code{gcov} - coverage testing tool - and
23607 @code{gprof} - profiler tool - on your Ada programs.
23608
23609 @menu
23610 * Code Coverage of Ada Programs using gcov::
23611 * Profiling an Ada Program using gprof::
23612 @end menu
23613
23614 @node Code Coverage of Ada Programs using gcov
23615 @section Code Coverage of Ada Programs using gcov
23616 @cindex gcov
23617 @cindex -fprofile-arcs
23618 @cindex -ftest-coverage
23619 @cindex -coverage
23620 @cindex Code Coverage
23621
23622 @noindent
23623 @code{gcov} is a test coverage program: it analyzes the execution of a given
23624 program on selected tests, to help you determine the portions of the program
23625 that are still untested.
23626
23627 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
23628 User's Guide. You can refer to this documentation for a more complete
23629 description.
23630
23631 This chapter provides a quick startup guide, and
23632 details some Gnat-specific features.
23633
23634 @menu
23635 * Quick startup guide::
23636 * Gnat specifics::
23637 @end menu
23638
23639 @node Quick startup guide
23640 @subsection Quick startup guide
23641
23642 In order to perform coverage analysis of a program using @code{gcov}, 3
23643 steps are needed:
23644
23645 @itemize @bullet
23646 @item
23647 Code instrumentation during the compilation process
23648 @item
23649 Execution of the instrumented program
23650 @item
23651 Execution of the @code{gcov} tool to generate the result.
23652 @end itemize
23653
23654 The code instrumentation needed by gcov is created at the object level:
23655 The source code is not modified in any way, because the instrumentation code is
23656 inserted by gcc during the compilation process. To compile your code with code
23657 coverage activated, you need to recompile your whole project using the
23658 switches
23659 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
23660 @code{-fprofile-arcs}.
23661
23662 @smallexample
23663 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
23664    -largs -fprofile-arcs
23665 @end smallexample
23666
23667 This compilation process will create @file{.gcno} files together with
23668 the usual object files.
23669
23670 Once the program is compiled with coverage instrumentation, you can
23671 run it as many times as needed - on portions of a test suite for
23672 example. The first execution will produce @file{.gcda} files at the
23673 same location as the @file{.gcno} files.  The following executions
23674 will update those files, so that a cumulative result of the covered
23675 portions of the program is generated.
23676
23677 Finally, you need to call the @code{gcov} tool. The different options of
23678 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
23679
23680 This will create annotated source files with a @file{.gcov} extension:
23681 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
23682
23683 @node Gnat specifics
23684 @subsection Gnat specifics
23685
23686 Because Ada semantics, portions of the source code may be shared among
23687 several object files. This is the case for example when generics are
23688 involved, when inlining is active  or when declarations generate  initialisation
23689 calls. In order to take
23690 into account this shared code, you need to call @code{gcov} on all
23691 source files of the tested program at once.
23692
23693 The list of source files might exceed the system's maximum command line
23694 length. In order to bypass this limitation, a new mechanism has been
23695 implemented in @code{gcov}: you can now list all your project's files into a
23696 text file, and provide this file to gcov as a parameter,  preceded by a @@
23697 (e.g. @samp{gcov @@mysrclist.txt}).
23698
23699 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
23700 not supported as there can be unresolved symbols during the final link.
23701
23702 @node Profiling an Ada Program using gprof
23703 @section Profiling an Ada Program using gprof
23704 @cindex gprof
23705 @cindex -pg
23706 @cindex Profiling
23707
23708 @noindent
23709 This section is not meant to be an exhaustive documentation of @code{gprof}.
23710 Full documentation for it can be found in the GNU Profiler User's Guide
23711 documentation that is part of this GNAT distribution.
23712
23713 Profiling a program helps determine the parts of a program that are executed
23714 most often, and are therefore the most time-consuming.
23715
23716 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
23717 better handle Ada programs and multitasking.
23718 It is currently supported on the following platforms
23719 @itemize @bullet
23720 @item
23721 linux x86/x86_64
23722 @item
23723 solaris sparc/sparc64/x86
23724 @item
23725 windows x86
23726 @end itemize
23727
23728 @noindent
23729 In order to profile a program using @code{gprof}, 3 steps are needed:
23730
23731 @itemize @bullet
23732 @item
23733 Code instrumentation, requiring a full recompilation of the project with the
23734 proper switches.
23735 @item
23736 Execution of the program under the analysis conditions, i.e. with the desired
23737 input.
23738 @item
23739 Analysis of the results using the @code{gprof} tool.
23740 @end itemize
23741
23742 @noindent
23743 The following sections detail the different steps, and indicate how
23744 to interpret the results:
23745 @menu
23746 * Compilation for profiling::
23747 * Program execution::
23748 * Running gprof::
23749 * Interpretation of profiling results::
23750 @end menu
23751
23752 @node Compilation for profiling
23753 @subsection Compilation for profiling
23754 @cindex -pg
23755 @cindex Profiling
23756
23757 In order to profile a program the first step is to tell the compiler
23758 to generate the necessary profiling information. The compiler switch to be used
23759 is @code{-pg}, which must be added to other compilation switches. This
23760 switch needs to be specified both during compilation and link stages, and can
23761 be specified once when using gnatmake:
23762
23763 @smallexample
23764 gnatmake -f -pg -P my_project
23765 @end smallexample
23766
23767 @noindent
23768 Note that only the objects that were compiled with the @samp{-pg} switch will be
23769 profiled; if you need to profile your whole project, use the
23770 @samp{-f} gnatmake switch to force full recompilation.
23771
23772 @node Program execution
23773 @subsection Program execution
23774
23775 @noindent
23776 Once the program has been compiled for profiling, you can run it as usual.
23777
23778 The only constraint imposed by profiling is that the program must terminate
23779 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
23780 properly analyzed.
23781
23782 Once the program completes execution, a data file called @file{gmon.out} is
23783 generated in the directory where the program was launched from. If this file
23784 already exists, it will be overwritten.
23785
23786 @node Running gprof
23787 @subsection Running gprof
23788
23789 @noindent
23790 The @code{gprof} tool is called as follow:
23791
23792 @smallexample
23793 gprof my_prog gmon.out
23794 @end smallexample
23795
23796 @noindent
23797 or simpler:
23798
23799 @smallexample
23800 gprof my_prog
23801 @end smallexample
23802
23803 @noindent
23804 The complete form of the gprof command line is the following:
23805
23806 @smallexample
23807 gprof [^switches^options^] [executable [data-file]]
23808 @end smallexample
23809
23810 @noindent
23811 @code{gprof} supports numerous ^switch^options^. The order of these
23812 ^switch^options^ does not matter. The full list of options can be found in
23813 the GNU Profiler User's Guide documentation that comes with this documentation.
23814
23815 The following is the subset of those switches that is most relevant:
23816
23817 @table @option
23818
23819 @item --demangle[=@var{style}]
23820 @itemx --no-demangle
23821 @cindex @option{--demangle} (@code{gprof})
23822 These options control whether symbol names should be demangled when
23823 printing output.  The default is to demangle C++ symbols.  The
23824 @code{--no-demangle} option may be used to turn off demangling. Different
23825 compilers have different mangling styles.  The optional demangling style
23826 argument can be used to choose an appropriate demangling style for your
23827 compiler, in particular Ada symbols generated by GNAT can be demangled using
23828 @code{--demangle=gnat}.
23829
23830 @item -e @var{function_name}
23831 @cindex @option{-e} (@code{gprof})
23832 The @samp{-e @var{function}} option tells @code{gprof} not to print
23833 information about the function @var{function_name} (and its
23834 children@dots{}) in the call graph.  The function will still be listed
23835 as a child of any functions that call it, but its index number will be
23836 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
23837 given; only one @var{function_name} may be indicated with each @samp{-e}
23838 option.
23839
23840 @item -E @var{function_name}
23841 @cindex @option{-E} (@code{gprof})
23842 The @code{-E @var{function}} option works like the @code{-e} option, but
23843 execution time spent in the function (and children who were not called from
23844 anywhere else), will not be used to compute the percentages-of-time for
23845 the call graph.  More than one @samp{-E} option may be given; only one
23846 @var{function_name} may be indicated with each @samp{-E} option.
23847
23848 @item -f @var{function_name}
23849 @cindex @option{-f} (@code{gprof})
23850 The @samp{-f @var{function}} option causes @code{gprof} to limit the
23851 call graph to the function @var{function_name} and its children (and
23852 their children@dots{}).  More than one @samp{-f} option may be given;
23853 only one @var{function_name} may be indicated with each @samp{-f}
23854 option.
23855
23856 @item -F @var{function_name}
23857 @cindex @option{-F} (@code{gprof})
23858 The @samp{-F @var{function}} option works like the @code{-f} option, but
23859 only time spent in the function and its children (and their
23860 children@dots{}) will be used to determine total-time and
23861 percentages-of-time for the call graph.  More than one @samp{-F} option
23862 may be given; only one @var{function_name} may be indicated with each
23863 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
23864
23865 @end table
23866
23867 @node Interpretation of profiling results
23868 @subsection Interpretation of profiling results
23869
23870 @noindent
23871
23872 The results of the profiling analysis are represented by two arrays: the
23873 'flat profile' and the 'call graph'. Full documentation of those outputs
23874 can be found in the GNU Profiler User's Guide.
23875
23876 The flat profile shows the time spent in each function of the program, and how
23877 many time it has been called. This allows you to locate easily the most
23878 time-consuming functions.
23879
23880 The call graph shows, for each subprogram, the subprograms that call it,
23881 and the subprograms that it calls. It also provides an estimate of the time
23882 spent in each of those callers/called subprograms.
23883 @end ifclear
23884
23885 @c ******************************
23886 @node Running and Debugging Ada Programs
23887 @chapter Running and Debugging Ada Programs
23888 @cindex Debugging
23889
23890 @noindent
23891 This chapter discusses how to debug Ada programs.
23892 @ifset vms
23893 It applies to GNAT on the Alpha OpenVMS platform;
23894 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
23895 since HP has implemented Ada support in the OpenVMS debugger on I64.
23896 @end ifset
23897
23898 An incorrect Ada program may be handled in three ways by the GNAT compiler:
23899
23900 @enumerate
23901 @item
23902 The illegality may be a violation of the static semantics of Ada. In
23903 that case GNAT diagnoses the constructs in the program that are illegal.
23904 It is then a straightforward matter for the user to modify those parts of
23905 the program.
23906
23907 @item
23908 The illegality may be a violation of the dynamic semantics of Ada. In
23909 that case the program compiles and executes, but may generate incorrect
23910 results, or may terminate abnormally with some exception.
23911
23912 @item
23913 When presented with a program that contains convoluted errors, GNAT
23914 itself may terminate abnormally without providing full diagnostics on
23915 the incorrect user program.
23916 @end enumerate
23917
23918 @menu
23919 * The GNAT Debugger GDB::
23920 * Running GDB::
23921 * Introduction to GDB Commands::
23922 * Using Ada Expressions::
23923 * Calling User-Defined Subprograms::
23924 * Using the Next Command in a Function::
23925 * Ada Exceptions::
23926 * Ada Tasks::
23927 * Debugging Generic Units::
23928 * GNAT Abnormal Termination or Failure to Terminate::
23929 * Naming Conventions for GNAT Source Files::
23930 * Getting Internal Debugging Information::
23931 * Stack Traceback::
23932 @end menu
23933
23934 @cindex Debugger
23935 @findex gdb
23936
23937 @node The GNAT Debugger GDB
23938 @section The GNAT Debugger GDB
23939
23940 @noindent
23941 @code{GDB} is a general purpose, platform-independent debugger that
23942 can be used to debug mixed-language programs compiled with @command{gcc},
23943 and in particular is capable of debugging Ada programs compiled with
23944 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
23945 complex Ada data structures.
23946
23947 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
23948 @ifset vms
23949 located in the GNU:[DOCS] directory,
23950 @end ifset
23951 for full details on the usage of @code{GDB}, including a section on
23952 its usage on programs. This manual should be consulted for full
23953 details. The section that follows is a brief introduction to the
23954 philosophy and use of @code{GDB}.
23955
23956 When GNAT programs are compiled, the compiler optionally writes debugging
23957 information into the generated object file, including information on
23958 line numbers, and on declared types and variables. This information is
23959 separate from the generated code. It makes the object files considerably
23960 larger, but it does not add to the size of the actual executable that
23961 will be loaded into memory, and has no impact on run-time performance. The
23962 generation of debug information is triggered by the use of the
23963 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
23964 used to carry out the compilations. It is important to emphasize that
23965 the use of these options does not change the generated code.
23966
23967 The debugging information is written in standard system formats that
23968 are used by many tools, including debuggers and profilers. The format
23969 of the information is typically designed to describe C types and
23970 semantics, but GNAT implements a translation scheme which allows full
23971 details about Ada types and variables to be encoded into these
23972 standard C formats. Details of this encoding scheme may be found in
23973 the file exp_dbug.ads in the GNAT source distribution. However, the
23974 details of this encoding are, in general, of no interest to a user,
23975 since @code{GDB} automatically performs the necessary decoding.
23976
23977 When a program is bound and linked, the debugging information is
23978 collected from the object files, and stored in the executable image of
23979 the program. Again, this process significantly increases the size of
23980 the generated executable file, but it does not increase the size of
23981 the executable program itself. Furthermore, if this program is run in
23982 the normal manner, it runs exactly as if the debug information were
23983 not present, and takes no more actual memory.
23984
23985 However, if the program is run under control of @code{GDB}, the
23986 debugger is activated.  The image of the program is loaded, at which
23987 point it is ready to run.  If a run command is given, then the program
23988 will run exactly as it would have if @code{GDB} were not present. This
23989 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
23990 entirely non-intrusive until a breakpoint is encountered.  If no
23991 breakpoint is ever hit, the program will run exactly as it would if no
23992 debugger were present. When a breakpoint is hit, @code{GDB} accesses
23993 the debugging information and can respond to user commands to inspect
23994 variables, and more generally to report on the state of execution.
23995
23996 @c **************
23997 @node Running GDB
23998 @section Running GDB
23999
24000 @noindent
24001 This section describes how to initiate the debugger.
24002 @c The above sentence is really just filler, but it was otherwise
24003 @c clumsy to get the first paragraph nonindented given the conditional
24004 @c nature of the description
24005
24006 @ifclear vms
24007 The debugger can be launched from a @code{GPS} menu or
24008 directly from the command line. The description below covers the latter use.
24009 All the commands shown can be used in the @code{GPS} debug console window,
24010 but there are usually more GUI-based ways to achieve the same effect.
24011 @end ifclear
24012
24013 The command to run @code{GDB} is
24014
24015 @smallexample
24016 $ ^gdb program^GDB PROGRAM^
24017 @end smallexample
24018
24019 @noindent
24020 where @code{^program^PROGRAM^} is the name of the executable file. This
24021 activates the debugger and results in a prompt for debugger commands.
24022 The simplest command is simply @code{run}, which causes the program to run
24023 exactly as if the debugger were not present. The following section
24024 describes some of the additional commands that can be given to @code{GDB}.
24025
24026 @c *******************************
24027 @node Introduction to GDB Commands
24028 @section Introduction to GDB Commands
24029
24030 @noindent
24031 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
24032 Debugging with GDB, gdb, Debugging with GDB},
24033 @ifset vms
24034 located in the GNU:[DOCS] directory,
24035 @end ifset
24036 for extensive documentation on the use
24037 of these commands, together with examples of their use. Furthermore,
24038 the command @command{help} invoked from within GDB activates a simple help
24039 facility which summarizes the available commands and their options.
24040 In this section we summarize a few of the most commonly
24041 used commands to give an idea of what @code{GDB} is about. You should create
24042 a simple program with debugging information and experiment with the use of
24043 these @code{GDB} commands on the program as you read through the
24044 following section.
24045
24046 @table @code
24047 @item set args @var{arguments}
24048 The @var{arguments} list above is a list of arguments to be passed to
24049 the program on a subsequent run command, just as though the arguments
24050 had been entered on a normal invocation of the program. The @code{set args}
24051 command is not needed if the program does not require arguments.
24052
24053 @item run
24054 The @code{run} command causes execution of the program to start from
24055 the beginning. If the program is already running, that is to say if
24056 you are currently positioned at a breakpoint, then a prompt will ask
24057 for confirmation that you want to abandon the current execution and
24058 restart.
24059
24060 @item breakpoint @var{location}
24061 The breakpoint command sets a breakpoint, that is to say a point at which
24062 execution will halt and @code{GDB} will await further
24063 commands. @var{location} is
24064 either a line number within a file, given in the format @code{file:linenumber},
24065 or it is the name of a subprogram. If you request that a breakpoint be set on
24066 a subprogram that is overloaded, a prompt will ask you to specify on which of
24067 those subprograms you want to breakpoint. You can also
24068 specify that all of them should be breakpointed. If the program is run
24069 and execution encounters the breakpoint, then the program
24070 stops and @code{GDB} signals that the breakpoint was encountered by
24071 printing the line of code before which the program is halted.
24072
24073 @item breakpoint exception @var{name}
24074 A special form of the breakpoint command which breakpoints whenever
24075 exception @var{name} is raised.
24076 If @var{name} is omitted,
24077 then a breakpoint will occur when any exception is raised.
24078
24079 @item print @var{expression}
24080 This will print the value of the given expression. Most simple
24081 Ada expression formats are properly handled by @code{GDB}, so the expression
24082 can contain function calls, variables, operators, and attribute references.
24083
24084 @item continue
24085 Continues execution following a breakpoint, until the next breakpoint or the
24086 termination of the program.
24087
24088 @item step
24089 Executes a single line after a breakpoint. If the next statement
24090 is a subprogram call, execution continues into (the first statement of)
24091 the called subprogram.
24092
24093 @item next
24094 Executes a single line. If this line is a subprogram call, executes and
24095 returns from the call.
24096
24097 @item list
24098 Lists a few lines around the current source location. In practice, it
24099 is usually more convenient to have a separate edit window open with the
24100 relevant source file displayed. Successive applications of this command
24101 print subsequent lines. The command can be given an argument which is a
24102 line number, in which case it displays a few lines around the specified one.
24103
24104 @item backtrace
24105 Displays a backtrace of the call chain. This command is typically
24106 used after a breakpoint has occurred, to examine the sequence of calls that
24107 leads to the current breakpoint. The display includes one line for each
24108 activation record (frame) corresponding to an active subprogram.
24109
24110 @item up
24111 At a breakpoint, @code{GDB} can display the values of variables local
24112 to the current frame. The command @code{up} can be used to
24113 examine the contents of other active frames, by moving the focus up
24114 the stack, that is to say from callee to caller, one frame at a time.
24115
24116 @item down
24117 Moves the focus of @code{GDB} down from the frame currently being
24118 examined to the frame of its callee (the reverse of the previous command),
24119
24120 @item frame @var{n}
24121 Inspect the frame with the given number. The value 0 denotes the frame
24122 of the current breakpoint, that is to say the top of the call stack.
24123
24124 @end table
24125
24126 @noindent
24127 The above list is a very short introduction to the commands that
24128 @code{GDB} provides. Important additional capabilities, including conditional
24129 breakpoints, the ability to execute command sequences on a breakpoint,
24130 the ability to debug at the machine instruction level and many other
24131 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
24132 Debugging with GDB}.  Note that most commands can be abbreviated
24133 (for example, c for continue, bt for backtrace).
24134
24135 @node Using Ada Expressions
24136 @section Using Ada Expressions
24137 @cindex Ada expressions
24138
24139 @noindent
24140 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
24141 extensions. The philosophy behind the design of this subset is
24142
24143 @itemize @bullet
24144 @item
24145 That @code{GDB} should provide basic literals and access to operations for
24146 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
24147 leaving more sophisticated computations to subprograms written into the
24148 program (which therefore may be called from @code{GDB}).
24149
24150 @item
24151 That type safety and strict adherence to Ada language restrictions
24152 are not particularly important to the @code{GDB} user.
24153
24154 @item
24155 That brevity is important to the @code{GDB} user.
24156 @end itemize
24157
24158 @noindent
24159 Thus, for brevity, the debugger acts as if there were
24160 implicit @code{with} and @code{use} clauses in effect for all user-written
24161 packages, thus making it unnecessary to fully qualify most names with
24162 their packages, regardless of context. Where this causes ambiguity,
24163 @code{GDB} asks the user's intent.
24164
24165 For details on the supported Ada syntax, see @ref{Top,, Debugging with
24166 GDB, gdb, Debugging with GDB}.
24167
24168 @node Calling User-Defined Subprograms
24169 @section Calling User-Defined Subprograms
24170
24171 @noindent
24172 An important capability of @code{GDB} is the ability to call user-defined
24173 subprograms while debugging. This is achieved simply by entering
24174 a subprogram call statement in the form:
24175
24176 @smallexample
24177 call subprogram-name (parameters)
24178 @end smallexample
24179
24180 @noindent
24181 The keyword @code{call} can be omitted in the normal case where the
24182 @code{subprogram-name} does not coincide with any of the predefined
24183 @code{GDB} commands.
24184
24185 The effect is to invoke the given subprogram, passing it the
24186 list of parameters that is supplied. The parameters can be expressions and
24187 can include variables from the program being debugged. The
24188 subprogram must be defined
24189 at the library level within your program, and @code{GDB} will call the
24190 subprogram within the environment of your program execution (which
24191 means that the subprogram is free to access or even modify variables
24192 within your program).
24193
24194 The most important use of this facility is in allowing the inclusion of
24195 debugging routines that are tailored to particular data structures
24196 in your program. Such debugging routines can be written to provide a suitably
24197 high-level description of an abstract type, rather than a low-level dump
24198 of its physical layout. After all, the standard
24199 @code{GDB print} command only knows the physical layout of your
24200 types, not their abstract meaning. Debugging routines can provide information
24201 at the desired semantic level and are thus enormously useful.
24202
24203 For example, when debugging GNAT itself, it is crucial to have access to
24204 the contents of the tree nodes used to represent the program internally.
24205 But tree nodes are represented simply by an integer value (which in turn
24206 is an index into a table of nodes).
24207 Using the @code{print} command on a tree node would simply print this integer
24208 value, which is not very useful. But the PN routine (defined in file
24209 treepr.adb in the GNAT sources) takes a tree node as input, and displays
24210 a useful high level representation of the tree node, which includes the
24211 syntactic category of the node, its position in the source, the integers
24212 that denote descendant nodes and parent node, as well as varied
24213 semantic information. To study this example in more detail, you might want to
24214 look at the body of the PN procedure in the stated file.
24215
24216 @node Using the Next Command in a Function
24217 @section Using the Next Command in a Function
24218
24219 @noindent
24220 When you use the @code{next} command in a function, the current source
24221 location will advance to the next statement as usual. A special case
24222 arises in the case of a @code{return} statement.
24223
24224 Part of the code for a return statement is the ``epilog'' of the function.
24225 This is the code that returns to the caller. There is only one copy of
24226 this epilog code, and it is typically associated with the last return
24227 statement in the function if there is more than one return. In some
24228 implementations, this epilog is associated with the first statement
24229 of the function.
24230
24231 The result is that if you use the @code{next} command from a return
24232 statement that is not the last return statement of the function you
24233 may see a strange apparent jump to the last return statement or to
24234 the start of the function. You should simply ignore this odd jump.
24235 The value returned is always that from the first return statement
24236 that was stepped through.
24237
24238 @node Ada Exceptions
24239 @section Breaking on Ada Exceptions
24240 @cindex Exceptions
24241
24242 @noindent
24243 You can set breakpoints that trip when your program raises
24244 selected exceptions.
24245
24246 @table @code
24247 @item break exception
24248 Set a breakpoint that trips whenever (any task in the) program raises
24249 any exception.
24250
24251 @item break exception @var{name}
24252 Set a breakpoint that trips whenever (any task in the) program raises
24253 the exception @var{name}.
24254
24255 @item break exception unhandled
24256 Set a breakpoint that trips whenever (any task in the) program raises an
24257 exception for which there is no handler.
24258
24259 @item info exceptions
24260 @itemx info exceptions @var{regexp}
24261 The @code{info exceptions} command permits the user to examine all defined
24262 exceptions within Ada programs. With a regular expression, @var{regexp}, as
24263 argument, prints out only those exceptions whose name matches @var{regexp}.
24264 @end table
24265
24266 @node Ada Tasks
24267 @section Ada Tasks
24268 @cindex Tasks
24269
24270 @noindent
24271 @code{GDB} allows the following task-related commands:
24272
24273 @table @code
24274 @item info tasks
24275 This command shows a list of current Ada tasks, as in the following example:
24276
24277 @smallexample
24278 @iftex
24279 @leftskip=0cm
24280 @end iftex
24281 (gdb) info tasks
24282   ID       TID P-ID   Thread Pri State                 Name
24283    1   8088000   0   807e000  15 Child Activation Wait main_task
24284    2   80a4000   1   80ae000  15 Accept/Select Wait    b
24285    3   809a800   1   80a4800  15 Child Activation Wait a
24286 *  4   80ae800   3   80b8000  15 Running               c
24287 @end smallexample
24288
24289 @noindent
24290 In this listing, the asterisk before the first task indicates it to be the
24291 currently running task. The first column lists the task ID that is used
24292 to refer to tasks in the following commands.
24293
24294 @item break @var{linespec} task @var{taskid}
24295 @itemx break @var{linespec} task @var{taskid} if @dots{}
24296 @cindex Breakpoints and tasks
24297 These commands are like the @code{break @dots{} thread @dots{}}.
24298 @var{linespec} specifies source lines.
24299
24300 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
24301 to specify that you only want @code{GDB} to stop the program when a
24302 particular Ada task reaches this breakpoint. @var{taskid} is one of the
24303 numeric task identifiers assigned by @code{GDB}, shown in the first
24304 column of the @samp{info tasks} display.
24305
24306 If you do not specify @samp{task @var{taskid}} when you set a
24307 breakpoint, the breakpoint applies to @emph{all} tasks of your
24308 program.
24309
24310 You can use the @code{task} qualifier on conditional breakpoints as
24311 well; in this case, place @samp{task @var{taskid}} before the
24312 breakpoint condition (before the @code{if}).
24313
24314 @item task @var{taskno}
24315 @cindex Task switching
24316
24317 This command allows to switch to the task referred by @var{taskno}. In
24318 particular, This allows to browse the backtrace of the specified
24319 task. It is advised to switch back to the original task before
24320 continuing execution otherwise the scheduling of the program may be
24321 perturbed.
24322 @end table
24323
24324 @noindent
24325 For more detailed information on the tasking support,
24326 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
24327
24328 @node Debugging Generic Units
24329 @section Debugging Generic Units
24330 @cindex Debugging Generic Units
24331 @cindex Generics
24332
24333 @noindent
24334 GNAT always uses code expansion for generic instantiation. This means that
24335 each time an instantiation occurs, a complete copy of the original code is
24336 made, with appropriate substitutions of formals by actuals.
24337
24338 It is not possible to refer to the original generic entities in
24339 @code{GDB}, but it is always possible to debug a particular instance of
24340 a generic, by using the appropriate expanded names. For example, if we have
24341
24342 @smallexample @c ada
24343 @group
24344 @cartouche
24345 procedure g is
24346
24347    generic package k is
24348       procedure kp (v1 : in out integer);
24349    end k;
24350
24351    package body k is
24352       procedure kp (v1 : in out integer) is
24353       begin
24354          v1 := v1 + 1;
24355       end kp;
24356    end k;
24357
24358    package k1 is new k;
24359    package k2 is new k;
24360
24361    var : integer := 1;
24362
24363 begin
24364    k1.kp (var);
24365    k2.kp (var);
24366    k1.kp (var);
24367    k2.kp (var);
24368 end;
24369 @end cartouche
24370 @end group
24371 @end smallexample
24372
24373 @noindent
24374 Then to break on a call to procedure kp in the k2 instance, simply
24375 use the command:
24376
24377 @smallexample
24378 (gdb) break g.k2.kp
24379 @end smallexample
24380
24381 @noindent
24382 When the breakpoint occurs, you can step through the code of the
24383 instance in the normal manner and examine the values of local variables, as for
24384 other units.
24385
24386 @node GNAT Abnormal Termination or Failure to Terminate
24387 @section GNAT Abnormal Termination or Failure to Terminate
24388 @cindex GNAT Abnormal Termination or Failure to Terminate
24389
24390 @noindent
24391 When presented with programs that contain serious errors in syntax
24392 or semantics,
24393 GNAT may on rare occasions  experience problems in operation, such
24394 as aborting with a
24395 segmentation fault or illegal memory access, raising an internal
24396 exception, terminating abnormally, or failing to terminate at all.
24397 In such cases, you can activate
24398 various features of GNAT that can help you pinpoint the construct in your
24399 program that is the likely source of the problem.
24400
24401 The following strategies are presented in increasing order of
24402 difficulty, corresponding to your experience in using GNAT and your
24403 familiarity with compiler internals.
24404
24405 @enumerate
24406 @item
24407 Run @command{gcc} with the @option{-gnatf}. This first
24408 switch causes all errors on a given line to be reported. In its absence,
24409 only the first error on a line is displayed.
24410
24411 The @option{-gnatdO} switch causes errors to be displayed as soon as they
24412 are encountered, rather than after compilation is terminated. If GNAT
24413 terminates prematurely or goes into an infinite loop, the last error
24414 message displayed may help to pinpoint the culprit.
24415
24416 @item
24417 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
24418 mode, @command{gcc} produces ongoing information about the progress of the
24419 compilation and provides the name of each procedure as code is
24420 generated. This switch allows you to find which Ada procedure was being
24421 compiled when it encountered a code generation problem.
24422
24423 @item
24424 @cindex @option{-gnatdc} switch
24425 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
24426 switch that does for the front-end what @option{^-v^VERBOSE^} does
24427 for the back end. The system prints the name of each unit,
24428 either a compilation unit or nested unit, as it is being analyzed.
24429 @item
24430 Finally, you can start
24431 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
24432 front-end of GNAT, and can be run independently (normally it is just
24433 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
24434 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
24435 @code{where} command is the first line of attack; the variable
24436 @code{lineno} (seen by @code{print lineno}), used by the second phase of
24437 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
24438 which the execution stopped, and @code{input_file name} indicates the name of
24439 the source file.
24440 @end enumerate
24441
24442 @node Naming Conventions for GNAT Source Files
24443 @section Naming Conventions for GNAT Source Files
24444
24445 @noindent
24446 In order to examine the workings of the GNAT system, the following
24447 brief description of its organization may be helpful:
24448
24449 @itemize @bullet
24450 @item
24451 Files with prefix @file{^sc^SC^} contain the lexical scanner.
24452
24453 @item
24454 All files prefixed with @file{^par^PAR^} are components of the parser. The
24455 numbers correspond to chapters of the Ada Reference Manual. For example,
24456 parsing of select statements can be found in @file{par-ch9.adb}.
24457
24458 @item
24459 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
24460 numbers correspond to chapters of the Ada standard. For example, all
24461 issues involving context clauses can be found in @file{sem_ch10.adb}. In
24462 addition, some features of the language require sufficient special processing
24463 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
24464 dynamic dispatching, etc.
24465
24466 @item
24467 All files prefixed with @file{^exp^EXP^} perform normalization and
24468 expansion of the intermediate representation (abstract syntax tree, or AST).
24469 these files use the same numbering scheme as the parser and semantics files.
24470 For example, the construction of record initialization procedures is done in
24471 @file{exp_ch3.adb}.
24472
24473 @item
24474 The files prefixed with @file{^bind^BIND^} implement the binder, which
24475 verifies the consistency of the compilation, determines an order of
24476 elaboration, and generates the bind file.
24477
24478 @item
24479 The files @file{atree.ads} and @file{atree.adb} detail the low-level
24480 data structures used by the front-end.
24481
24482 @item
24483 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
24484 the abstract syntax tree as produced by the parser.
24485
24486 @item
24487 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
24488 all entities, computed during semantic analysis.
24489
24490 @item
24491 Library management issues are dealt with in files with prefix
24492 @file{^lib^LIB^}.
24493
24494 @item
24495 @findex Ada
24496 @cindex Annex A
24497 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
24498 defined in Annex A.
24499
24500 @item
24501 @findex Interfaces
24502 @cindex Annex B
24503 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
24504 defined in Annex B.
24505
24506 @item
24507 @findex System
24508 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
24509 both language-defined children and GNAT run-time routines.
24510
24511 @item
24512 @findex GNAT
24513 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
24514 general-purpose packages, fully documented in their specs. All
24515 the other @file{.c} files are modifications of common @command{gcc} files.
24516 @end itemize
24517
24518 @node Getting Internal Debugging Information
24519 @section Getting Internal Debugging Information
24520
24521 @noindent
24522 Most compilers have internal debugging switches and modes. GNAT
24523 does also, except GNAT internal debugging switches and modes are not
24524 secret. A summary and full description of all the compiler and binder
24525 debug flags are in the file @file{debug.adb}. You must obtain the
24526 sources of the compiler to see the full detailed effects of these flags.
24527
24528 The switches that print the source of the program (reconstructed from
24529 the internal tree) are of general interest for user programs, as are the
24530 options to print
24531 the full internal tree, and the entity table (the symbol table
24532 information). The reconstructed source provides a readable version of the
24533 program after the front-end has completed analysis and  expansion,
24534 and is useful when studying the performance of specific constructs.
24535 For example, constraint checks are indicated, complex aggregates
24536 are replaced with loops and assignments, and tasking primitives
24537 are replaced with run-time calls.
24538
24539 @node Stack Traceback
24540 @section Stack Traceback
24541 @cindex traceback
24542 @cindex stack traceback
24543 @cindex stack unwinding
24544
24545 @noindent
24546 Traceback is a mechanism to display the sequence of subprogram calls that
24547 leads to a specified execution point in a program. Often (but not always)
24548 the execution point is an instruction at which an exception has been raised.
24549 This mechanism is also known as @i{stack unwinding} because it obtains
24550 its information by scanning the run-time stack and recovering the activation
24551 records of all active subprograms. Stack unwinding is one of the most
24552 important tools for program debugging.
24553
24554 The first entry stored in traceback corresponds to the deepest calling level,
24555 that is to say the subprogram currently executing the instruction
24556 from which we want to obtain the traceback.
24557
24558 Note that there is no runtime performance penalty when stack traceback
24559 is enabled, and no exception is raised during program execution.
24560
24561 @menu
24562 * Non-Symbolic Traceback::
24563 * Symbolic Traceback::
24564 @end menu
24565
24566 @node Non-Symbolic Traceback
24567 @subsection Non-Symbolic Traceback
24568 @cindex traceback, non-symbolic
24569
24570 @noindent
24571 Note: this feature is not supported on all platforms. See
24572 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
24573 platforms.
24574
24575 @menu
24576 * Tracebacks From an Unhandled Exception::
24577 * Tracebacks From Exception Occurrences (non-symbolic)::
24578 * Tracebacks From Anywhere in a Program (non-symbolic)::
24579 @end menu
24580
24581 @node Tracebacks From an Unhandled Exception
24582 @subsubsection Tracebacks From an Unhandled Exception
24583
24584 @noindent
24585 A runtime non-symbolic traceback is a list of addresses of call instructions.
24586 To enable this feature you must use the @option{-E}
24587 @code{gnatbind}'s option. With this option a stack traceback is stored as part
24588 of exception information. You can retrieve this information using the
24589 @code{addr2line} tool.
24590
24591 Here is a simple example:
24592
24593 @smallexample @c ada
24594 @cartouche
24595 procedure STB is
24596
24597    procedure P1 is
24598    begin
24599       raise Constraint_Error;
24600    end P1;
24601
24602    procedure P2 is
24603    begin
24604       P1;
24605    end P2;
24606
24607 begin
24608    P2;
24609 end STB;
24610 @end cartouche
24611 @end smallexample
24612
24613 @smallexample
24614 $ gnatmake stb -bargs -E
24615 $ stb
24616
24617 Execution terminated by unhandled exception
24618 Exception name: CONSTRAINT_ERROR
24619 Message: stb.adb:5
24620 Call stack traceback locations:
24621 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24622 @end smallexample
24623
24624 @noindent
24625 As we see the traceback lists a sequence of addresses for the unhandled
24626 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
24627 guess that this exception come from procedure P1. To translate these
24628 addresses into the source lines where the calls appear, the
24629 @code{addr2line} tool, described below, is invaluable. The use of this tool
24630 requires the program to be compiled with debug information.
24631
24632 @smallexample
24633 $ gnatmake -g stb -bargs -E
24634 $ stb
24635
24636 Execution terminated by unhandled exception
24637 Exception name: CONSTRAINT_ERROR
24638 Message: stb.adb:5
24639 Call stack traceback locations:
24640 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24641
24642 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
24643    0x4011f1 0x77e892a4
24644
24645 00401373 at d:/stb/stb.adb:5
24646 0040138B at d:/stb/stb.adb:10
24647 0040139C at d:/stb/stb.adb:14
24648 00401335 at d:/stb/b~stb.adb:104
24649 004011C4 at /build/@dots{}/crt1.c:200
24650 004011F1 at /build/@dots{}/crt1.c:222
24651 77E892A4 in ?? at ??:0
24652 @end smallexample
24653
24654 @noindent
24655 The @code{addr2line} tool has several other useful options:
24656
24657 @table @code
24658 @item --functions
24659 to get the function name corresponding to any location
24660
24661 @item --demangle=gnat
24662 to use the gnat decoding mode for the function names. Note that
24663 for binutils version 2.9.x the option is simply @option{--demangle}.
24664 @end table
24665
24666 @smallexample
24667 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
24668    0x40139c 0x401335 0x4011c4 0x4011f1
24669
24670 00401373 in stb.p1 at d:/stb/stb.adb:5
24671 0040138B in stb.p2 at d:/stb/stb.adb:10
24672 0040139C in stb at d:/stb/stb.adb:14
24673 00401335 in main at d:/stb/b~stb.adb:104
24674 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
24675 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
24676 @end smallexample
24677
24678 @noindent
24679 From this traceback we can see that the exception was raised in
24680 @file{stb.adb} at line 5, which was reached from a procedure call in
24681 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
24682 which contains the call to the main program.
24683 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
24684 and the output will vary from platform to platform.
24685
24686 It is also possible to use @code{GDB} with these traceback addresses to debug
24687 the program. For example, we can break at a given code location, as reported
24688 in the stack traceback:
24689
24690 @smallexample
24691 $ gdb -nw stb
24692 @ifclear vms
24693 @noindent
24694 Furthermore, this feature is not implemented inside Windows DLL. Only
24695 the non-symbolic traceback is reported in this case.
24696 @end ifclear
24697
24698 (gdb) break *0x401373
24699 Breakpoint 1 at 0x401373: file stb.adb, line 5.
24700 @end smallexample
24701
24702 @noindent
24703 It is important to note that the stack traceback addresses
24704 do not change when debug information is included. This is particularly useful
24705 because it makes it possible to release software without debug information (to
24706 minimize object size), get a field report that includes a stack traceback
24707 whenever an internal bug occurs, and then be able to retrieve the sequence
24708 of calls with the same program compiled with debug information.
24709
24710 @node Tracebacks From Exception Occurrences (non-symbolic)
24711 @subsubsection Tracebacks From Exception Occurrences
24712
24713 @noindent
24714 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
24715 The stack traceback is attached to the exception information string, and can
24716 be retrieved in an exception handler within the Ada program, by means of the
24717 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
24718
24719 @smallexample @c ada
24720 with Ada.Text_IO;
24721 with Ada.Exceptions;
24722
24723 procedure STB is
24724
24725    use Ada;
24726    use Ada.Exceptions;
24727
24728    procedure P1 is
24729       K : Positive := 1;
24730    begin
24731       K := K - 1;
24732    exception
24733       when E : others =>
24734          Text_IO.Put_Line (Exception_Information (E));
24735    end P1;
24736
24737    procedure P2 is
24738    begin
24739       P1;
24740    end P2;
24741
24742 begin
24743    P2;
24744 end STB;
24745 @end smallexample
24746
24747 @noindent
24748 This program will output:
24749
24750 @smallexample
24751 $ stb
24752
24753 Exception name: CONSTRAINT_ERROR
24754 Message: stb.adb:12
24755 Call stack traceback locations:
24756 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
24757 @end smallexample
24758
24759 @node Tracebacks From Anywhere in a Program (non-symbolic)
24760 @subsubsection Tracebacks From Anywhere in a Program
24761
24762 @noindent
24763 It is also possible to retrieve a stack traceback from anywhere in a
24764 program. For this you need to
24765 use the @code{GNAT.Traceback} API. This package includes a procedure called
24766 @code{Call_Chain} that computes a complete stack traceback, as well as useful
24767 display procedures described below. It is not necessary to use the
24768 @option{-E gnatbind} option in this case, because the stack traceback mechanism
24769 is invoked explicitly.
24770
24771 @noindent
24772 In the following example we compute a traceback at a specific location in
24773 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
24774 convert addresses to strings:
24775
24776 @smallexample @c ada
24777 with Ada.Text_IO;
24778 with GNAT.Traceback;
24779 with GNAT.Debug_Utilities;
24780
24781 procedure STB is
24782
24783    use Ada;
24784    use GNAT;
24785    use GNAT.Traceback;
24786
24787    procedure P1 is
24788       TB  : Tracebacks_Array (1 .. 10);
24789       --  We are asking for a maximum of 10 stack frames.
24790       Len : Natural;
24791       --  Len will receive the actual number of stack frames returned.
24792    begin
24793       Call_Chain (TB, Len);
24794
24795       Text_IO.Put ("In STB.P1 : ");
24796
24797       for K in 1 .. Len loop
24798          Text_IO.Put (Debug_Utilities.Image (TB (K)));
24799          Text_IO.Put (' ');
24800       end loop;
24801
24802       Text_IO.New_Line;
24803    end P1;
24804
24805    procedure P2 is
24806    begin
24807       P1;
24808    end P2;
24809
24810 begin
24811    P2;
24812 end STB;
24813 @end smallexample
24814
24815 @smallexample
24816 $ gnatmake -g stb
24817 $ stb
24818
24819 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
24820 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
24821 @end smallexample
24822
24823 @noindent
24824 You can then get further information by invoking the @code{addr2line}
24825 tool as described earlier (note that the hexadecimal addresses
24826 need to be specified in C format, with a leading ``0x'').
24827
24828 @node Symbolic Traceback
24829 @subsection Symbolic Traceback
24830 @cindex traceback, symbolic
24831
24832 @noindent
24833 A symbolic traceback is a stack traceback in which procedure names are
24834 associated with each code location.
24835
24836 @noindent
24837 Note that this feature is not supported on all platforms. See
24838 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
24839 list of currently supported platforms.
24840
24841 @noindent
24842 Note that the symbolic traceback requires that the program be compiled
24843 with debug information. If it is not compiled with debug information
24844 only the non-symbolic information will be valid.
24845
24846 @menu
24847 * Tracebacks From Exception Occurrences (symbolic)::
24848 * Tracebacks From Anywhere in a Program (symbolic)::
24849 @end menu
24850
24851 @node Tracebacks From Exception Occurrences (symbolic)
24852 @subsubsection Tracebacks From Exception Occurrences
24853
24854 @smallexample @c ada
24855 with Ada.Text_IO;
24856 with GNAT.Traceback.Symbolic;
24857
24858 procedure STB is
24859
24860    procedure P1 is
24861    begin
24862       raise Constraint_Error;
24863    end P1;
24864
24865    procedure P2 is
24866    begin
24867       P1;
24868    end P2;
24869
24870    procedure P3 is
24871    begin
24872       P2;
24873    end P3;
24874
24875 begin
24876    P3;
24877 exception
24878    when E : others =>
24879       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
24880 end STB;
24881 @end smallexample
24882
24883 @smallexample
24884 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
24885 $ stb
24886
24887 0040149F in stb.p1 at stb.adb:8
24888 004014B7 in stb.p2 at stb.adb:13
24889 004014CF in stb.p3 at stb.adb:18
24890 004015DD in ada.stb at stb.adb:22
24891 00401461 in main at b~stb.adb:168
24892 004011C4 in __mingw_CRTStartup at crt1.c:200
24893 004011F1 in mainCRTStartup at crt1.c:222
24894 77E892A4 in ?? at ??:0
24895 @end smallexample
24896
24897 @noindent
24898 In the above example the ``.\'' syntax in the @command{gnatmake} command
24899 is currently required by @command{addr2line} for files that are in
24900 the current working directory.
24901 Moreover, the exact sequence of linker options may vary from platform
24902 to platform.
24903 The above @option{-largs} section is for Windows platforms. By contrast,
24904 under Unix there is no need for the @option{-largs} section.
24905 Differences across platforms are due to details of linker implementation.
24906
24907 @node Tracebacks From Anywhere in a Program (symbolic)
24908 @subsubsection Tracebacks From Anywhere in a Program
24909
24910 @noindent
24911 It is possible to get a symbolic stack traceback
24912 from anywhere in a program, just as for non-symbolic tracebacks.
24913 The first step is to obtain a non-symbolic
24914 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
24915 information. Here is an example:
24916
24917 @smallexample @c ada
24918 with Ada.Text_IO;
24919 with GNAT.Traceback;
24920 with GNAT.Traceback.Symbolic;
24921
24922 procedure STB is
24923
24924    use Ada;
24925    use GNAT.Traceback;
24926    use GNAT.Traceback.Symbolic;
24927
24928    procedure P1 is
24929       TB  : Tracebacks_Array (1 .. 10);
24930       --  We are asking for a maximum of 10 stack frames.
24931       Len : Natural;
24932       --  Len will receive the actual number of stack frames returned.
24933    begin
24934       Call_Chain (TB, Len);
24935       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
24936    end P1;
24937
24938    procedure P2 is
24939    begin
24940       P1;
24941    end P2;
24942
24943 begin
24944    P2;
24945 end STB;
24946 @end smallexample
24947
24948 @c ******************************
24949 @ifset vms
24950 @node Compatibility with HP Ada
24951 @chapter Compatibility with HP Ada
24952 @cindex Compatibility
24953
24954 @noindent
24955 @cindex DEC Ada
24956 @cindex HP Ada
24957 @cindex Compatibility between GNAT and HP Ada
24958 This chapter compares HP Ada (formerly known as ``DEC Ada'')
24959 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
24960 GNAT is highly compatible
24961 with HP Ada, and it should generally be straightforward to port code
24962 from the HP Ada environment to GNAT. However, there are a few language
24963 and implementation differences of which the user must be aware. These
24964 differences are discussed in this chapter. In
24965 addition, the operating environment and command structure for the
24966 compiler are different, and these differences are also discussed.
24967
24968 For further details on these and other compatibility issues,
24969 see Appendix E of the HP publication
24970 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
24971
24972 Except where otherwise indicated, the description of GNAT for OpenVMS
24973 applies to both the Alpha and I64 platforms.
24974
24975 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
24976 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24977
24978 The discussion in this chapter addresses specifically the implementation
24979 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
24980 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
24981 GNAT always follows the Alpha implementation.
24982
24983 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
24984 attributes are recognized, although only a subset of them can sensibly
24985 be implemented.  The description of pragmas in
24986 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
24987 indicates whether or not they are applicable to non-VMS systems.
24988
24989 @menu
24990 * Ada Language Compatibility::
24991 * Differences in the Definition of Package System::
24992 * Language-Related Features::
24993 * The Package STANDARD::
24994 * The Package SYSTEM::
24995 * Tasking and Task-Related Features::
24996 * Pragmas and Pragma-Related Features::
24997 * Library of Predefined Units::
24998 * Bindings::
24999 * Main Program Definition::
25000 * Implementation-Defined Attributes::
25001 * Compiler and Run-Time Interfacing::
25002 * Program Compilation and Library Management::
25003 * Input-Output::
25004 * Implementation Limits::
25005 * Tools and Utilities::
25006 @end menu
25007
25008 @node Ada Language Compatibility
25009 @section Ada Language Compatibility
25010
25011 @noindent
25012 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
25013 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
25014 with Ada 83, and therefore Ada 83 programs will compile
25015 and run under GNAT with
25016 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
25017 provides details on specific incompatibilities.
25018
25019 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
25020 as well as the pragma @code{ADA_83}, to force the compiler to
25021 operate in Ada 83 mode. This mode does not guarantee complete
25022 conformance to Ada 83, but in practice is sufficient to
25023 eliminate most sources of incompatibilities.
25024 In particular, it eliminates the recognition of the
25025 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
25026 in Ada 83 programs is legal, and handles the cases of packages
25027 with optional bodies, and generics that instantiate unconstrained
25028 types without the use of @code{(<>)}.
25029
25030 @node Differences in the Definition of Package System
25031 @section Differences in the Definition of Package @code{System}
25032
25033 @noindent
25034 An Ada compiler is allowed to add
25035 implementation-dependent declarations to package @code{System}.
25036 In normal mode,
25037 GNAT does not take advantage of this permission, and the version of
25038 @code{System} provided by GNAT exactly matches that defined in the Ada
25039 Reference Manual.
25040
25041 However, HP Ada adds an extensive set of declarations to package
25042 @code{System},
25043 as fully documented in the HP Ada manuals. To minimize changes required
25044 for programs that make use of these extensions, GNAT provides the pragma
25045 @code{Extend_System} for extending the definition of package System. By using:
25046 @cindex pragma @code{Extend_System}
25047 @cindex @code{Extend_System} pragma
25048
25049 @smallexample @c ada
25050 @group
25051 @cartouche
25052 pragma Extend_System (Aux_DEC);
25053 @end cartouche
25054 @end group
25055 @end smallexample
25056
25057 @noindent
25058 the set of definitions in @code{System} is extended to include those in
25059 package @code{System.Aux_DEC}.
25060 @cindex @code{System.Aux_DEC} package
25061 @cindex @code{Aux_DEC} package (child of @code{System})
25062 These definitions are incorporated directly into package @code{System},
25063 as though they had been declared there. For a
25064 list of the declarations added, see the spec of this package,
25065 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
25066 @cindex @file{s-auxdec.ads} file
25067 The pragma @code{Extend_System} is a configuration pragma, which means that
25068 it can be placed in the file @file{gnat.adc}, so that it will automatically
25069 apply to all subsequent compilations. See @ref{Configuration Pragmas},
25070 for further details.
25071
25072 An alternative approach that avoids the use of the non-standard
25073 @code{Extend_System} pragma is to add a context clause to the unit that
25074 references these facilities:
25075
25076 @smallexample @c ada
25077 @cartouche
25078 with System.Aux_DEC;
25079 use  System.Aux_DEC;
25080 @end cartouche
25081 @end smallexample
25082
25083 @noindent
25084 The effect is not quite semantically identical to incorporating
25085 the declarations directly into package @code{System},
25086 but most programs will not notice a difference
25087 unless they use prefix notation (e.g.@: @code{System.Integer_8})
25088 to reference the entities directly in package @code{System}.
25089 For units containing such references,
25090 the prefixes must either be removed, or the pragma @code{Extend_System}
25091 must be used.
25092
25093 @node Language-Related Features
25094 @section Language-Related Features
25095
25096 @noindent
25097 The following sections highlight differences in types,
25098 representations of types, operations, alignment, and
25099 related topics.
25100
25101 @menu
25102 * Integer Types and Representations::
25103 * Floating-Point Types and Representations::
25104 * Pragmas Float_Representation and Long_Float::
25105 * Fixed-Point Types and Representations::
25106 * Record and Array Component Alignment::
25107 * Address Clauses::
25108 * Other Representation Clauses::
25109 @end menu
25110
25111 @node Integer Types and Representations
25112 @subsection Integer Types and Representations
25113
25114 @noindent
25115 The set of predefined integer types is identical in HP Ada and GNAT.
25116 Furthermore the representation of these integer types is also identical,
25117 including the capability of size clauses forcing biased representation.
25118
25119 In addition,
25120 HP Ada for OpenVMS Alpha systems has defined the
25121 following additional integer types in package @code{System}:
25122
25123 @itemize @bullet
25124
25125 @item
25126 @code{INTEGER_8}
25127
25128 @item
25129 @code{INTEGER_16}
25130
25131 @item
25132 @code{INTEGER_32}
25133
25134 @item
25135 @code{INTEGER_64}
25136
25137 @item
25138 @code{LARGEST_INTEGER}
25139 @end itemize
25140
25141 @noindent
25142 In GNAT, the first four of these types may be obtained from the
25143 standard Ada package @code{Interfaces}.
25144 Alternatively, by use of the pragma @code{Extend_System}, identical
25145 declarations can be referenced directly in package @code{System}.
25146 On both GNAT and HP Ada, the maximum integer size is 64 bits.
25147
25148 @node Floating-Point Types and Representations
25149 @subsection Floating-Point Types and Representations
25150 @cindex Floating-Point types
25151
25152 @noindent
25153 The set of predefined floating-point types is identical in HP Ada and GNAT.
25154 Furthermore the representation of these floating-point
25155 types is also identical. One important difference is that the default
25156 representation for HP Ada is @code{VAX_Float}, but the default representation
25157 for GNAT is IEEE.
25158
25159 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
25160 pragma @code{Float_Representation} as described in the HP Ada
25161 documentation.
25162 For example, the declarations:
25163
25164 @smallexample @c ada
25165 @cartouche
25166 type F_Float is digits 6;
25167 pragma Float_Representation (VAX_Float, F_Float);
25168 @end cartouche
25169 @end smallexample
25170
25171 @noindent
25172 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
25173 format.
25174 This set of declarations actually appears in @code{System.Aux_DEC},
25175 which contains
25176 the full set of additional floating-point declarations provided in
25177 the HP Ada version of package @code{System}.
25178 This and similar declarations may be accessed in a user program
25179 by using pragma @code{Extend_System}. The use of this
25180 pragma, and the related pragma @code{Long_Float} is described in further
25181 detail in the following section.
25182
25183 @node Pragmas Float_Representation and Long_Float
25184 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
25185
25186 @noindent
25187 HP Ada provides the pragma @code{Float_Representation}, which
25188 acts as a program library switch to allow control over
25189 the internal representation chosen for the predefined
25190 floating-point types declared in the package @code{Standard}.
25191 The format of this pragma is as follows:
25192
25193 @smallexample @c ada
25194 @cartouche
25195 pragma Float_Representation(VAX_Float | IEEE_Float);
25196 @end cartouche
25197 @end smallexample
25198
25199 @noindent
25200 This pragma controls the representation of floating-point
25201 types as follows:
25202
25203 @itemize @bullet
25204 @item
25205 @code{VAX_Float} specifies that floating-point
25206 types are represented by default with the VAX system hardware types
25207 @code{F-floating}, @code{D-floating}, @code{G-floating}.
25208 Note that the @code{H-floating}
25209 type was available only on VAX systems, and is not available
25210 in either HP Ada or GNAT.
25211
25212 @item
25213 @code{IEEE_Float} specifies that floating-point
25214 types are represented by default with the IEEE single and
25215 double floating-point types.
25216 @end itemize
25217
25218 @noindent
25219 GNAT provides an identical implementation of the pragma
25220 @code{Float_Representation}, except that it functions as a
25221 configuration pragma. Note that the
25222 notion of configuration pragma corresponds closely to the
25223 HP Ada notion of a program library switch.
25224
25225 When no pragma is used in GNAT, the default is @code{IEEE_Float},
25226 which is different
25227 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
25228 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
25229 advisable to change the format of numbers passed to standard library
25230 routines, and if necessary explicit type conversions may be needed.
25231
25232 The use of @code{IEEE_Float} is recommended in GNAT since it is more
25233 efficient, and (given that it conforms to an international standard)
25234 potentially more portable.
25235 The situation in which @code{VAX_Float} may be useful is in interfacing
25236 to existing code and data that expect the use of @code{VAX_Float}.
25237 In such a situation use the predefined @code{VAX_Float}
25238 types in package @code{System}, as extended by
25239 @code{Extend_System}. For example, use @code{System.F_Float}
25240 to specify the 32-bit @code{F-Float} format.
25241
25242 @noindent
25243 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
25244 to allow control over the internal representation chosen
25245 for the predefined type @code{Long_Float} and for floating-point
25246 type declarations with digits specified in the range 7 .. 15.
25247 The format of this pragma is as follows:
25248
25249 @smallexample @c ada
25250 @cartouche
25251 pragma Long_Float (D_FLOAT | G_FLOAT);
25252 @end cartouche
25253 @end smallexample
25254
25255 @node Fixed-Point Types and Representations
25256 @subsection Fixed-Point Types and Representations
25257
25258 @noindent
25259 On HP Ada for OpenVMS Alpha systems, rounding is
25260 away from zero for both positive and negative numbers.
25261 Therefore, @code{+0.5} rounds to @code{1},
25262 and @code{-0.5} rounds to @code{-1}.
25263
25264 On GNAT the results of operations
25265 on fixed-point types are in accordance with the Ada
25266 rules. In particular, results of operations on decimal
25267 fixed-point types are truncated.
25268
25269 @node Record and Array Component Alignment
25270 @subsection Record and Array Component Alignment
25271
25272 @noindent
25273 On HP Ada for OpenVMS Alpha, all non-composite components
25274 are aligned on natural boundaries. For example, 1-byte
25275 components are aligned on byte boundaries, 2-byte
25276 components on 2-byte boundaries, 4-byte components on 4-byte
25277 byte boundaries, and so on. The OpenVMS Alpha hardware
25278 runs more efficiently with naturally aligned data.
25279
25280 On GNAT, alignment rules are compatible
25281 with HP Ada for OpenVMS Alpha.
25282
25283 @node Address Clauses
25284 @subsection Address Clauses
25285
25286 @noindent
25287 In HP Ada and GNAT, address clauses are supported for
25288 objects and imported subprograms.
25289 The predefined type @code{System.Address} is a private type
25290 in both compilers on Alpha OpenVMS, with the same representation
25291 (it is simply a machine pointer). Addition, subtraction, and comparison
25292 operations are available in the standard Ada package
25293 @code{System.Storage_Elements}, or in package @code{System}
25294 if it is extended to include @code{System.Aux_DEC} using a
25295 pragma @code{Extend_System} as previously described.
25296
25297 Note that code that @code{with}'s both this extended package @code{System}
25298 and the package @code{System.Storage_Elements} should not @code{use}
25299 both packages, or ambiguities will result. In general it is better
25300 not to mix these two sets of facilities. The Ada package was
25301 designed specifically to provide the kind of features that HP Ada
25302 adds directly to package @code{System}.
25303
25304 The type @code{System.Address} is a 64-bit integer type in GNAT for
25305 I64 OpenVMS.  For more information,
25306 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
25307
25308 GNAT is compatible with HP Ada in its handling of address
25309 clauses, except for some limitations in
25310 the form of address clauses for composite objects with
25311 initialization. Such address clauses are easily replaced
25312 by the use of an explicitly-defined constant as described
25313 in the Ada Reference Manual (13.1(22)). For example, the sequence
25314 of declarations:
25315
25316 @smallexample @c ada
25317 @cartouche
25318 X, Y : Integer := Init_Func;
25319 Q : String (X .. Y) := "abc";
25320 @dots{}
25321 for Q'Address use Compute_Address;
25322 @end cartouche
25323 @end smallexample
25324
25325 @noindent
25326 will be rejected by GNAT, since the address cannot be computed at the time
25327 that @code{Q} is declared. To achieve the intended effect, write instead:
25328
25329 @smallexample @c ada
25330 @group
25331 @cartouche
25332 X, Y : Integer := Init_Func;
25333 Q_Address : constant Address := Compute_Address;
25334 Q : String (X .. Y) := "abc";
25335 @dots{}
25336 for Q'Address use Q_Address;
25337 @end cartouche
25338 @end group
25339 @end smallexample
25340
25341 @noindent
25342 which will be accepted by GNAT (and other Ada compilers), and is also
25343 compatible with Ada 83. A fuller description of the restrictions
25344 on address specifications is found in @ref{Top, GNAT Reference Manual,
25345 About This Guide, gnat_rm, GNAT Reference Manual}.
25346
25347 @node Other Representation Clauses
25348 @subsection Other Representation Clauses
25349
25350 @noindent
25351 GNAT implements in a compatible manner all the representation
25352 clauses supported by HP Ada. In addition, GNAT
25353 implements the representation clause forms that were introduced in Ada 95,
25354 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
25355
25356 @node The Package STANDARD
25357 @section The Package @code{STANDARD}
25358
25359 @noindent
25360 The package @code{STANDARD}, as implemented by HP Ada, is fully
25361 described in the @cite{Ada Reference Manual} and in the
25362 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
25363 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
25364
25365 In addition, HP Ada supports the Latin-1 character set in
25366 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
25367 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
25368 the type @code{WIDE_CHARACTER}.
25369
25370 The floating-point types supported by GNAT are those
25371 supported by HP Ada, but the defaults are different, and are controlled by
25372 pragmas. See @ref{Floating-Point Types and Representations}, for details.
25373
25374 @node The Package SYSTEM
25375 @section The Package @code{SYSTEM}
25376
25377 @noindent
25378 HP Ada provides a specific version of the package
25379 @code{SYSTEM} for each platform on which the language is implemented.
25380 For the complete spec of the package @code{SYSTEM}, see
25381 Appendix F of the @cite{HP Ada Language Reference Manual}.
25382
25383 On HP Ada, the package @code{SYSTEM} includes the following conversion
25384 functions:
25385 @itemize @bullet
25386 @item @code{TO_ADDRESS(INTEGER)}
25387
25388 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
25389
25390 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
25391
25392 @item @code{TO_INTEGER(ADDRESS)}
25393
25394 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
25395
25396 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
25397 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
25398 @end itemize
25399
25400 @noindent
25401 By default, GNAT supplies a version of @code{SYSTEM} that matches
25402 the definition given in the @cite{Ada Reference Manual}.
25403 This
25404 is a subset of the HP system definitions, which is as
25405 close as possible to the original definitions. The only difference
25406 is that the definition of @code{SYSTEM_NAME} is different:
25407
25408 @smallexample @c ada
25409 @cartouche
25410 type Name is (SYSTEM_NAME_GNAT);
25411 System_Name : constant Name := SYSTEM_NAME_GNAT;
25412 @end cartouche
25413 @end smallexample
25414
25415 @noindent
25416 Also, GNAT adds the Ada declarations for
25417 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
25418
25419 However, the use of the following pragma causes GNAT
25420 to extend the definition of package @code{SYSTEM} so that it
25421 encompasses the full set of HP-specific extensions,
25422 including the functions listed above:
25423
25424 @smallexample @c ada
25425 @cartouche
25426 pragma Extend_System (Aux_DEC);
25427 @end cartouche
25428 @end smallexample
25429
25430 @noindent
25431 The pragma @code{Extend_System} is a configuration pragma that
25432 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
25433 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
25434
25435 HP Ada does not allow the recompilation of the package
25436 @code{SYSTEM}. Instead HP Ada provides several pragmas
25437 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
25438 to modify values in the package @code{SYSTEM}.
25439 On OpenVMS Alpha systems, the pragma
25440 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
25441 its single argument.
25442
25443 GNAT does permit the recompilation of package @code{SYSTEM} using
25444 the special switch @option{-gnatg}, and this switch can be used if
25445 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
25446 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
25447 or @code{MEMORY_SIZE} by any other means.
25448
25449 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
25450 enumeration literal @code{SYSTEM_NAME_GNAT}.
25451
25452 The definitions provided by the use of
25453
25454 @smallexample @c ada
25455 pragma Extend_System (AUX_Dec);
25456 @end smallexample
25457
25458 @noindent
25459 are virtually identical to those provided by the HP Ada 83 package
25460 @code{SYSTEM}. One important difference is that the name of the
25461 @code{TO_ADDRESS}
25462 function for type @code{UNSIGNED_LONGWORD} is changed to
25463 @code{TO_ADDRESS_LONG}.
25464 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
25465 discussion of why this change was necessary.
25466
25467 @noindent
25468 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
25469 is in fact
25470 an extension to Ada 83 not strictly compatible with the reference manual.
25471 GNAT, in order to be exactly compatible with the standard,
25472 does not provide this capability. In HP Ada 83, the
25473 point of this definition is to deal with a call like:
25474
25475 @smallexample @c ada
25476 TO_ADDRESS (16#12777#);
25477 @end smallexample
25478
25479 @noindent
25480 Normally, according to Ada 83 semantics, one would expect this to be
25481 ambiguous, since it matches both the @code{INTEGER} and
25482 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
25483 However, in HP Ada 83, there is no ambiguity, since the
25484 definition using @i{universal_integer} takes precedence.
25485
25486 In GNAT, since the version with @i{universal_integer} cannot be supplied,
25487 it is
25488 not possible to be 100% compatible. Since there are many programs using
25489 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
25490 GNAT was
25491 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
25492 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
25493
25494 @smallexample @c ada
25495 function To_Address (X : Integer) return Address;
25496 pragma Pure_Function (To_Address);
25497
25498 function To_Address_Long (X : Unsigned_Longword) return Address;
25499 pragma Pure_Function (To_Address_Long);
25500 @end smallexample
25501
25502 @noindent
25503 This means that programs using @code{TO_ADDRESS} for
25504 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
25505
25506 @node Tasking and Task-Related Features
25507 @section Tasking and Task-Related Features
25508
25509 @noindent
25510 This section compares the treatment of tasking in GNAT
25511 and in HP Ada for OpenVMS Alpha.
25512 The GNAT description applies to both Alpha and I64 OpenVMS.
25513 For detailed information on tasking in
25514 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
25515 relevant run-time reference manual.
25516
25517 @menu
25518 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
25519 * Assigning Task IDs::
25520 * Task IDs and Delays::
25521 * Task-Related Pragmas::
25522 * Scheduling and Task Priority::
25523 * The Task Stack::
25524 * External Interrupts::
25525 @end menu
25526
25527 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25528 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25529
25530 @noindent
25531 On OpenVMS Alpha systems, each Ada task (except a passive
25532 task) is implemented as a single stream of execution
25533 that is created and managed by the kernel. On these
25534 systems, HP Ada tasking support is based on DECthreads,
25535 an implementation of the POSIX standard for threads.
25536
25537 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
25538 code that calls DECthreads routines can be used together.
25539 The interaction between Ada tasks and DECthreads routines
25540 can have some benefits. For example when on OpenVMS Alpha,
25541 HP Ada can call C code that is already threaded.
25542
25543 GNAT uses the facilities of DECthreads,
25544 and Ada tasks are mapped to threads.
25545
25546 @node Assigning Task IDs
25547 @subsection Assigning Task IDs
25548
25549 @noindent
25550 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
25551 the environment task that executes the main program. On
25552 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
25553 that have been created but are not yet activated.
25554
25555 On OpenVMS Alpha systems, task IDs are assigned at
25556 activation. On GNAT systems, task IDs are also assigned at
25557 task creation but do not have the same form or values as
25558 task ID values in HP Ada. There is no null task, and the
25559 environment task does not have a specific task ID value.
25560
25561 @node Task IDs and Delays
25562 @subsection Task IDs and Delays
25563
25564 @noindent
25565 On OpenVMS Alpha systems, tasking delays are implemented
25566 using Timer System Services. The Task ID is used for the
25567 identification of the timer request (the @code{REQIDT} parameter).
25568 If Timers are used in the application take care not to use
25569 @code{0} for the identification, because cancelling such a timer
25570 will cancel all timers and may lead to unpredictable results.
25571
25572 @node Task-Related Pragmas
25573 @subsection Task-Related Pragmas
25574
25575 @noindent
25576 Ada supplies the pragma @code{TASK_STORAGE}, which allows
25577 specification of the size of the guard area for a task
25578 stack. (The guard area forms an area of memory that has no
25579 read or write access and thus helps in the detection of
25580 stack overflow.) On OpenVMS Alpha systems, if the pragma
25581 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
25582 area is created. In the absence of a pragma @code{TASK_STORAGE},
25583 a default guard area is created.
25584
25585 GNAT supplies the following task-related pragmas:
25586
25587 @itemize @bullet
25588 @item  @code{TASK_INFO}
25589
25590 This pragma appears within a task definition and
25591 applies to the task in which it appears. The argument
25592 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
25593
25594 @item  @code{TASK_STORAGE}
25595
25596 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
25597 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
25598 @code{SUPPRESS}, and @code{VOLATILE}.
25599 @end itemize
25600 @node Scheduling and Task Priority
25601 @subsection Scheduling and Task Priority
25602
25603 @noindent
25604 HP Ada implements the Ada language requirement that
25605 when two tasks are eligible for execution and they have
25606 different priorities, the lower priority task does not
25607 execute while the higher priority task is waiting. The HP
25608 Ada Run-Time Library keeps a task running until either the
25609 task is suspended or a higher priority task becomes ready.
25610
25611 On OpenVMS Alpha systems, the default strategy is round-
25612 robin with preemption. Tasks of equal priority take turns
25613 at the processor. A task is run for a certain period of
25614 time and then placed at the tail of the ready queue for
25615 its priority level.
25616
25617 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
25618 which can be used to enable or disable round-robin
25619 scheduling of tasks with the same priority.
25620 See the relevant HP Ada run-time reference manual for
25621 information on using the pragmas to control HP Ada task
25622 scheduling.
25623
25624 GNAT follows the scheduling rules of Annex D (Real-Time
25625 Annex) of the @cite{Ada Reference Manual}. In general, this
25626 scheduling strategy is fully compatible with HP Ada
25627 although it provides some additional constraints (as
25628 fully documented in Annex D).
25629 GNAT implements time slicing control in a manner compatible with
25630 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
25631 are identical to the HP Ada 83 pragma of the same name.
25632 Note that it is not possible to mix GNAT tasking and
25633 HP Ada 83 tasking in the same program, since the two run-time
25634 libraries are not compatible.
25635
25636 @node The Task Stack
25637 @subsection The Task Stack
25638
25639 @noindent
25640 In HP Ada, a task stack is allocated each time a
25641 non-passive task is activated. As soon as the task is
25642 terminated, the storage for the task stack is deallocated.
25643 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
25644 a default stack size is used. Also, regardless of the size
25645 specified, some additional space is allocated for task
25646 management purposes. On OpenVMS Alpha systems, at least
25647 one page is allocated.
25648
25649 GNAT handles task stacks in a similar manner. In accordance with
25650 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
25651 an alternative method for controlling the task stack size.
25652 The specification of the attribute @code{T'STORAGE_SIZE} is also
25653 supported in a manner compatible with HP Ada.
25654
25655 @node External Interrupts
25656 @subsection External Interrupts
25657
25658 @noindent
25659 On HP Ada, external interrupts can be associated with task entries.
25660 GNAT is compatible with HP Ada in its handling of external interrupts.
25661
25662 @node Pragmas and Pragma-Related Features
25663 @section Pragmas and Pragma-Related Features
25664
25665 @noindent
25666 Both HP Ada and GNAT supply all language-defined pragmas
25667 as specified by the Ada 83 standard. GNAT also supplies all
25668 language-defined pragmas introduced by Ada 95 and Ada 2005.
25669 In addition, GNAT implements the implementation-defined pragmas
25670 from HP Ada 83.
25671
25672 @itemize @bullet
25673 @item  @code{AST_ENTRY}
25674
25675 @item  @code{COMMON_OBJECT}
25676
25677 @item  @code{COMPONENT_ALIGNMENT}
25678
25679 @item  @code{EXPORT_EXCEPTION}
25680
25681 @item  @code{EXPORT_FUNCTION}
25682
25683 @item  @code{EXPORT_OBJECT}
25684
25685 @item  @code{EXPORT_PROCEDURE}
25686
25687 @item  @code{EXPORT_VALUED_PROCEDURE}
25688
25689 @item  @code{FLOAT_REPRESENTATION}
25690
25691 @item  @code{IDENT}
25692
25693 @item  @code{IMPORT_EXCEPTION}
25694
25695 @item  @code{IMPORT_FUNCTION}
25696
25697 @item  @code{IMPORT_OBJECT}
25698
25699 @item  @code{IMPORT_PROCEDURE}
25700
25701 @item  @code{IMPORT_VALUED_PROCEDURE}
25702
25703 @item  @code{INLINE_GENERIC}
25704
25705 @item  @code{INTERFACE_NAME}
25706
25707 @item  @code{LONG_FLOAT}
25708
25709 @item  @code{MAIN_STORAGE}
25710
25711 @item  @code{PASSIVE}
25712
25713 @item  @code{PSECT_OBJECT}
25714
25715 @item  @code{SHARE_GENERIC}
25716
25717 @item  @code{SUPPRESS_ALL}
25718
25719 @item  @code{TASK_STORAGE}
25720
25721 @item  @code{TIME_SLICE}
25722
25723 @item  @code{TITLE}
25724 @end itemize
25725
25726 @noindent
25727 These pragmas are all fully implemented, with the exception of @code{TITLE},
25728 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
25729 recognized, but which have no
25730 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
25731 use of Ada protected objects. In GNAT, all generics are inlined.
25732
25733 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
25734 a separate subprogram specification which must appear before the
25735 subprogram body.
25736
25737 GNAT also supplies a number of implementation-defined pragmas as follows:
25738 @itemize @bullet
25739 @item  @code{ABORT_DEFER}
25740
25741 @item  @code{ADA_83}
25742
25743 @item  @code{ADA_95}
25744
25745 @item  @code{ADA_05}
25746
25747 @item  @code{ANNOTATE}
25748
25749 @item  @code{ASSERT}
25750
25751 @item  @code{C_PASS_BY_COPY}
25752
25753 @item  @code{CPP_CLASS}
25754
25755 @item  @code{CPP_CONSTRUCTOR}
25756
25757 @item  @code{CPP_DESTRUCTOR}
25758
25759 @item  @code{DEBUG}
25760
25761 @item  @code{EXTEND_SYSTEM}
25762
25763 @item  @code{LINKER_ALIAS}
25764
25765 @item  @code{LINKER_SECTION}
25766
25767 @item  @code{MACHINE_ATTRIBUTE}
25768
25769 @item  @code{NO_RETURN}
25770
25771 @item  @code{PURE_FUNCTION}
25772
25773 @item  @code{SOURCE_FILE_NAME}
25774
25775 @item  @code{SOURCE_REFERENCE}
25776
25777 @item  @code{TASK_INFO}
25778
25779 @item  @code{UNCHECKED_UNION}
25780
25781 @item  @code{UNIMPLEMENTED_UNIT}
25782
25783 @item  @code{UNIVERSAL_DATA}
25784
25785 @item  @code{UNSUPPRESS}
25786
25787 @item  @code{WARNINGS}
25788
25789 @item  @code{WEAK_EXTERNAL}
25790 @end itemize
25791
25792 @noindent
25793 For full details on these GNAT implementation-defined pragmas,
25794 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
25795 Manual}.
25796
25797 @menu
25798 * Restrictions on the Pragma INLINE::
25799 * Restrictions on the Pragma INTERFACE::
25800 * Restrictions on the Pragma SYSTEM_NAME::
25801 @end menu
25802
25803 @node Restrictions on the Pragma INLINE
25804 @subsection Restrictions on Pragma @code{INLINE}
25805
25806 @noindent
25807 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
25808 @itemize @bullet
25809 @item  Parameters cannot have a task type.
25810
25811 @item  Function results cannot be task types, unconstrained
25812 array types, or unconstrained types with discriminants.
25813
25814 @item  Bodies cannot declare the following:
25815 @itemize @bullet
25816 @item  Subprogram body or stub (imported subprogram is allowed)
25817
25818 @item  Tasks
25819
25820 @item  Generic declarations
25821
25822 @item  Instantiations
25823
25824 @item  Exceptions
25825
25826 @item  Access types (types derived from access types allowed)
25827
25828 @item  Array or record types
25829
25830 @item  Dependent tasks
25831
25832 @item  Direct recursive calls of subprogram or containing
25833 subprogram, directly or via a renaming
25834
25835 @end itemize
25836 @end itemize
25837
25838 @noindent
25839 In GNAT, the only restriction on pragma @code{INLINE} is that the
25840 body must occur before the call if both are in the same
25841 unit, and the size must be appropriately small. There are
25842 no other specific restrictions which cause subprograms to
25843 be incapable of being inlined.
25844
25845 @node  Restrictions on the Pragma INTERFACE
25846 @subsection  Restrictions on Pragma @code{INTERFACE}
25847
25848 @noindent
25849 The following restrictions on pragma @code{INTERFACE}
25850 are enforced by both HP Ada and GNAT:
25851 @itemize @bullet
25852 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
25853 Default is the default on OpenVMS Alpha systems.
25854
25855 @item  Parameter passing: Language specifies default
25856 mechanisms but can be overridden with an @code{EXPORT} pragma.
25857
25858 @itemize @bullet
25859 @item  Ada: Use internal Ada rules.
25860
25861 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
25862 record or task type. Result cannot be a string, an
25863 array, or a record.
25864
25865 @item  Fortran: Parameters cannot have a task type. Result cannot
25866 be a string, an array, or a record.
25867 @end itemize
25868 @end itemize
25869
25870 @noindent
25871 GNAT is entirely upwards compatible with HP Ada, and in addition allows
25872 record parameters for all languages.
25873
25874 @node  Restrictions on the Pragma SYSTEM_NAME
25875 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
25876
25877 @noindent
25878 For HP Ada for OpenVMS Alpha, the enumeration literal
25879 for the type @code{NAME} is @code{OPENVMS_AXP}.
25880 In GNAT, the enumeration
25881 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
25882
25883 @node  Library of Predefined Units
25884 @section  Library of Predefined Units
25885
25886 @noindent
25887 A library of predefined units is provided as part of the
25888 HP Ada and GNAT implementations. HP Ada does not provide
25889 the package @code{MACHINE_CODE} but instead recommends importing
25890 assembler code.
25891
25892 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
25893 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
25894 version.
25895 The HP Ada Predefined Library units are modified to remove post-Ada 83
25896 incompatibilities and to make them interoperable with GNAT
25897 (@pxref{Changes to DECLIB}, for details).
25898 The units are located in the @file{DECLIB} directory.
25899
25900 The GNAT RTL is contained in
25901 the @file{ADALIB} directory, and
25902 the default search path is set up to find @code{DECLIB} units in preference
25903 to @code{ADALIB} units with the same name (@code{TEXT_IO},
25904 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
25905
25906 @menu
25907 * Changes to DECLIB::
25908 @end menu
25909
25910 @node Changes to DECLIB
25911 @subsection Changes to @code{DECLIB}
25912
25913 @noindent
25914 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
25915 compatibility are minor and include the following:
25916
25917 @itemize @bullet
25918 @item  Adjusting the location of pragmas and record representation
25919 clauses to obey Ada 95 (and thus Ada 2005) rules
25920
25921 @item  Adding the proper notation to generic formal parameters
25922 that take unconstrained types in instantiation
25923
25924 @item  Adding pragma @code{ELABORATE_BODY} to package specs
25925 that have package bodies not otherwise allowed
25926
25927 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
25928 ``@code{PROTECTD}''.
25929 Currently these are found only in the @code{STARLET} package spec.
25930
25931 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
25932 where the address size is constrained to 32 bits.
25933 @end itemize
25934
25935 @noindent
25936 None of the above changes is visible to users.
25937
25938 @node Bindings
25939 @section Bindings
25940
25941 @noindent
25942 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
25943 @itemize @bullet
25944
25945 @item  Command Language Interpreter (CLI interface)
25946
25947 @item  DECtalk Run-Time Library (DTK interface)
25948
25949 @item  Librarian utility routines (LBR interface)
25950
25951 @item  General Purpose Run-Time Library (LIB interface)
25952
25953 @item  Math Run-Time Library (MTH interface)
25954
25955 @item  National Character Set Run-Time Library (NCS interface)
25956
25957 @item  Compiled Code Support Run-Time Library (OTS interface)
25958
25959 @item  Parallel Processing Run-Time Library (PPL interface)
25960
25961 @item  Screen Management Run-Time Library (SMG interface)
25962
25963 @item  Sort Run-Time Library (SOR interface)
25964
25965 @item  String Run-Time Library (STR interface)
25966
25967 @item STARLET System Library
25968 @findex Starlet
25969
25970 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
25971
25972 @item  X Windows Toolkit (XT interface)
25973
25974 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
25975 @end itemize
25976
25977 @noindent
25978 GNAT provides implementations of these HP bindings in the @code{DECLIB}
25979 directory, on both the Alpha and I64 OpenVMS platforms.
25980
25981 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
25982 in the
25983 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
25984 A pragma @code{Linker_Options} has been added to packages @code{Xm},
25985 @code{Xt}, and @code{X_Lib}
25986 causing the default X/Motif sharable image libraries to be linked in. This
25987 is done via options files named @file{xm.opt}, @file{xt.opt}, and
25988 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
25989
25990 It may be necessary to edit these options files to update or correct the
25991 library names if, for example, the newer X/Motif bindings from
25992 @file{ADA$EXAMPLES}
25993 had been (previous to installing GNAT) copied and renamed to supersede the
25994 default @file{ADA$PREDEFINED} versions.
25995
25996 @menu
25997 * Shared Libraries and Options Files::
25998 * Interfaces to C::
25999 @end menu
26000
26001 @node Shared Libraries and Options Files
26002 @subsection Shared Libraries and Options Files
26003
26004 @noindent
26005 When using the HP Ada
26006 predefined X and Motif bindings, the linking with their sharable images is
26007 done automatically by @command{GNAT LINK}.
26008 When using other X and Motif bindings, you need
26009 to add the corresponding sharable images to the command line for
26010 @code{GNAT LINK}. When linking with shared libraries, or with
26011 @file{.OPT} files, you must
26012 also add them to the command line for @command{GNAT LINK}.
26013
26014 A shared library to be used with GNAT is built in the same way as other
26015 libraries under VMS. The VMS Link command can be used in standard fashion.
26016
26017 @node Interfaces to C
26018 @subsection Interfaces to C
26019
26020 @noindent
26021 HP Ada
26022 provides the following Ada types and operations:
26023
26024 @itemize @bullet
26025 @item C types package (@code{C_TYPES})
26026
26027 @item C strings (@code{C_TYPES.NULL_TERMINATED})
26028
26029 @item Other_types (@code{SHORT_INT})
26030 @end itemize
26031
26032 @noindent
26033 Interfacing to C with GNAT, you can use the above approach
26034 described for HP Ada or the facilities of Annex B of
26035 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
26036 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
26037 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
26038
26039 The @option{-gnatF} qualifier forces default and explicit
26040 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
26041 to be uppercased for compatibility with the default behavior
26042 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
26043
26044 @node Main Program Definition
26045 @section Main Program Definition
26046
26047 @noindent
26048 The following section discusses differences in the
26049 definition of main programs on HP Ada and GNAT.
26050 On HP Ada, main programs are defined to meet the
26051 following conditions:
26052 @itemize @bullet
26053 @item  Procedure with no formal parameters (returns @code{0} upon
26054 normal completion)
26055
26056 @item  Procedure with no formal parameters (returns @code{42} when
26057 an unhandled exception is raised)
26058
26059 @item  Function with no formal parameters whose returned value
26060 is of a discrete type
26061
26062 @item  Procedure with one @code{out} formal of a discrete type for
26063 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
26064
26065 @end itemize
26066
26067 @noindent
26068 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
26069 a main function or main procedure returns a discrete
26070 value whose size is less than 64 bits (32 on VAX systems),
26071 the value is zero- or sign-extended as appropriate.
26072 On GNAT, main programs are defined as follows:
26073 @itemize @bullet
26074 @item  Must be a non-generic, parameterless subprogram that
26075 is either a procedure or function returning an Ada
26076 @code{STANDARD.INTEGER} (the predefined type)
26077
26078 @item  Cannot be a generic subprogram or an instantiation of a
26079 generic subprogram
26080 @end itemize
26081
26082 @node Implementation-Defined Attributes
26083 @section Implementation-Defined Attributes
26084
26085 @noindent
26086 GNAT provides all HP Ada implementation-defined
26087 attributes.
26088
26089 @node Compiler and Run-Time Interfacing
26090 @section Compiler and Run-Time Interfacing
26091
26092 @noindent
26093 HP Ada provides the following qualifiers to pass options to the linker
26094 (ACS LINK):
26095 @itemize @bullet
26096 @item  @option{/WAIT} and @option{/SUBMIT}
26097
26098 @item  @option{/COMMAND}
26099
26100 @item  @option{/@r{[}NO@r{]}MAP}
26101
26102 @item  @option{/OUTPUT=@var{file-spec}}
26103
26104 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26105 @end itemize
26106
26107 @noindent
26108 To pass options to the linker, GNAT provides the following
26109 switches:
26110
26111 @itemize @bullet
26112 @item   @option{/EXECUTABLE=@var{exec-name}}
26113
26114 @item   @option{/VERBOSE}
26115
26116 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26117 @end itemize
26118
26119 @noindent
26120 For more information on these switches, see
26121 @ref{Switches for gnatlink}.
26122 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
26123 to control optimization. HP Ada also supplies the
26124 following pragmas:
26125 @itemize @bullet
26126 @item  @code{OPTIMIZE}
26127
26128 @item  @code{INLINE}
26129
26130 @item  @code{INLINE_GENERIC}
26131
26132 @item  @code{SUPPRESS_ALL}
26133
26134 @item  @code{PASSIVE}
26135 @end itemize
26136
26137 @noindent
26138 In GNAT, optimization is controlled strictly by command
26139 line parameters, as described in the corresponding section of this guide.
26140 The HP pragmas for control of optimization are
26141 recognized but ignored.
26142
26143 Note that in GNAT, the default is optimization off, whereas in HP Ada
26144 the default is that optimization is turned on.
26145
26146 @node Program Compilation and Library Management
26147 @section Program Compilation and Library Management
26148
26149 @noindent
26150 HP Ada and GNAT provide a comparable set of commands to
26151 build programs. HP Ada also provides a program library,
26152 which is a concept that does not exist on GNAT. Instead,
26153 GNAT provides directories of sources that are compiled as
26154 needed.
26155
26156 The following table summarizes
26157 the HP Ada commands and provides
26158 equivalent GNAT commands. In this table, some GNAT
26159 equivalents reflect the fact that GNAT does not use the
26160 concept of a program library. Instead, it uses a model
26161 in which collections of source and object files are used
26162 in a manner consistent with other languages like C and
26163 Fortran. Therefore, standard system file commands are used
26164 to manipulate these elements. Those GNAT commands are marked with
26165 an asterisk.
26166 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
26167
26168 @need 1500
26169 @multitable @columnfractions .35 .65
26170
26171 @item @emph{HP Ada Command}
26172 @tab @emph{GNAT Equivalent / Description}
26173
26174 @item @command{ADA}
26175 @tab @command{GNAT COMPILE}@*
26176 Invokes the compiler to compile one or more Ada source files.
26177
26178 @item @command{ACS ATTACH}@*
26179 @tab [No equivalent]@*
26180 Switches control of terminal from current process running the program
26181 library manager.
26182
26183 @item @command{ACS CHECK}
26184 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
26185 Forms the execution closure of one
26186 or more compiled units and checks completeness and currency.
26187
26188 @item @command{ACS COMPILE}
26189 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26190 Forms the execution closure of one or
26191 more specified units, checks completeness and currency,
26192 identifies units that have revised source files, compiles same,
26193 and recompiles units that are or will become obsolete.
26194 Also completes incomplete generic instantiations.
26195
26196 @item @command{ACS COPY FOREIGN}
26197 @tab Copy (*)@*
26198 Copies a foreign object file into the program library as a
26199 library unit body.
26200
26201 @item @command{ACS COPY UNIT}
26202 @tab Copy (*)@*
26203 Copies a compiled unit from one program library to another.
26204
26205 @item @command{ACS CREATE LIBRARY}
26206 @tab Create /directory (*)@*
26207 Creates a program library.
26208
26209 @item @command{ACS CREATE SUBLIBRARY}
26210 @tab Create /directory (*)@*
26211 Creates a program sublibrary.
26212
26213 @item @command{ACS DELETE LIBRARY}
26214 @tab @*
26215 Deletes a program library and its contents.
26216
26217 @item @command{ACS DELETE SUBLIBRARY}
26218 @tab @*
26219 Deletes a program sublibrary and its contents.
26220
26221 @item @command{ACS DELETE UNIT}
26222 @tab Delete file (*)@*
26223 On OpenVMS systems, deletes one or more compiled units from
26224 the current program library.
26225
26226 @item @command{ACS DIRECTORY}
26227 @tab Directory (*)@*
26228 On OpenVMS systems, lists units contained in the current
26229 program library.
26230
26231 @item @command{ACS ENTER FOREIGN}
26232 @tab Copy (*)@*
26233 Allows the import of a foreign body as an Ada library
26234 spec and enters a reference to a pointer.
26235
26236 @item @command{ACS ENTER UNIT}
26237 @tab Copy (*)@*
26238 Enters a reference (pointer) from the current program library to
26239 a unit compiled into another program library.
26240
26241 @item @command{ACS EXIT}
26242 @tab [No equivalent]@*
26243 Exits from the program library manager.
26244
26245 @item @command{ACS EXPORT}
26246 @tab Copy (*)@*
26247 Creates an object file that contains system-specific object code
26248 for one or more units. With GNAT, object files can simply be copied
26249 into the desired directory.
26250
26251 @item @command{ACS EXTRACT SOURCE}
26252 @tab Copy (*)@*
26253 Allows access to the copied source file for each Ada compilation unit
26254
26255 @item @command{ACS HELP}
26256 @tab @command{HELP GNAT}@*
26257 Provides online help.
26258
26259 @item @command{ACS LINK}
26260 @tab @command{GNAT LINK}@*
26261 Links an object file containing Ada units into an executable file.
26262
26263 @item @command{ACS LOAD}
26264 @tab Copy (*)@*
26265 Loads (partially compiles) Ada units into the program library.
26266 Allows loading a program from a collection of files into a library
26267 without knowing the relationship among units.
26268
26269 @item @command{ACS MERGE}
26270 @tab Copy (*)@*
26271 Merges into the current program library, one or more units from
26272 another library where they were modified.
26273
26274 @item @command{ACS RECOMPILE}
26275 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26276 Recompiles from   external or copied source files any obsolete
26277 unit in the closure. Also, completes any incomplete generic
26278 instantiations.
26279
26280 @item @command{ACS REENTER}
26281 @tab @command{GNAT MAKE}@*
26282 Reenters current references to units compiled after last entered
26283 with the @command{ACS ENTER UNIT} command.
26284
26285 @item @command{ACS SET LIBRARY}
26286 @tab Set default (*)@*
26287 Defines a program library to be the compilation context as well
26288 as the target library for compiler output and commands in general.
26289
26290 @item @command{ACS SET PRAGMA}
26291 @tab Edit @file{gnat.adc} (*)@*
26292 Redefines specified  values of the library characteristics
26293 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
26294 and @code{Float_Representation}.
26295
26296 @item @command{ACS SET SOURCE}
26297 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
26298 Defines the source file search list for the @command{ACS COMPILE} command.
26299
26300 @item @command{ACS SHOW LIBRARY}
26301 @tab Directory (*)@*
26302 Lists information about one or more program libraries.
26303
26304 @item @command{ACS SHOW PROGRAM}
26305 @tab [No equivalent]@*
26306 Lists information about the execution closure of one or
26307 more units in the program library.
26308
26309 @item @command{ACS SHOW SOURCE}
26310 @tab Show logical @code{ADA_INCLUDE_PATH}@*
26311 Shows the source file search used when compiling units.
26312
26313 @item @command{ACS SHOW VERSION}
26314 @tab Compile with @option{VERBOSE} option
26315 Displays the version number of the compiler and program library
26316 manager used.
26317
26318 @item @command{ACS SPAWN}
26319 @tab [No equivalent]@*
26320 Creates a subprocess of the current process (same as @command{DCL SPAWN}
26321 command).
26322
26323 @item @command{ACS VERIFY}
26324 @tab [No equivalent]@*
26325 Performs a series of consistency checks on a program library to
26326 determine whether the library structure and library files are in
26327 valid form.
26328 @end multitable
26329
26330 @noindent
26331
26332 @node Input-Output
26333 @section Input-Output
26334
26335 @noindent
26336 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
26337 Management Services (RMS) to perform operations on
26338 external files.
26339
26340 @noindent
26341 HP Ada and GNAT predefine an identical set of input-
26342 output packages. To make the use of the
26343 generic @code{TEXT_IO} operations more convenient, HP Ada
26344 provides predefined library packages that instantiate the
26345 integer and floating-point operations for the predefined
26346 integer and floating-point types as shown in the following table.
26347
26348 @multitable @columnfractions .45 .55
26349 @item @emph{Package Name} @tab Instantiation
26350
26351 @item @code{INTEGER_TEXT_IO}
26352 @tab @code{INTEGER_IO(INTEGER)}
26353
26354 @item @code{SHORT_INTEGER_TEXT_IO}
26355 @tab @code{INTEGER_IO(SHORT_INTEGER)}
26356
26357 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
26358 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
26359
26360 @item @code{FLOAT_TEXT_IO}
26361 @tab @code{FLOAT_IO(FLOAT)}
26362
26363 @item @code{LONG_FLOAT_TEXT_IO}
26364 @tab @code{FLOAT_IO(LONG_FLOAT)}
26365 @end multitable
26366
26367 @noindent
26368 The HP Ada predefined packages and their operations
26369 are implemented using OpenVMS Alpha files and input-output
26370 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
26371 Familiarity with the following is recommended:
26372 @itemize @bullet
26373 @item  RMS file organizations and access methods
26374
26375 @item  OpenVMS file specifications and directories
26376
26377 @item  OpenVMS File Definition Language (FDL)
26378 @end itemize
26379
26380 @noindent
26381 GNAT provides I/O facilities that are completely
26382 compatible with HP Ada. The distribution includes the
26383 standard HP Ada versions of all I/O packages, operating
26384 in a manner compatible with HP Ada. In particular, the
26385 following packages are by default the HP Ada (Ada 83)
26386 versions of these packages rather than the renamings
26387 suggested in Annex J of the Ada Reference Manual:
26388 @itemize @bullet
26389 @item  @code{TEXT_IO}
26390
26391 @item  @code{SEQUENTIAL_IO}
26392
26393 @item  @code{DIRECT_IO}
26394 @end itemize
26395
26396 @noindent
26397 The use of the standard child package syntax (for
26398 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
26399 packages.
26400 GNAT provides HP-compatible predefined instantiations
26401 of the @code{TEXT_IO} packages, and also
26402 provides the standard predefined instantiations required
26403 by the @cite{Ada Reference Manual}.
26404
26405 For further information on how GNAT interfaces to the file
26406 system or how I/O is implemented in programs written in
26407 mixed languages, see @ref{Implementation of the Standard I/O,,,
26408 gnat_rm, GNAT Reference Manual}.
26409 This chapter covers the following:
26410 @itemize @bullet
26411 @item  Standard I/O packages
26412
26413 @item  @code{FORM} strings
26414
26415 @item  @code{ADA.DIRECT_IO}
26416
26417 @item  @code{ADA.SEQUENTIAL_IO}
26418
26419 @item  @code{ADA.TEXT_IO}
26420
26421 @item  Stream pointer positioning
26422
26423 @item  Reading and writing non-regular files
26424
26425 @item  @code{GET_IMMEDIATE}
26426
26427 @item  Treating @code{TEXT_IO} files as streams
26428
26429 @item  Shared files
26430
26431 @item  Open modes
26432 @end itemize
26433
26434 @node Implementation Limits
26435 @section Implementation Limits
26436
26437 @noindent
26438 The following table lists implementation limits for HP Ada
26439 and GNAT systems.
26440 @multitable @columnfractions .60 .20 .20
26441 @sp 1
26442 @item  @emph{Compilation Parameter}
26443 @tab   @emph{HP Ada}
26444 @tab   @emph{GNAT}
26445 @sp 1
26446
26447 @item  In a subprogram or entry  declaration, maximum number of
26448 formal parameters that are of an unconstrained record type
26449 @tab   32
26450 @tab   No set limit
26451 @sp 1
26452
26453 @item  Maximum identifier length (number of characters)
26454 @tab   255
26455 @tab   32766
26456 @sp 1
26457
26458 @item  Maximum number of characters in a source line
26459 @tab   255
26460 @tab   32766
26461 @sp 1
26462
26463 @item  Maximum collection size   (number of bytes)
26464 @tab   2**31-1
26465 @tab   2**31-1
26466 @sp 1
26467
26468 @item  Maximum number of discriminants for a record type
26469 @tab   245
26470 @tab   No set limit
26471 @sp 1
26472
26473 @item  Maximum number of formal parameters in an entry or
26474 subprogram declaration
26475 @tab   246
26476 @tab    No set limit
26477 @sp 1
26478
26479 @item  Maximum number of dimensions in an array type
26480 @tab   255
26481 @tab   No set limit
26482 @sp 1
26483
26484 @item  Maximum number of library  units and subunits in a compilation.
26485 @tab   4095
26486 @tab   No set limit
26487 @sp 1
26488
26489 @item  Maximum number of library units and subunits in an execution.
26490 @tab   16383
26491 @tab   No set limit
26492 @sp 1
26493
26494 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
26495 or @code{PSECT_OBJECT}
26496 @tab   32757
26497 @tab   No set limit
26498 @sp 1
26499
26500 @item  Maximum number of enumeration literals in an enumeration type
26501 definition
26502 @tab   65535
26503 @tab   No set limit
26504 @sp 1
26505
26506 @item  Maximum number of lines in a source file
26507 @tab   65534
26508 @tab   No set limit
26509 @sp 1
26510
26511 @item  Maximum number of bits in any object
26512 @tab   2**31-1
26513 @tab   2**31-1
26514 @sp 1
26515
26516 @item  Maximum size of the static portion of a stack frame (approximate)
26517 @tab   2**31-1
26518 @tab   2**31-1
26519 @end multitable
26520
26521 @node Tools and Utilities
26522 @section Tools and Utilities
26523
26524 @noindent
26525 The following table lists some of the OpenVMS development tools
26526 available for HP Ada, and the corresponding tools for
26527 use with @value{EDITION} on Alpha and I64 platforms.
26528 Aside from the debugger, all the OpenVMS tools identified are part
26529 of the DECset package.
26530
26531 @iftex
26532 @c Specify table in TeX since Texinfo does a poor job
26533 @tex
26534 \smallskip
26535 \smallskip
26536 \settabs\+Language-Sensitive Editor\quad
26537    &Product with HP Ada\quad
26538    &\cr
26539 \+\it Tool
26540    &\it Product with HP Ada
26541    & \it Product with GNAT Pro\cr
26542 \smallskip
26543 \+Code Management System
26544    &HP CMS
26545    & HP CMS\cr
26546 \smallskip
26547 \+Language-Sensitive Editor
26548    &HP LSE
26549    & emacs or HP LSE (Alpha)\cr
26550 \+
26551    &
26552    & HP LSE (I64)\cr
26553 \smallskip
26554 \+Debugger
26555    &OpenVMS Debug
26556    & gdb (Alpha),\cr
26557 \+
26558    &
26559    & OpenVMS Debug (I64)\cr
26560 \smallskip
26561 \+Source Code Analyzer /
26562    &HP SCA
26563    & GNAT XREF\cr
26564 \+Cross Referencer
26565    &
26566    &\cr
26567 \smallskip
26568 \+Test Manager
26569    &HP Digital Test
26570    & HP DTM\cr
26571 \+
26572    &Manager (DTM)
26573    &\cr
26574 \smallskip
26575 \+Performance and
26576    & HP PCA
26577    & HP PCA\cr
26578 \+Coverage Analyzer
26579    &
26580    &\cr
26581 \smallskip
26582 \+Module Management
26583    & HP MMS
26584    & Not applicable\cr
26585 \+ System
26586    &
26587    &\cr
26588 \smallskip
26589 \smallskip
26590 @end tex
26591 @end iftex
26592
26593 @ifnottex
26594 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
26595 @c the TeX version above for the printed version
26596 @flushleft
26597 @c @multitable @columnfractions .3 .4 .4
26598 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
26599 @item @i{Tool}
26600 @tab @i{Tool with HP Ada}
26601 @tab @i{Tool with @value{EDITION}}
26602 @item Code Management@*System
26603 @tab HP CMS
26604 @tab HP CMS
26605 @item Language-Sensitive@*Editor
26606 @tab HP LSE
26607 @tab emacs or HP LSE (Alpha)
26608 @item
26609 @tab
26610 @tab HP LSE (I64)
26611 @item Debugger
26612 @tab OpenVMS Debug
26613 @tab gdb (Alpha),
26614 @item
26615 @tab
26616 @tab OpenVMS Debug (I64)
26617 @item Source Code Analyzer /@*Cross Referencer
26618 @tab HP SCA
26619 @tab GNAT XREF
26620 @item Test Manager
26621 @tab HP Digital Test@*Manager (DTM)
26622 @tab HP DTM
26623 @item Performance and@*Coverage Analyzer
26624 @tab HP PCA
26625 @tab HP PCA
26626 @item Module Management@*System
26627 @tab HP MMS
26628 @tab Not applicable
26629 @end multitable
26630 @end flushleft
26631 @end ifnottex
26632
26633 @end ifset
26634
26635 @c **************************************
26636 @node Platform-Specific Information for the Run-Time Libraries
26637 @appendix Platform-Specific Information for the Run-Time Libraries
26638 @cindex Tasking and threads libraries
26639 @cindex Threads libraries and tasking
26640 @cindex Run-time libraries (platform-specific information)
26641
26642 @noindent
26643 The GNAT run-time implementation may vary with respect to both the
26644 underlying threads library and the exception handling scheme.
26645 For threads support, one or more of the following are supplied:
26646 @itemize @bullet
26647 @item @b{native threads library}, a binding to the thread package from
26648 the underlying operating system
26649
26650 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
26651 POSIX thread package
26652 @end itemize
26653
26654 @noindent
26655 For exception handling, either or both of two models are supplied:
26656 @itemize @bullet
26657 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
26658 Most programs should experience a substantial speed improvement by
26659 being compiled with a ZCX run-time.
26660 This is especially true for
26661 tasking applications or applications with many exception handlers.}
26662 @cindex Zero-Cost Exceptions
26663 @cindex ZCX (Zero-Cost Exceptions)
26664 which uses binder-generated tables that
26665 are interrogated at run time to locate a handler
26666
26667 @item @b{setjmp / longjmp} (``SJLJ''),
26668 @cindex setjmp/longjmp Exception Model
26669 @cindex SJLJ (setjmp/longjmp Exception Model)
26670 which uses dynamically-set data to establish
26671 the set of handlers
26672 @end itemize
26673
26674 @noindent
26675 This appendix summarizes which combinations of threads and exception support
26676 are supplied on various GNAT platforms.
26677 It then shows how to select a particular library either
26678 permanently or temporarily,
26679 explains the properties of (and tradeoffs among) the various threads
26680 libraries, and provides some additional
26681 information about several specific platforms.
26682
26683 @menu
26684 * Summary of Run-Time Configurations::
26685 * Specifying a Run-Time Library::
26686 * Choosing the Scheduling Policy::
26687 * Solaris-Specific Considerations::
26688 * Linux-Specific Considerations::
26689 * AIX-Specific Considerations::
26690 * Irix-Specific Considerations::
26691 * RTX-Specific Considerations::
26692 @end menu
26693
26694 @node Summary of Run-Time Configurations
26695 @section Summary of Run-Time Configurations
26696
26697 @multitable @columnfractions .30 .70
26698 @item @b{alpha-openvms}
26699 @item @code{@ @ }@i{rts-native (default)}
26700 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26701 @item @code{@ @ @ @ }Exceptions @tab ZCX
26702 @*
26703 @item @b{alpha-tru64}
26704 @item @code{@ @ }@i{rts-native (default)}
26705 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26706 @item @code{@ @ @ @ }Exceptions @tab ZCX
26707 @*
26708 @item @code{@ @ }@i{rts-sjlj}
26709 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26710 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26711 @*
26712 @item @b{ia64-hp_linux}
26713 @item @code{@ @ }@i{rts-native (default)}
26714 @item @code{@ @ @ @ }Tasking    @tab pthread library
26715 @item @code{@ @ @ @ }Exceptions @tab ZCX
26716 @*
26717 @item @b{ia64-hpux}
26718 @item @code{@ @ }@i{rts-native (default)}
26719 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26720 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26721 @*
26722 @item @b{ia64-openvms}
26723 @item @code{@ @ }@i{rts-native (default)}
26724 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26725 @item @code{@ @ @ @ }Exceptions @tab ZCX
26726 @*
26727 @item @b{ia64-sgi_linux}
26728 @item @code{@ @ }@i{rts-native (default)}
26729 @item @code{@ @ @ @ }Tasking    @tab pthread library
26730 @item @code{@ @ @ @ }Exceptions @tab ZCX
26731 @*
26732 @item @b{mips-irix}
26733 @item @code{@ @ }@i{rts-native (default)}
26734 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
26735 @item @code{@ @ @ @ }Exceptions @tab ZCX
26736 @*
26737 @item @b{pa-hpux}
26738 @item @code{@ @ }@i{rts-native (default)}
26739 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26740 @item @code{@ @ @ @ }Exceptions @tab ZCX
26741 @*
26742 @item @code{@ @ }@i{rts-sjlj}
26743 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26744 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26745 @*
26746 @item @b{ppc-aix}
26747 @item @code{@ @ }@i{rts-native (default)}
26748 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
26749 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26750 @*
26751 @item @b{ppc-darwin}
26752 @item @code{@ @ }@i{rts-native (default)}
26753 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
26754 @item @code{@ @ @ @ }Exceptions @tab ZCX
26755 @*
26756 @item @b{sparc-solaris}  @tab
26757 @item @code{@ @ }@i{rts-native (default)}
26758 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26759 @item @code{@ @ @ @ }Exceptions @tab ZCX
26760 @*
26761 @item @code{@ @ }@i{rts-pthread}
26762 @item @code{@ @ @ @ }Tasking    @tab pthread library
26763 @item @code{@ @ @ @ }Exceptions @tab ZCX
26764 @*
26765 @item @code{@ @ }@i{rts-sjlj}
26766 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26767 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26768 @*
26769 @item @b{sparc64-solaris}  @tab
26770 @item @code{@ @ }@i{rts-native (default)}
26771 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26772 @item @code{@ @ @ @ }Exceptions @tab ZCX
26773 @*
26774 @item @b{x86-linux}
26775 @item @code{@ @ }@i{rts-native (default)}
26776 @item @code{@ @ @ @ }Tasking    @tab pthread library
26777 @item @code{@ @ @ @ }Exceptions @tab ZCX
26778 @*
26779 @item @code{@ @ }@i{rts-sjlj}
26780 @item @code{@ @ @ @ }Tasking    @tab pthread library
26781 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26782 @*
26783 @item @b{x86-lynx}
26784 @item @code{@ @ }@i{rts-native (default)}
26785 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
26786 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26787 @*
26788 @item @b{x86-solaris}
26789 @item @code{@ @ }@i{rts-native (default)}
26790 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
26791 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26792 @*
26793 @item @b{x86-windows}
26794 @item @code{@ @ }@i{rts-native (default)}
26795 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
26796 @item @code{@ @ @ @ }Exceptions @tab ZCX
26797 @*
26798 @item @code{@ @ }@i{rts-sjlj (default)}
26799 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
26800 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26801 @*
26802 @item @b{x86-windows-rtx}
26803 @item @code{@ @ }@i{rts-rtx-rtss (default)}
26804 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
26805 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26806 @*
26807 @item @code{@ @ }@i{rts-rtx-w32}
26808 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
26809 @item @code{@ @ @ @ }Exceptions @tab ZCX
26810 @*
26811 @item @b{x86_64-linux}
26812 @item @code{@ @ }@i{rts-native (default)}
26813 @item @code{@ @ @ @ }Tasking    @tab pthread library
26814 @item @code{@ @ @ @ }Exceptions @tab ZCX
26815 @*
26816 @item @code{@ @ }@i{rts-sjlj}
26817 @item @code{@ @ @ @ }Tasking    @tab pthread library
26818 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26819 @*
26820 @end multitable
26821
26822 @node Specifying a Run-Time Library
26823 @section Specifying a Run-Time Library
26824
26825 @noindent
26826 The @file{adainclude} subdirectory containing the sources of the GNAT
26827 run-time library, and the @file{adalib} subdirectory containing the
26828 @file{ALI} files and the static and/or shared GNAT library, are located
26829 in the gcc target-dependent area:
26830
26831 @smallexample
26832 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
26833 @end smallexample
26834
26835 @noindent
26836 As indicated above, on some platforms several run-time libraries are supplied.
26837 These libraries are installed in the target dependent area and
26838 contain a complete source and binary subdirectory. The detailed description
26839 below explains the differences between the different libraries in terms of
26840 their thread support.
26841
26842 The default run-time library (when GNAT is installed) is @emph{rts-native}.
26843 This default run time is selected by the means of soft links.
26844 For example on x86-linux:
26845
26846 @smallexample
26847 @group
26848  $(target-dir)
26849      |
26850      +--- adainclude----------+
26851      |                        |
26852      +--- adalib-----------+  |
26853      |                     |  |
26854      +--- rts-native       |  |
26855      |    |                |  |
26856      |    +--- adainclude <---+
26857      |    |                |
26858      |    +--- adalib <----+
26859      |
26860      +--- rts-sjlj
26861           |
26862           +--- adainclude
26863           |
26864           +--- adalib
26865 @end group
26866 @end smallexample
26867
26868 @noindent
26869 If the @i{rts-sjlj} library is to be selected on a permanent basis,
26870 these soft links can be modified with the following commands:
26871
26872 @smallexample
26873 $ cd $target
26874 $ rm -f adainclude adalib
26875 $ ln -s rts-sjlj/adainclude adainclude
26876 $ ln -s rts-sjlj/adalib adalib
26877 @end smallexample
26878
26879 @noindent
26880 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
26881 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
26882 @file{$target/ada_object_path}.
26883
26884 Selecting another run-time library temporarily can be
26885 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
26886 @cindex @option{--RTS} option
26887
26888 @node Choosing the Scheduling Policy
26889 @section Choosing the Scheduling Policy
26890
26891 @noindent
26892 When using a POSIX threads implementation, you have a choice of several
26893 scheduling policies: @code{SCHED_FIFO},
26894 @cindex @code{SCHED_FIFO} scheduling policy
26895 @code{SCHED_RR}
26896 @cindex @code{SCHED_RR} scheduling policy
26897 and @code{SCHED_OTHER}.
26898 @cindex @code{SCHED_OTHER} scheduling policy
26899 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
26900 or @code{SCHED_RR} requires special (e.g., root) privileges.
26901
26902 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
26903 @code{SCHED_FIFO},
26904 @cindex @code{SCHED_FIFO} scheduling policy
26905 you can use one of the following:
26906
26907 @itemize @bullet
26908 @item
26909 @code{pragma Time_Slice (0.0)}
26910 @cindex pragma Time_Slice
26911 @item
26912 the corresponding binder option @option{-T0}
26913 @cindex @option{-T0} option
26914 @item
26915 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
26916 @cindex pragma Task_Dispatching_Policy
26917 @end itemize
26918
26919 @noindent
26920 To specify @code{SCHED_RR},
26921 @cindex @code{SCHED_RR} scheduling policy
26922 you should use @code{pragma Time_Slice} with a
26923 value greater than @code{0.0}, or else use the corresponding @option{-T}
26924 binder option.
26925
26926 @node Solaris-Specific Considerations
26927 @section Solaris-Specific Considerations
26928 @cindex Solaris Sparc threads libraries
26929
26930 @noindent
26931 This section addresses some topics related to the various threads libraries
26932 on Sparc Solaris.
26933
26934 @menu
26935 * Solaris Threads Issues::
26936 @end menu
26937
26938 @node Solaris Threads Issues
26939 @subsection Solaris Threads Issues
26940
26941 @noindent
26942 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
26943 library based on POSIX threads --- @emph{rts-pthread}.
26944 @cindex rts-pthread threads library
26945 This run-time library has the advantage of being mostly shared across all
26946 POSIX-compliant thread implementations, and it also provides under
26947 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
26948 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
26949 and @code{PTHREAD_PRIO_PROTECT}
26950 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
26951 semantics that can be selected using the predefined pragma
26952 @code{Locking_Policy}
26953 @cindex pragma Locking_Policy (under rts-pthread)
26954 with respectively
26955 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
26956 @cindex @code{Inheritance_Locking} (under rts-pthread)
26957 @cindex @code{Ceiling_Locking} (under rts-pthread)
26958
26959 As explained above, the native run-time library is based on the Solaris thread
26960 library (@code{libthread}) and is the default library.
26961
26962 When the Solaris threads library is used (this is the default), programs
26963 compiled with GNAT can automatically take advantage of
26964 and can thus execute on multiple processors.
26965 The user can alternatively specify a processor on which the program should run
26966 to emulate a single-processor system. The multiprocessor / uniprocessor choice
26967 is made by
26968 setting the environment variable @env{GNAT_PROCESSOR}
26969 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
26970 to one of the following:
26971
26972 @table @code
26973 @item -2
26974 Use the default configuration (run the program on all
26975 available processors) - this is the same as having @code{GNAT_PROCESSOR}
26976 unset
26977
26978 @item -1
26979 Let the run-time implementation choose one processor and run the program on
26980 that processor
26981
26982 @item 0 .. Last_Proc
26983 Run the program on the specified processor.
26984 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
26985 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
26986 @end table
26987
26988 @node Linux-Specific Considerations
26989 @section Linux-Specific Considerations
26990 @cindex Linux threads libraries
26991
26992 @noindent
26993 On GNU/Linux without NPTL support (usually system with GNU C Library
26994 older than 2.3), the signal model is not POSIX compliant, which means
26995 that to send a signal to the process, you need to send the signal to all
26996 threads, e.g.@: by using @code{killpg()}.
26997
26998 @node AIX-Specific Considerations
26999 @section AIX-Specific Considerations
27000 @cindex AIX resolver library
27001
27002 @noindent
27003 On AIX, the resolver library initializes some internal structure on
27004 the first call to @code{get*by*} functions, which are used to implement
27005 @code{GNAT.Sockets.Get_Host_By_Name} and
27006 @code{GNAT.Sockets.Get_Host_By_Address}.
27007 If such initialization occurs within an Ada task, and the stack size for
27008 the task is the default size, a stack overflow may occur.
27009
27010 To avoid this overflow, the user should either ensure that the first call
27011 to @code{GNAT.Sockets.Get_Host_By_Name} or
27012 @code{GNAT.Sockets.Get_Host_By_Addrss}
27013 occurs in the environment task, or use @code{pragma Storage_Size} to
27014 specify a sufficiently large size for the stack of the task that contains
27015 this call.
27016
27017 @node Irix-Specific Considerations
27018 @section Irix-Specific Considerations
27019 @cindex Irix libraries
27020
27021 @noindent
27022 The GCC support libraries coming with the Irix compiler have moved to
27023 their canonical place with respect to the general Irix ABI related
27024 conventions. Running applications built with the default shared GNAT
27025 run-time now requires the LD_LIBRARY_PATH environment variable to
27026 include this location. A possible way to achieve this is to issue the
27027 following command line on a bash prompt:
27028
27029 @smallexample
27030 @group
27031 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
27032 @end group
27033 @end smallexample
27034
27035 @node RTX-Specific Considerations
27036 @section RTX-Specific Considerations
27037 @cindex RTX libraries
27038
27039 @noindent
27040 The Real-time Extension (RTX) to Windows is based on the Windows Win32
27041 API. Applications can be built to work in two different modes:
27042
27043 @itemize @bullet
27044 @item
27045 Windows executables that run in Ring 3 to utilize memory protection
27046 (@emph{rts-rtx-w32}).
27047
27048 @item
27049 Real-time subsystem (RTSS) executables that run in Ring 0, where
27050 performance can be optimized with RTSS applications taking precedent
27051 over all Windows applications (@emph{rts-rtx-rtss}).
27052
27053 @end itemize
27054
27055 @c *******************************
27056 @node Example of Binder Output File
27057 @appendix Example of Binder Output File
27058
27059 @noindent
27060 This Appendix displays the source code for @command{gnatbind}'s output
27061 file generated for a simple ``Hello World'' program.
27062 Comments have been added for clarification purposes.
27063
27064 @smallexample @c adanocomment
27065 @iftex
27066 @leftskip=0cm
27067 @end iftex
27068 --  The package is called Ada_Main unless this name is actually used
27069 --  as a unit name in the partition, in which case some other unique
27070 --  name is used.
27071
27072 with System;
27073 package ada_main is
27074
27075    Elab_Final_Code : Integer;
27076    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
27077
27078    --  The main program saves the parameters (argument count,
27079    --  argument values, environment pointer) in global variables
27080    --  for later access by other units including
27081    --  Ada.Command_Line.
27082
27083    gnat_argc : Integer;
27084    gnat_argv : System.Address;
27085    gnat_envp : System.Address;
27086
27087    --  The actual variables are stored in a library routine. This
27088    --  is useful for some shared library situations, where there
27089    --  are problems if variables are not in the library.
27090
27091    pragma Import (C, gnat_argc);
27092    pragma Import (C, gnat_argv);
27093    pragma Import (C, gnat_envp);
27094
27095    --  The exit status is similarly an external location
27096
27097    gnat_exit_status : Integer;
27098    pragma Import (C, gnat_exit_status);
27099
27100    GNAT_Version : constant String :=
27101                     "GNAT Version: 6.0.0w (20061115)";
27102    pragma Export (C, GNAT_Version, "__gnat_version");
27103
27104    --  This is the generated adafinal routine that performs
27105    --  finalization at the end of execution. In the case where
27106    --  Ada is the main program, this main program makes a call
27107    --  to adafinal at program termination.
27108
27109    procedure adafinal;
27110    pragma Export (C, adafinal, "adafinal");
27111
27112    --  This is the generated adainit routine that performs
27113    --  initialization at the start of execution. In the case
27114    --  where Ada is the main program, this main program makes
27115    --  a call to adainit at program startup.
27116
27117    procedure adainit;
27118    pragma Export (C, adainit, "adainit");
27119
27120    --  This routine is called at the start of execution. It is
27121    --  a dummy routine that is used by the debugger to breakpoint
27122    --  at the start of execution.
27123
27124    procedure Break_Start;
27125    pragma Import (C, Break_Start, "__gnat_break_start");
27126
27127    --  This is the actual generated main program (it would be
27128    --  suppressed if the no main program switch were used). As
27129    --  required by standard system conventions, this program has
27130    --  the external name main.
27131
27132    function main
27133      (argc : Integer;
27134       argv : System.Address;
27135       envp : System.Address)
27136       return Integer;
27137    pragma Export (C, main, "main");
27138
27139    --  The following set of constants give the version
27140    --  identification values for every unit in the bound
27141    --  partition. This identification is computed from all
27142    --  dependent semantic units, and corresponds to the
27143    --  string that would be returned by use of the
27144    --  Body_Version or Version attributes.
27145
27146    type Version_32 is mod 2 ** 32;
27147    u00001 : constant Version_32 := 16#7880BEB3#;
27148    u00002 : constant Version_32 := 16#0D24CBD0#;
27149    u00003 : constant Version_32 := 16#3283DBEB#;
27150    u00004 : constant Version_32 := 16#2359F9ED#;
27151    u00005 : constant Version_32 := 16#664FB847#;
27152    u00006 : constant Version_32 := 16#68E803DF#;
27153    u00007 : constant Version_32 := 16#5572E604#;
27154    u00008 : constant Version_32 := 16#46B173D8#;
27155    u00009 : constant Version_32 := 16#156A40CF#;
27156    u00010 : constant Version_32 := 16#033DABE0#;
27157    u00011 : constant Version_32 := 16#6AB38FEA#;
27158    u00012 : constant Version_32 := 16#22B6217D#;
27159    u00013 : constant Version_32 := 16#68A22947#;
27160    u00014 : constant Version_32 := 16#18CC4A56#;
27161    u00015 : constant Version_32 := 16#08258E1B#;
27162    u00016 : constant Version_32 := 16#367D5222#;
27163    u00017 : constant Version_32 := 16#20C9ECA4#;
27164    u00018 : constant Version_32 := 16#50D32CB6#;
27165    u00019 : constant Version_32 := 16#39A8BB77#;
27166    u00020 : constant Version_32 := 16#5CF8FA2B#;
27167    u00021 : constant Version_32 := 16#2F1EB794#;
27168    u00022 : constant Version_32 := 16#31AB6444#;
27169    u00023 : constant Version_32 := 16#1574B6E9#;
27170    u00024 : constant Version_32 := 16#5109C189#;
27171    u00025 : constant Version_32 := 16#56D770CD#;
27172    u00026 : constant Version_32 := 16#02F9DE3D#;
27173    u00027 : constant Version_32 := 16#08AB6B2C#;
27174    u00028 : constant Version_32 := 16#3FA37670#;
27175    u00029 : constant Version_32 := 16#476457A0#;
27176    u00030 : constant Version_32 := 16#731E1B6E#;
27177    u00031 : constant Version_32 := 16#23C2E789#;
27178    u00032 : constant Version_32 := 16#0F1BD6A1#;
27179    u00033 : constant Version_32 := 16#7C25DE96#;
27180    u00034 : constant Version_32 := 16#39ADFFA2#;
27181    u00035 : constant Version_32 := 16#571DE3E7#;
27182    u00036 : constant Version_32 := 16#5EB646AB#;
27183    u00037 : constant Version_32 := 16#4249379B#;
27184    u00038 : constant Version_32 := 16#0357E00A#;
27185    u00039 : constant Version_32 := 16#3784FB72#;
27186    u00040 : constant Version_32 := 16#2E723019#;
27187    u00041 : constant Version_32 := 16#623358EA#;
27188    u00042 : constant Version_32 := 16#107F9465#;
27189    u00043 : constant Version_32 := 16#6843F68A#;
27190    u00044 : constant Version_32 := 16#63305874#;
27191    u00045 : constant Version_32 := 16#31E56CE1#;
27192    u00046 : constant Version_32 := 16#02917970#;
27193    u00047 : constant Version_32 := 16#6CCBA70E#;
27194    u00048 : constant Version_32 := 16#41CD4204#;
27195    u00049 : constant Version_32 := 16#572E3F58#;
27196    u00050 : constant Version_32 := 16#20729FF5#;
27197    u00051 : constant Version_32 := 16#1D4F93E8#;
27198    u00052 : constant Version_32 := 16#30B2EC3D#;
27199    u00053 : constant Version_32 := 16#34054F96#;
27200    u00054 : constant Version_32 := 16#5A199860#;
27201    u00055 : constant Version_32 := 16#0E7F912B#;
27202    u00056 : constant Version_32 := 16#5760634A#;
27203    u00057 : constant Version_32 := 16#5D851835#;
27204
27205    --  The following Export pragmas export the version numbers
27206    --  with symbolic names ending in B (for body) or S
27207    --  (for spec) so that they can be located in a link. The
27208    --  information provided here is sufficient to track down
27209    --  the exact versions of units used in a given build.
27210
27211    pragma Export (C, u00001, "helloB");
27212    pragma Export (C, u00002, "system__standard_libraryB");
27213    pragma Export (C, u00003, "system__standard_libraryS");
27214    pragma Export (C, u00004, "adaS");
27215    pragma Export (C, u00005, "ada__text_ioB");
27216    pragma Export (C, u00006, "ada__text_ioS");
27217    pragma Export (C, u00007, "ada__exceptionsB");
27218    pragma Export (C, u00008, "ada__exceptionsS");
27219    pragma Export (C, u00009, "gnatS");
27220    pragma Export (C, u00010, "gnat__heap_sort_aB");
27221    pragma Export (C, u00011, "gnat__heap_sort_aS");
27222    pragma Export (C, u00012, "systemS");
27223    pragma Export (C, u00013, "system__exception_tableB");
27224    pragma Export (C, u00014, "system__exception_tableS");
27225    pragma Export (C, u00015, "gnat__htableB");
27226    pragma Export (C, u00016, "gnat__htableS");
27227    pragma Export (C, u00017, "system__exceptionsS");
27228    pragma Export (C, u00018, "system__machine_state_operationsB");
27229    pragma Export (C, u00019, "system__machine_state_operationsS");
27230    pragma Export (C, u00020, "system__machine_codeS");
27231    pragma Export (C, u00021, "system__storage_elementsB");
27232    pragma Export (C, u00022, "system__storage_elementsS");
27233    pragma Export (C, u00023, "system__secondary_stackB");
27234    pragma Export (C, u00024, "system__secondary_stackS");
27235    pragma Export (C, u00025, "system__parametersB");
27236    pragma Export (C, u00026, "system__parametersS");
27237    pragma Export (C, u00027, "system__soft_linksB");
27238    pragma Export (C, u00028, "system__soft_linksS");
27239    pragma Export (C, u00029, "system__stack_checkingB");
27240    pragma Export (C, u00030, "system__stack_checkingS");
27241    pragma Export (C, u00031, "system__tracebackB");
27242    pragma Export (C, u00032, "system__tracebackS");
27243    pragma Export (C, u00033, "ada__streamsS");
27244    pragma Export (C, u00034, "ada__tagsB");
27245    pragma Export (C, u00035, "ada__tagsS");
27246    pragma Export (C, u00036, "system__string_opsB");
27247    pragma Export (C, u00037, "system__string_opsS");
27248    pragma Export (C, u00038, "interfacesS");
27249    pragma Export (C, u00039, "interfaces__c_streamsB");
27250    pragma Export (C, u00040, "interfaces__c_streamsS");
27251    pragma Export (C, u00041, "system__file_ioB");
27252    pragma Export (C, u00042, "system__file_ioS");
27253    pragma Export (C, u00043, "ada__finalizationB");
27254    pragma Export (C, u00044, "ada__finalizationS");
27255    pragma Export (C, u00045, "system__finalization_rootB");
27256    pragma Export (C, u00046, "system__finalization_rootS");
27257    pragma Export (C, u00047, "system__finalization_implementationB");
27258    pragma Export (C, u00048, "system__finalization_implementationS");
27259    pragma Export (C, u00049, "system__string_ops_concat_3B");
27260    pragma Export (C, u00050, "system__string_ops_concat_3S");
27261    pragma Export (C, u00051, "system__stream_attributesB");
27262    pragma Export (C, u00052, "system__stream_attributesS");
27263    pragma Export (C, u00053, "ada__io_exceptionsS");
27264    pragma Export (C, u00054, "system__unsigned_typesS");
27265    pragma Export (C, u00055, "system__file_control_blockS");
27266    pragma Export (C, u00056, "ada__finalization__list_controllerB");
27267    pragma Export (C, u00057, "ada__finalization__list_controllerS");
27268
27269    -- BEGIN ELABORATION ORDER
27270    -- ada (spec)
27271    -- gnat (spec)
27272    -- gnat.heap_sort_a (spec)
27273    -- gnat.heap_sort_a (body)
27274    -- gnat.htable (spec)
27275    -- gnat.htable (body)
27276    -- interfaces (spec)
27277    -- system (spec)
27278    -- system.machine_code (spec)
27279    -- system.parameters (spec)
27280    -- system.parameters (body)
27281    -- interfaces.c_streams (spec)
27282    -- interfaces.c_streams (body)
27283    -- system.standard_library (spec)
27284    -- ada.exceptions (spec)
27285    -- system.exception_table (spec)
27286    -- system.exception_table (body)
27287    -- ada.io_exceptions (spec)
27288    -- system.exceptions (spec)
27289    -- system.storage_elements (spec)
27290    -- system.storage_elements (body)
27291    -- system.machine_state_operations (spec)
27292    -- system.machine_state_operations (body)
27293    -- system.secondary_stack (spec)
27294    -- system.stack_checking (spec)
27295    -- system.soft_links (spec)
27296    -- system.soft_links (body)
27297    -- system.stack_checking (body)
27298    -- system.secondary_stack (body)
27299    -- system.standard_library (body)
27300    -- system.string_ops (spec)
27301    -- system.string_ops (body)
27302    -- ada.tags (spec)
27303    -- ada.tags (body)
27304    -- ada.streams (spec)
27305    -- system.finalization_root (spec)
27306    -- system.finalization_root (body)
27307    -- system.string_ops_concat_3 (spec)
27308    -- system.string_ops_concat_3 (body)
27309    -- system.traceback (spec)
27310    -- system.traceback (body)
27311    -- ada.exceptions (body)
27312    -- system.unsigned_types (spec)
27313    -- system.stream_attributes (spec)
27314    -- system.stream_attributes (body)
27315    -- system.finalization_implementation (spec)
27316    -- system.finalization_implementation (body)
27317    -- ada.finalization (spec)
27318    -- ada.finalization (body)
27319    -- ada.finalization.list_controller (spec)
27320    -- ada.finalization.list_controller (body)
27321    -- system.file_control_block (spec)
27322    -- system.file_io (spec)
27323    -- system.file_io (body)
27324    -- ada.text_io (spec)
27325    -- ada.text_io (body)
27326    -- hello (body)
27327    -- END ELABORATION ORDER
27328
27329 end ada_main;
27330
27331 --  The following source file name pragmas allow the generated file
27332 --  names to be unique for different main programs. They are needed
27333 --  since the package name will always be Ada_Main.
27334
27335 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
27336 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
27337
27338 --  Generated package body for Ada_Main starts here
27339
27340 package body ada_main is
27341
27342    --  The actual finalization is performed by calling the
27343    --  library routine in System.Standard_Library.Adafinal
27344
27345    procedure Do_Finalize;
27346    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
27347
27348    -------------
27349    -- adainit --
27350    -------------
27351
27352 @findex adainit
27353    procedure adainit is
27354
27355       --  These booleans are set to True once the associated unit has
27356       --  been elaborated. It is also used to avoid elaborating the
27357       --  same unit twice.
27358
27359       E040 : Boolean;
27360       pragma Import (Ada, E040, "interfaces__c_streams_E");
27361
27362       E008 : Boolean;
27363       pragma Import (Ada, E008, "ada__exceptions_E");
27364
27365       E014 : Boolean;
27366       pragma Import (Ada, E014, "system__exception_table_E");
27367
27368       E053 : Boolean;
27369       pragma Import (Ada, E053, "ada__io_exceptions_E");
27370
27371       E017 : Boolean;
27372       pragma Import (Ada, E017, "system__exceptions_E");
27373
27374       E024 : Boolean;
27375       pragma Import (Ada, E024, "system__secondary_stack_E");
27376
27377       E030 : Boolean;
27378       pragma Import (Ada, E030, "system__stack_checking_E");
27379
27380       E028 : Boolean;
27381       pragma Import (Ada, E028, "system__soft_links_E");
27382
27383       E035 : Boolean;
27384       pragma Import (Ada, E035, "ada__tags_E");
27385
27386       E033 : Boolean;
27387       pragma Import (Ada, E033, "ada__streams_E");
27388
27389       E046 : Boolean;
27390       pragma Import (Ada, E046, "system__finalization_root_E");
27391
27392       E048 : Boolean;
27393       pragma Import (Ada, E048, "system__finalization_implementation_E");
27394
27395       E044 : Boolean;
27396       pragma Import (Ada, E044, "ada__finalization_E");
27397
27398       E057 : Boolean;
27399       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
27400
27401       E055 : Boolean;
27402       pragma Import (Ada, E055, "system__file_control_block_E");
27403
27404       E042 : Boolean;
27405       pragma Import (Ada, E042, "system__file_io_E");
27406
27407       E006 : Boolean;
27408       pragma Import (Ada, E006, "ada__text_io_E");
27409
27410       --  Set_Globals is a library routine that stores away the
27411       --  value of the indicated set of global values in global
27412       --  variables within the library.
27413
27414       procedure Set_Globals
27415         (Main_Priority            : Integer;
27416          Time_Slice_Value         : Integer;
27417          WC_Encoding              : Character;
27418          Locking_Policy           : Character;
27419          Queuing_Policy           : Character;
27420          Task_Dispatching_Policy  : Character;
27421          Adafinal                 : System.Address;
27422          Unreserve_All_Interrupts : Integer;
27423          Exception_Tracebacks     : Integer);
27424 @findex __gnat_set_globals
27425       pragma Import (C, Set_Globals, "__gnat_set_globals");
27426
27427       --  SDP_Table_Build is a library routine used to build the
27428       --  exception tables. See unit Ada.Exceptions in files
27429       --  a-except.ads/adb for full details of how zero cost
27430       --  exception handling works. This procedure, the call to
27431       --  it, and the two following tables are all omitted if the
27432       --  build is in longjmp/setjmp exception mode.
27433
27434 @findex SDP_Table_Build
27435 @findex Zero Cost Exceptions
27436       procedure SDP_Table_Build
27437         (SDP_Addresses   : System.Address;
27438          SDP_Count       : Natural;
27439          Elab_Addresses  : System.Address;
27440          Elab_Addr_Count : Natural);
27441       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
27442
27443       --  Table of Unit_Exception_Table addresses. Used for zero
27444       --  cost exception handling to build the top level table.
27445
27446       ST : aliased constant array (1 .. 23) of System.Address := (
27447         Hello'UET_Address,
27448         Ada.Text_Io'UET_Address,
27449         Ada.Exceptions'UET_Address,
27450         Gnat.Heap_Sort_A'UET_Address,
27451         System.Exception_Table'UET_Address,
27452         System.Machine_State_Operations'UET_Address,
27453         System.Secondary_Stack'UET_Address,
27454         System.Parameters'UET_Address,
27455         System.Soft_Links'UET_Address,
27456         System.Stack_Checking'UET_Address,
27457         System.Traceback'UET_Address,
27458         Ada.Streams'UET_Address,
27459         Ada.Tags'UET_Address,
27460         System.String_Ops'UET_Address,
27461         Interfaces.C_Streams'UET_Address,
27462         System.File_Io'UET_Address,
27463         Ada.Finalization'UET_Address,
27464         System.Finalization_Root'UET_Address,
27465         System.Finalization_Implementation'UET_Address,
27466         System.String_Ops_Concat_3'UET_Address,
27467         System.Stream_Attributes'UET_Address,
27468         System.File_Control_Block'UET_Address,
27469         Ada.Finalization.List_Controller'UET_Address);
27470
27471       --  Table of addresses of elaboration routines. Used for
27472       --  zero cost exception handling to make sure these
27473       --  addresses are included in the top level procedure
27474       --  address table.
27475
27476       EA : aliased constant array (1 .. 23) of System.Address := (
27477         adainit'Code_Address,
27478         Do_Finalize'Code_Address,
27479         Ada.Exceptions'Elab_Spec'Address,
27480         System.Exceptions'Elab_Spec'Address,
27481         Interfaces.C_Streams'Elab_Spec'Address,
27482         System.Exception_Table'Elab_Body'Address,
27483         Ada.Io_Exceptions'Elab_Spec'Address,
27484         System.Stack_Checking'Elab_Spec'Address,
27485         System.Soft_Links'Elab_Body'Address,
27486         System.Secondary_Stack'Elab_Body'Address,
27487         Ada.Tags'Elab_Spec'Address,
27488         Ada.Tags'Elab_Body'Address,
27489         Ada.Streams'Elab_Spec'Address,
27490         System.Finalization_Root'Elab_Spec'Address,
27491         Ada.Exceptions'Elab_Body'Address,
27492         System.Finalization_Implementation'Elab_Spec'Address,
27493         System.Finalization_Implementation'Elab_Body'Address,
27494         Ada.Finalization'Elab_Spec'Address,
27495         Ada.Finalization.List_Controller'Elab_Spec'Address,
27496         System.File_Control_Block'Elab_Spec'Address,
27497         System.File_Io'Elab_Body'Address,
27498         Ada.Text_Io'Elab_Spec'Address,
27499         Ada.Text_Io'Elab_Body'Address);
27500
27501    --  Start of processing for adainit
27502
27503    begin
27504
27505       --  Call SDP_Table_Build to build the top level procedure
27506       --  table for zero cost exception handling (omitted in
27507       --  longjmp/setjmp mode).
27508
27509       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
27510
27511       --  Call Set_Globals to record various information for
27512       --  this partition.  The values are derived by the binder
27513       --  from information stored in the ali files by the compiler.
27514
27515 @findex __gnat_set_globals
27516       Set_Globals
27517         (Main_Priority            => -1,
27518          --  Priority of main program, -1 if no pragma Priority used
27519
27520          Time_Slice_Value         => -1,
27521          --  Time slice from Time_Slice pragma, -1 if none used
27522
27523          WC_Encoding              => 'b',
27524          --  Wide_Character encoding used, default is brackets
27525
27526          Locking_Policy           => ' ',
27527          --  Locking_Policy used, default of space means not
27528          --  specified, otherwise it is the first character of
27529          --  the policy name.
27530
27531          Queuing_Policy           => ' ',
27532          --  Queuing_Policy used, default of space means not
27533          --  specified, otherwise it is the first character of
27534          --  the policy name.
27535
27536          Task_Dispatching_Policy  => ' ',
27537          --  Task_Dispatching_Policy used, default of space means
27538          --  not specified, otherwise first character of the
27539          --  policy name.
27540
27541          Adafinal                 => System.Null_Address,
27542          --  Address of Adafinal routine, not used anymore
27543
27544          Unreserve_All_Interrupts => 0,
27545          --  Set true if pragma Unreserve_All_Interrupts was used
27546
27547          Exception_Tracebacks     => 0);
27548          --  Indicates if exception tracebacks are enabled
27549
27550       Elab_Final_Code := 1;
27551
27552       --  Now we have the elaboration calls for all units in the partition.
27553       --  The Elab_Spec and Elab_Body attributes generate references to the
27554       --  implicit elaboration procedures generated by the compiler for
27555       --  each unit that requires elaboration.
27556
27557       if not E040 then
27558          Interfaces.C_Streams'Elab_Spec;
27559       end if;
27560       E040 := True;
27561       if not E008 then
27562          Ada.Exceptions'Elab_Spec;
27563       end if;
27564       if not E014 then
27565          System.Exception_Table'Elab_Body;
27566          E014 := True;
27567       end if;
27568       if not E053 then
27569          Ada.Io_Exceptions'Elab_Spec;
27570          E053 := True;
27571       end if;
27572       if not E017 then
27573          System.Exceptions'Elab_Spec;
27574          E017 := True;
27575       end if;
27576       if not E030 then
27577          System.Stack_Checking'Elab_Spec;
27578       end if;
27579       if not E028 then
27580          System.Soft_Links'Elab_Body;
27581          E028 := True;
27582       end if;
27583       E030 := True;
27584       if not E024 then
27585          System.Secondary_Stack'Elab_Body;
27586          E024 := True;
27587       end if;
27588       if not E035 then
27589          Ada.Tags'Elab_Spec;
27590       end if;
27591       if not E035 then
27592          Ada.Tags'Elab_Body;
27593          E035 := True;
27594       end if;
27595       if not E033 then
27596          Ada.Streams'Elab_Spec;
27597          E033 := True;
27598       end if;
27599       if not E046 then
27600          System.Finalization_Root'Elab_Spec;
27601       end if;
27602       E046 := True;
27603       if not E008 then
27604          Ada.Exceptions'Elab_Body;
27605          E008 := True;
27606       end if;
27607       if not E048 then
27608          System.Finalization_Implementation'Elab_Spec;
27609       end if;
27610       if not E048 then
27611          System.Finalization_Implementation'Elab_Body;
27612          E048 := True;
27613       end if;
27614       if not E044 then
27615          Ada.Finalization'Elab_Spec;
27616       end if;
27617       E044 := True;
27618       if not E057 then
27619          Ada.Finalization.List_Controller'Elab_Spec;
27620       end if;
27621       E057 := True;
27622       if not E055 then
27623          System.File_Control_Block'Elab_Spec;
27624          E055 := True;
27625       end if;
27626       if not E042 then
27627          System.File_Io'Elab_Body;
27628          E042 := True;
27629       end if;
27630       if not E006 then
27631          Ada.Text_Io'Elab_Spec;
27632       end if;
27633       if not E006 then
27634          Ada.Text_Io'Elab_Body;
27635          E006 := True;
27636       end if;
27637
27638       Elab_Final_Code := 0;
27639    end adainit;
27640
27641    --------------
27642    -- adafinal --
27643    --------------
27644
27645 @findex adafinal
27646    procedure adafinal is
27647    begin
27648       Do_Finalize;
27649    end adafinal;
27650
27651    ----------
27652    -- main --
27653    ----------
27654
27655    --  main is actually a function, as in the ANSI C standard,
27656    --  defined to return the exit status. The three parameters
27657    --  are the argument count, argument values and environment
27658    --  pointer.
27659
27660 @findex Main Program
27661    function main
27662      (argc : Integer;
27663       argv : System.Address;
27664       envp : System.Address)
27665       return Integer
27666    is
27667       --  The initialize routine performs low level system
27668       --  initialization using a standard library routine which
27669       --  sets up signal handling and performs any other
27670       --  required setup. The routine can be found in file
27671       --  a-init.c.
27672
27673 @findex __gnat_initialize
27674       procedure initialize;
27675       pragma Import (C, initialize, "__gnat_initialize");
27676
27677       --  The finalize routine performs low level system
27678       --  finalization using a standard library routine. The
27679       --  routine is found in file a-final.c and in the standard
27680       --  distribution is a dummy routine that does nothing, so
27681       --  really this is a hook for special user finalization.
27682
27683 @findex __gnat_finalize
27684       procedure finalize;
27685       pragma Import (C, finalize, "__gnat_finalize");
27686
27687       --  We get to the main program of the partition by using
27688       --  pragma Import because if we try to with the unit and
27689       --  call it Ada style, then not only do we waste time
27690       --  recompiling it, but also, we don't really know the right
27691       --  switches (e.g.@: identifier character set) to be used
27692       --  to compile it.
27693
27694       procedure Ada_Main_Program;
27695       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
27696
27697    --  Start of processing for main
27698
27699    begin
27700       --  Save global variables
27701
27702       gnat_argc := argc;
27703       gnat_argv := argv;
27704       gnat_envp := envp;
27705
27706       --  Call low level system initialization
27707
27708       Initialize;
27709
27710       --  Call our generated Ada initialization routine
27711
27712       adainit;
27713
27714       --  This is the point at which we want the debugger to get
27715       --  control
27716
27717       Break_Start;
27718
27719       --  Now we call the main program of the partition
27720
27721       Ada_Main_Program;
27722
27723       --  Perform Ada finalization
27724
27725       adafinal;
27726
27727       --  Perform low level system finalization
27728
27729       Finalize;
27730
27731       --  Return the proper exit status
27732       return (gnat_exit_status);
27733    end;
27734
27735 --  This section is entirely comments, so it has no effect on the
27736 --  compilation of the Ada_Main package. It provides the list of
27737 --  object files and linker options, as well as some standard
27738 --  libraries needed for the link. The gnatlink utility parses
27739 --  this b~hello.adb file to read these comment lines to generate
27740 --  the appropriate command line arguments for the call to the
27741 --  system linker. The BEGIN/END lines are used for sentinels for
27742 --  this parsing operation.
27743
27744 --  The exact file names will of course depend on the environment,
27745 --  host/target and location of files on the host system.
27746
27747 @findex Object file list
27748 -- BEGIN Object file/option list
27749    --   ./hello.o
27750    --   -L./
27751    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
27752    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
27753 -- END Object file/option list
27754
27755 end ada_main;
27756 @end smallexample
27757
27758 @noindent
27759 The Ada code in the above example is exactly what is generated by the
27760 binder. We have added comments to more clearly indicate the function
27761 of each part of the generated @code{Ada_Main} package.
27762
27763 The code is standard Ada in all respects, and can be processed by any
27764 tools that handle Ada. In particular, it is possible to use the debugger
27765 in Ada mode to debug the generated @code{Ada_Main} package. For example,
27766 suppose that for reasons that you do not understand, your program is crashing
27767 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
27768 you can place a breakpoint on the call:
27769
27770 @smallexample @c ada
27771 Ada.Text_Io'Elab_Body;
27772 @end smallexample
27773
27774 @noindent
27775 and trace the elaboration routine for this package to find out where
27776 the problem might be (more usually of course you would be debugging
27777 elaboration code in your own application).
27778
27779 @node Elaboration Order Handling in GNAT
27780 @appendix Elaboration Order Handling in GNAT
27781 @cindex Order of elaboration
27782 @cindex Elaboration control
27783
27784 @menu
27785 * Elaboration Code::
27786 * Checking the Elaboration Order::
27787 * Controlling the Elaboration Order::
27788 * Controlling Elaboration in GNAT - Internal Calls::
27789 * Controlling Elaboration in GNAT - External Calls::
27790 * Default Behavior in GNAT - Ensuring Safety::
27791 * Treatment of Pragma Elaborate::
27792 * Elaboration Issues for Library Tasks::
27793 * Mixing Elaboration Models::
27794 * What to Do If the Default Elaboration Behavior Fails::
27795 * Elaboration for Access-to-Subprogram Values::
27796 * Summary of Procedures for Elaboration Control::
27797 * Other Elaboration Order Considerations::
27798 @end menu
27799
27800 @noindent
27801 This chapter describes the handling of elaboration code in Ada and
27802 in GNAT, and discusses how the order of elaboration of program units can
27803 be controlled in GNAT, either automatically or with explicit programming
27804 features.
27805
27806 @node Elaboration Code
27807 @section Elaboration Code
27808
27809 @noindent
27810 Ada provides rather general mechanisms for executing code at elaboration
27811 time, that is to say before the main program starts executing. Such code arises
27812 in three contexts:
27813
27814 @table @asis
27815 @item Initializers for variables.
27816 Variables declared at the library level, in package specs or bodies, can
27817 require initialization that is performed at elaboration time, as in:
27818 @smallexample @c ada
27819 @cartouche
27820 Sqrt_Half : Float := Sqrt (0.5);
27821 @end cartouche
27822 @end smallexample
27823
27824 @item Package initialization code
27825 Code in a @code{BEGIN-END} section at the outer level of a package body is
27826 executed as part of the package body elaboration code.
27827
27828 @item Library level task allocators
27829 Tasks that are declared using task allocators at the library level
27830 start executing immediately and hence can execute at elaboration time.
27831 @end table
27832
27833 @noindent
27834 Subprogram calls are possible in any of these contexts, which means that
27835 any arbitrary part of the program may be executed as part of the elaboration
27836 code. It is even possible to write a program which does all its work at
27837 elaboration time, with a null main program, although stylistically this
27838 would usually be considered an inappropriate way to structure
27839 a program.
27840
27841 An important concern arises in the context of elaboration code:
27842 we have to be sure that it is executed in an appropriate order. What we
27843 have is a series of elaboration code sections, potentially one section
27844 for each unit in the program. It is important that these execute
27845 in the correct order. Correctness here means that, taking the above
27846 example of the declaration of @code{Sqrt_Half},
27847 if some other piece of
27848 elaboration code references @code{Sqrt_Half},
27849 then it must run after the
27850 section of elaboration code that contains the declaration of
27851 @code{Sqrt_Half}.
27852
27853 There would never be any order of elaboration problem if we made a rule
27854 that whenever you @code{with} a unit, you must elaborate both the spec and body
27855 of that unit before elaborating the unit doing the @code{with}'ing:
27856
27857 @smallexample @c ada
27858 @group
27859 @cartouche
27860 with Unit_1;
27861 package Unit_2 is @dots{}
27862 @end cartouche
27863 @end group
27864 @end smallexample
27865
27866 @noindent
27867 would require that both the body and spec of @code{Unit_1} be elaborated
27868 before the spec of @code{Unit_2}. However, a rule like that would be far too
27869 restrictive. In particular, it would make it impossible to have routines
27870 in separate packages that were mutually recursive.
27871
27872 You might think that a clever enough compiler could look at the actual
27873 elaboration code and determine an appropriate correct order of elaboration,
27874 but in the general case, this is not possible. Consider the following
27875 example.
27876
27877 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
27878 that references
27879 the variable @code{Sqrt_1}, which is declared in the elaboration code
27880 of the body of @code{Unit_1}:
27881
27882 @smallexample @c ada
27883 @cartouche
27884 Sqrt_1 : Float := Sqrt (0.1);
27885 @end cartouche
27886 @end smallexample
27887
27888 @noindent
27889 The elaboration code of the body of @code{Unit_1} also contains:
27890
27891 @smallexample @c ada
27892 @group
27893 @cartouche
27894 if expression_1 = 1 then
27895    Q := Unit_2.Func_2;
27896 end if;
27897 @end cartouche
27898 @end group
27899 @end smallexample
27900
27901 @noindent
27902 @code{Unit_2} is exactly parallel,
27903 it has a procedure @code{Func_2} that references
27904 the variable @code{Sqrt_2}, which is declared in the elaboration code of
27905 the body @code{Unit_2}:
27906
27907 @smallexample @c ada
27908 @cartouche
27909 Sqrt_2 : Float := Sqrt (0.1);
27910 @end cartouche
27911 @end smallexample
27912
27913 @noindent
27914 The elaboration code of the body of @code{Unit_2} also contains:
27915
27916 @smallexample @c ada
27917 @group
27918 @cartouche
27919 if expression_2 = 2 then
27920    Q := Unit_1.Func_1;
27921 end if;
27922 @end cartouche
27923 @end group
27924 @end smallexample
27925
27926 @noindent
27927 Now the question is, which of the following orders of elaboration is
27928 acceptable:
27929
27930 @smallexample
27931 @group
27932 Spec of Unit_1
27933 Spec of Unit_2
27934 Body of Unit_1
27935 Body of Unit_2
27936 @end group
27937 @end smallexample
27938
27939 @noindent
27940 or
27941
27942 @smallexample
27943 @group
27944 Spec of Unit_2
27945 Spec of Unit_1
27946 Body of Unit_2
27947 Body of Unit_1
27948 @end group
27949 @end smallexample
27950
27951 @noindent
27952 If you carefully analyze the flow here, you will see that you cannot tell
27953 at compile time the answer to this question.
27954 If @code{expression_1} is not equal to 1,
27955 and @code{expression_2} is not equal to 2,
27956 then either order is acceptable, because neither of the function calls is
27957 executed. If both tests evaluate to true, then neither order is acceptable
27958 and in fact there is no correct order.
27959
27960 If one of the two expressions is true, and the other is false, then one
27961 of the above orders is correct, and the other is incorrect. For example,
27962 if @code{expression_1} /= 1 and @code{expression_2} = 2,
27963 then the call to @code{Func_1}
27964 will occur, but not the call to @code{Func_2.}
27965 This means that it is essential
27966 to elaborate the body of @code{Unit_1} before
27967 the body of @code{Unit_2}, so the first
27968 order of elaboration is correct and the second is wrong.
27969
27970 By making @code{expression_1} and @code{expression_2}
27971 depend on input data, or perhaps
27972 the time of day, we can make it impossible for the compiler or binder
27973 to figure out which of these expressions will be true, and hence it
27974 is impossible to guarantee a safe order of elaboration at run time.
27975
27976 @node Checking the Elaboration Order
27977 @section Checking the Elaboration Order
27978
27979 @noindent
27980 In some languages that involve the same kind of elaboration problems,
27981 e.g.@: Java and C++, the programmer is expected to worry about these
27982 ordering problems himself, and it is common to
27983 write a program in which an incorrect elaboration order  gives
27984 surprising results, because it references variables before they
27985 are initialized.
27986 Ada is designed to be a safe language, and a programmer-beware approach is
27987 clearly not sufficient. Consequently, the language provides three lines
27988 of defense:
27989
27990 @table @asis
27991 @item Standard rules
27992 Some standard rules restrict the possible choice of elaboration
27993 order. In particular, if you @code{with} a unit, then its spec is always
27994 elaborated before the unit doing the @code{with}. Similarly, a parent
27995 spec is always elaborated before the child spec, and finally
27996 a spec is always elaborated before its corresponding body.
27997
27998 @item Dynamic elaboration checks
27999 @cindex Elaboration checks
28000 @cindex Checks, elaboration
28001 Dynamic checks are made at run time, so that if some entity is accessed
28002 before it is elaborated (typically  by means of a subprogram call)
28003 then the exception (@code{Program_Error}) is raised.
28004
28005 @item Elaboration control
28006 Facilities are provided for the programmer to specify the desired order
28007 of elaboration.
28008 @end table
28009
28010 Let's look at these facilities in more detail. First, the rules for
28011 dynamic checking. One possible rule would be simply to say that the
28012 exception is raised if you access a variable which has not yet been
28013 elaborated. The trouble with this approach is that it could require
28014 expensive checks on every variable reference. Instead Ada has two
28015 rules which are a little more restrictive, but easier to check, and
28016 easier to state:
28017
28018 @table @asis
28019 @item Restrictions on calls
28020 A subprogram can only be called at elaboration time if its body
28021 has been elaborated. The rules for elaboration given above guarantee
28022 that the spec of the subprogram has been elaborated before the
28023 call, but not the body. If this rule is violated, then the
28024 exception @code{Program_Error} is raised.
28025
28026 @item Restrictions on instantiations
28027 A generic unit can only be instantiated if the body of the generic
28028 unit has been elaborated. Again, the rules for elaboration given above
28029 guarantee that the spec of the generic unit has been elaborated
28030 before the instantiation, but not the body. If this rule is
28031 violated, then the exception @code{Program_Error} is raised.
28032 @end table
28033
28034 @noindent
28035 The idea is that if the body has been elaborated, then any variables
28036 it references must have been elaborated; by checking for the body being
28037 elaborated we guarantee that none of its references causes any
28038 trouble. As we noted above, this is a little too restrictive, because a
28039 subprogram that has no non-local references in its body may in fact be safe
28040 to call. However, it really would be unsafe to rely on this, because
28041 it would mean that the caller was aware of details of the implementation
28042 in the body. This goes against the basic tenets of Ada.
28043
28044 A plausible implementation can be described as follows.
28045 A Boolean variable is associated with each subprogram
28046 and each generic unit. This variable is initialized to False, and is set to
28047 True at the point body is elaborated. Every call or instantiation checks the
28048 variable, and raises @code{Program_Error} if the variable is False.
28049
28050 Note that one might think that it would be good enough to have one Boolean
28051 variable for each package, but that would not deal with cases of trying
28052 to call a body in the same package as the call
28053 that has not been elaborated yet.
28054 Of course a compiler may be able to do enough analysis to optimize away
28055 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
28056 does such optimizations, but still the easiest conceptual model is to
28057 think of there being one variable per subprogram.
28058
28059 @node Controlling the Elaboration Order
28060 @section Controlling the Elaboration Order
28061
28062 @noindent
28063 In the previous section we discussed the rules in Ada which ensure
28064 that @code{Program_Error} is raised if an incorrect elaboration order is
28065 chosen. This prevents erroneous executions, but we need mechanisms to
28066 specify a correct execution and avoid the exception altogether.
28067 To achieve this, Ada provides a number of features for controlling
28068 the order of elaboration. We discuss these features in this section.
28069
28070 First, there are several ways of indicating to the compiler that a given
28071 unit has no elaboration problems:
28072
28073 @table @asis
28074 @item packages that do not require a body
28075 A library package that does not require a body does not permit
28076 a body (this rule was introduced in Ada 95).
28077 Thus if we have a such a package, as in:
28078
28079 @smallexample @c ada
28080 @group
28081 @cartouche
28082 package Definitions is
28083    generic
28084       type m is new integer;
28085    package Subp is
28086       type a is array (1 .. 10) of m;
28087       type b is array (1 .. 20) of m;
28088    end Subp;
28089 end Definitions;
28090 @end cartouche
28091 @end group
28092 @end smallexample
28093
28094 @noindent
28095 A package that @code{with}'s @code{Definitions} may safely instantiate
28096 @code{Definitions.Subp} because the compiler can determine that there
28097 definitely is no package body to worry about in this case
28098
28099 @item pragma Pure
28100 @cindex pragma Pure
28101 @findex Pure
28102 Places sufficient restrictions on a unit to guarantee that
28103 no call to any subprogram in the unit can result in an
28104 elaboration problem. This means that the compiler does not need
28105 to worry about the point of elaboration of such units, and in
28106 particular, does not need to check any calls to any subprograms
28107 in this unit.
28108
28109 @item pragma Preelaborate
28110 @findex Preelaborate
28111 @cindex pragma Preelaborate
28112 This pragma places slightly less stringent restrictions on a unit than
28113 does pragma Pure,
28114 but these restrictions are still sufficient to ensure that there
28115 are no elaboration problems with any calls to the unit.
28116
28117 @item pragma Elaborate_Body
28118 @findex Elaborate_Body
28119 @cindex pragma Elaborate_Body
28120 This pragma requires that the body of a unit be elaborated immediately
28121 after its spec. Suppose a unit @code{A} has such a pragma,
28122 and unit @code{B} does
28123 a @code{with} of unit @code{A}. Recall that the standard rules require
28124 the spec of unit @code{A}
28125 to be elaborated before the @code{with}'ing unit; given the pragma in
28126 @code{A}, we also know that the body of @code{A}
28127 will be elaborated before @code{B}, so
28128 that calls to @code{A} are safe and do not need a check.
28129 @end table
28130
28131 @noindent
28132 Note that,
28133 unlike pragma @code{Pure} and pragma @code{Preelaborate},
28134 the use of
28135 @code{Elaborate_Body} does not guarantee that the program is
28136 free of elaboration problems, because it may not be possible
28137 to satisfy the requested elaboration order.
28138 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
28139 If a programmer
28140 marks @code{Unit_1} as @code{Elaborate_Body},
28141 and not @code{Unit_2,} then the order of
28142 elaboration will be:
28143
28144 @smallexample
28145 @group
28146 Spec of Unit_2
28147 Spec of Unit_1
28148 Body of Unit_1
28149 Body of Unit_2
28150 @end group
28151 @end smallexample
28152
28153 @noindent
28154 Now that means that the call to @code{Func_1} in @code{Unit_2}
28155 need not be checked,
28156 it must be safe. But the call to @code{Func_2} in
28157 @code{Unit_1} may still fail if
28158 @code{Expression_1} is equal to 1,
28159 and the programmer must still take
28160 responsibility for this not being the case.
28161
28162 If all units carry a pragma @code{Elaborate_Body}, then all problems are
28163 eliminated, except for calls entirely within a body, which are
28164 in any case fully under programmer control. However, using the pragma
28165 everywhere is not always possible.
28166 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
28167 we marked both of them as having pragma @code{Elaborate_Body}, then
28168 clearly there would be no possible elaboration order.
28169
28170 The above pragmas allow a server to guarantee safe use by clients, and
28171 clearly this is the preferable approach. Consequently a good rule
28172 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
28173 and if this is not possible,
28174 mark them as @code{Elaborate_Body} if possible.
28175 As we have seen, there are situations where neither of these
28176 three pragmas can be used.
28177 So we also provide methods for clients to control the
28178 order of elaboration of the servers on which they depend:
28179
28180 @table @asis
28181 @item pragma Elaborate (unit)
28182 @findex Elaborate
28183 @cindex pragma Elaborate
28184 This pragma is placed in the context clause, after a @code{with} clause,
28185 and it requires that the body of the named unit be elaborated before
28186 the unit in which the pragma occurs. The idea is to use this pragma
28187 if the current unit calls at elaboration time, directly or indirectly,
28188 some subprogram in the named unit.
28189
28190 @item pragma Elaborate_All (unit)
28191 @findex Elaborate_All
28192 @cindex pragma Elaborate_All
28193 This is a stronger version of the Elaborate pragma. Consider the
28194 following example:
28195
28196 @smallexample
28197 Unit A @code{with}'s unit B and calls B.Func in elab code
28198 Unit B @code{with}'s unit C, and B.Func calls C.Func
28199 @end smallexample
28200
28201 @noindent
28202 Now if we put a pragma @code{Elaborate (B)}
28203 in unit @code{A}, this ensures that the
28204 body of @code{B} is elaborated before the call, but not the
28205 body of @code{C}, so
28206 the call to @code{C.Func} could still cause @code{Program_Error} to
28207 be raised.
28208
28209 The effect of a pragma @code{Elaborate_All} is stronger, it requires
28210 not only that the body of the named unit be elaborated before the
28211 unit doing the @code{with}, but also the bodies of all units that the
28212 named unit uses, following @code{with} links transitively. For example,
28213 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
28214 then it requires
28215 not only that the body of @code{B} be elaborated before @code{A},
28216 but also the
28217 body of @code{C}, because @code{B} @code{with}'s @code{C}.
28218 @end table
28219
28220 @noindent
28221 We are now in a position to give a usage rule in Ada for avoiding
28222 elaboration problems, at least if dynamic dispatching and access to
28223 subprogram values are not used. We will handle these cases separately
28224 later.
28225
28226 The rule is simple. If a unit has elaboration code that can directly or
28227 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
28228 a generic package in a @code{with}'ed unit,
28229 then if the @code{with}'ed unit does not have
28230 pragma @code{Pure} or @code{Preelaborate}, then the client should have
28231 a pragma @code{Elaborate_All}
28232 for the @code{with}'ed unit. By following this rule a client is
28233 assured that calls can be made without risk of an exception.
28234
28235 For generic subprogram instantiations, the rule can be relaxed to
28236 require only a pragma @code{Elaborate} since elaborating the body
28237 of a subprogram cannot cause any transitive elaboration (we are
28238 not calling the subprogram in this case, just elaborating its
28239 declaration).
28240
28241 If this rule is not followed, then a program may be in one of four
28242 states:
28243
28244 @table @asis
28245 @item No order exists
28246 No order of elaboration exists which follows the rules, taking into
28247 account any @code{Elaborate}, @code{Elaborate_All},
28248 or @code{Elaborate_Body} pragmas. In
28249 this case, an Ada compiler must diagnose the situation at bind
28250 time, and refuse to build an executable program.
28251
28252 @item One or more orders exist, all incorrect
28253 One or more acceptable elaboration orders exist, and all of them
28254 generate an elaboration order problem. In this case, the binder
28255 can build an executable program, but @code{Program_Error} will be raised
28256 when the program is run.
28257
28258 @item Several orders exist, some right, some incorrect
28259 One or more acceptable elaboration orders exists, and some of them
28260 work, and some do not. The programmer has not controlled
28261 the order of elaboration, so the binder may or may not pick one of
28262 the correct orders, and the program may or may not raise an
28263 exception when it is run. This is the worst case, because it means
28264 that the program may fail when moved to another compiler, or even
28265 another version of the same compiler.
28266
28267 @item One or more orders exists, all correct
28268 One ore more acceptable elaboration orders exist, and all of them
28269 work. In this case the program runs successfully. This state of
28270 affairs can be guaranteed by following the rule we gave above, but
28271 may be true even if the rule is not followed.
28272 @end table
28273
28274 @noindent
28275 Note that one additional advantage of following our rules on the use
28276 of @code{Elaborate} and @code{Elaborate_All}
28277 is that the program continues to stay in the ideal (all orders OK) state
28278 even if maintenance
28279 changes some bodies of some units. Conversely, if a program that does
28280 not follow this rule happens to be safe at some point, this state of affairs
28281 may deteriorate silently as a result of maintenance changes.
28282
28283 You may have noticed that the above discussion did not mention
28284 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
28285 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
28286 code in the body makes calls to some other unit, so it is still necessary
28287 to use @code{Elaborate_All} on such units.
28288
28289 @node Controlling Elaboration in GNAT - Internal Calls
28290 @section Controlling Elaboration in GNAT - Internal Calls
28291
28292 @noindent
28293 In the case of internal calls, i.e., calls within a single package, the
28294 programmer has full control over the order of elaboration, and it is up
28295 to the programmer to elaborate declarations in an appropriate order. For
28296 example writing:
28297
28298 @smallexample @c ada
28299 @group
28300 @cartouche
28301 function One return Float;
28302
28303 Q : Float := One;
28304
28305 function One return Float is
28306 begin
28307      return 1.0;
28308 end One;
28309 @end cartouche
28310 @end group
28311 @end smallexample
28312
28313 @noindent
28314 will obviously raise @code{Program_Error} at run time, because function
28315 One will be called before its body is elaborated. In this case GNAT will
28316 generate a warning that the call will raise @code{Program_Error}:
28317
28318 @smallexample
28319 @group
28320 @cartouche
28321  1. procedure y is
28322  2.    function One return Float;
28323  3.
28324  4.    Q : Float := One;
28325                     |
28326     >>> warning: cannot call "One" before body is elaborated
28327     >>> warning: Program_Error will be raised at run time
28328
28329  5.
28330  6.    function One return Float is
28331  7.    begin
28332  8.         return 1.0;
28333  9.    end One;
28334 10.
28335 11. begin
28336 12.    null;
28337 13. end;
28338 @end cartouche
28339 @end group
28340 @end smallexample
28341
28342 @noindent
28343 Note that in this particular case, it is likely that the call is safe, because
28344 the function @code{One} does not access any global variables.
28345 Nevertheless in Ada, we do not want the validity of the check to depend on
28346 the contents of the body (think about the separate compilation case), so this
28347 is still wrong, as we discussed in the previous sections.
28348
28349 The error is easily corrected by rearranging the declarations so that the
28350 body of @code{One} appears before the declaration containing the call
28351 (note that in Ada 95 and Ada 2005,
28352 declarations can appear in any order, so there is no restriction that
28353 would prevent this reordering, and if we write:
28354
28355 @smallexample @c ada
28356 @group
28357 @cartouche
28358 function One return Float;
28359
28360 function One return Float is
28361 begin
28362      return 1.0;
28363 end One;
28364
28365 Q : Float := One;
28366 @end cartouche
28367 @end group
28368 @end smallexample
28369
28370 @noindent
28371 then all is well, no warning is generated, and no
28372 @code{Program_Error} exception
28373 will be raised.
28374 Things are more complicated when a chain of subprograms is executed:
28375
28376 @smallexample @c ada
28377 @group
28378 @cartouche
28379 function A return Integer;
28380 function B return Integer;
28381 function C return Integer;
28382
28383 function B return Integer is begin return A; end;
28384 function C return Integer is begin return B; end;
28385
28386 X : Integer := C;
28387
28388 function A return Integer is begin return 1; end;
28389 @end cartouche
28390 @end group
28391 @end smallexample
28392
28393 @noindent
28394 Now the call to @code{C}
28395 at elaboration time in the declaration of @code{X} is correct, because
28396 the body of @code{C} is already elaborated,
28397 and the call to @code{B} within the body of
28398 @code{C} is correct, but the call
28399 to @code{A} within the body of @code{B} is incorrect, because the body
28400 of @code{A} has not been elaborated, so @code{Program_Error}
28401 will be raised on the call to @code{A}.
28402 In this case GNAT will generate a
28403 warning that @code{Program_Error} may be
28404 raised at the point of the call. Let's look at the warning:
28405
28406 @smallexample
28407 @group
28408 @cartouche
28409  1. procedure x is
28410  2.    function A return Integer;
28411  3.    function B return Integer;
28412  4.    function C return Integer;
28413  5.
28414  6.    function B return Integer is begin return A; end;
28415                                                     |
28416     >>> warning: call to "A" before body is elaborated may
28417                  raise Program_Error
28418     >>> warning: "B" called at line 7
28419     >>> warning: "C" called at line 9
28420
28421  7.    function C return Integer is begin return B; end;
28422  8.
28423  9.    X : Integer := C;
28424 10.
28425 11.    function A return Integer is begin return 1; end;
28426 12.
28427 13. begin
28428 14.    null;
28429 15. end;
28430 @end cartouche
28431 @end group
28432 @end smallexample
28433
28434 @noindent
28435 Note that the message here says ``may raise'', instead of the direct case,
28436 where the message says ``will be raised''. That's because whether
28437 @code{A} is
28438 actually called depends in general on run-time flow of control.
28439 For example, if the body of @code{B} said
28440
28441 @smallexample @c ada
28442 @group
28443 @cartouche
28444 function B return Integer is
28445 begin
28446    if some-condition-depending-on-input-data then
28447       return A;
28448    else
28449       return 1;
28450    end if;
28451 end B;
28452 @end cartouche
28453 @end group
28454 @end smallexample
28455
28456 @noindent
28457 then we could not know until run time whether the incorrect call to A would
28458 actually occur, so @code{Program_Error} might
28459 or might not be raised. It is possible for a compiler to
28460 do a better job of analyzing bodies, to
28461 determine whether or not @code{Program_Error}
28462 might be raised, but it certainly
28463 couldn't do a perfect job (that would require solving the halting problem
28464 and is provably impossible), and because this is a warning anyway, it does
28465 not seem worth the effort to do the analysis. Cases in which it
28466 would be relevant are rare.
28467
28468 In practice, warnings of either of the forms given
28469 above will usually correspond to
28470 real errors, and should be examined carefully and eliminated.
28471 In the rare case where a warning is bogus, it can be suppressed by any of
28472 the following methods:
28473
28474 @itemize @bullet
28475 @item
28476 Compile with the @option{-gnatws} switch set
28477
28478 @item
28479 Suppress @code{Elaboration_Check} for the called subprogram
28480
28481 @item
28482 Use pragma @code{Warnings_Off} to turn warnings off for the call
28483 @end itemize
28484
28485 @noindent
28486 For the internal elaboration check case,
28487 GNAT by default generates the
28488 necessary run-time checks to ensure
28489 that @code{Program_Error} is raised if any
28490 call fails an elaboration check. Of course this can only happen if a
28491 warning has been issued as described above. The use of pragma
28492 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
28493 some of these checks, meaning that it may be possible (but is not
28494 guaranteed) for a program to be able to call a subprogram whose body
28495 is not yet elaborated, without raising a @code{Program_Error} exception.
28496
28497 @node Controlling Elaboration in GNAT - External Calls
28498 @section Controlling Elaboration in GNAT - External Calls
28499
28500 @noindent
28501 The previous section discussed the case in which the execution of a
28502 particular thread of elaboration code occurred entirely within a
28503 single unit. This is the easy case to handle, because a programmer
28504 has direct and total control over the order of elaboration, and
28505 furthermore, checks need only be generated in cases which are rare
28506 and which the compiler can easily detect.
28507 The situation is more complex when separate compilation is taken into account.
28508 Consider the following:
28509
28510 @smallexample @c ada
28511 @cartouche
28512 @group
28513 package Math is
28514    function Sqrt (Arg : Float) return Float;
28515 end Math;
28516
28517 package body Math is
28518    function Sqrt (Arg : Float) return Float is
28519    begin
28520          @dots{}
28521    end Sqrt;
28522 end Math;
28523 @end group
28524 @group
28525 with Math;
28526 package Stuff is
28527    X : Float := Math.Sqrt (0.5);
28528 end Stuff;
28529
28530 with Stuff;
28531 procedure Main is
28532 begin
28533    @dots{}
28534 end Main;
28535 @end group
28536 @end cartouche
28537 @end smallexample
28538
28539 @noindent
28540 where @code{Main} is the main program. When this program is executed, the
28541 elaboration code must first be executed, and one of the jobs of the
28542 binder is to determine the order in which the units of a program are
28543 to be elaborated. In this case we have four units: the spec and body
28544 of @code{Math},
28545 the spec of @code{Stuff} and the body of @code{Main}).
28546 In what order should the four separate sections of elaboration code
28547 be executed?
28548
28549 There are some restrictions in the order of elaboration that the binder
28550 can choose. In particular, if unit U has a @code{with}
28551 for a package @code{X}, then you
28552 are assured that the spec of @code{X}
28553 is elaborated before U , but you are
28554 not assured that the body of @code{X}
28555 is elaborated before U.
28556 This means that in the above case, the binder is allowed to choose the
28557 order:
28558
28559 @smallexample
28560 spec of Math
28561 spec of Stuff
28562 body of Math
28563 body of Main
28564 @end smallexample
28565
28566 @noindent
28567 but that's not good, because now the call to @code{Math.Sqrt}
28568 that happens during
28569 the elaboration of the @code{Stuff}
28570 spec happens before the body of @code{Math.Sqrt} is
28571 elaborated, and hence causes @code{Program_Error} exception to be raised.
28572 At first glance, one might say that the binder is misbehaving, because
28573 obviously you want to elaborate the body of something you @code{with}
28574 first, but
28575 that is not a general rule that can be followed in all cases. Consider
28576
28577 @smallexample @c ada
28578 @group
28579 @cartouche
28580 package X is @dots{}
28581
28582 package Y is @dots{}
28583
28584 with X;
28585 package body Y is @dots{}
28586
28587 with Y;
28588 package body X is @dots{}
28589 @end cartouche
28590 @end group
28591 @end smallexample
28592
28593 @noindent
28594 This is a common arrangement, and, apart from the order of elaboration
28595 problems that might arise in connection with elaboration code, this works fine.
28596 A rule that says that you must first elaborate the body of anything you
28597 @code{with} cannot work in this case:
28598 the body of @code{X} @code{with}'s @code{Y},
28599 which means you would have to
28600 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
28601 which means
28602 you have to elaborate the body of @code{X} first, but @dots{} and we have a
28603 loop that cannot be broken.
28604
28605 It is true that the binder can in many cases guess an order of elaboration
28606 that is unlikely to cause a @code{Program_Error}
28607 exception to be raised, and it tries to do so (in the
28608 above example of @code{Math/Stuff/Spec}, the GNAT binder will
28609 by default
28610 elaborate the body of @code{Math} right after its spec, so all will be well).
28611
28612 However, a program that blindly relies on the binder to be helpful can
28613 get into trouble, as we discussed in the previous sections, so
28614 GNAT
28615 provides a number of facilities for assisting the programmer in
28616 developing programs that are robust with respect to elaboration order.
28617
28618 @node Default Behavior in GNAT - Ensuring Safety
28619 @section Default Behavior in GNAT - Ensuring Safety
28620
28621 @noindent
28622 The default behavior in GNAT ensures elaboration safety. In its
28623 default mode GNAT implements the
28624 rule we previously described as the right approach. Let's restate it:
28625
28626 @itemize
28627 @item
28628 @emph{If a unit has elaboration code that can directly or indirectly make a
28629 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
28630 package in a @code{with}'ed unit, then if the @code{with}'ed unit
28631 does not have pragma @code{Pure} or
28632 @code{Preelaborate}, then the client should have an
28633 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
28634
28635 @emph{In the case of instantiating a generic subprogram, it is always
28636 sufficient to have only an @code{Elaborate} pragma for the
28637 @code{with}'ed unit.}
28638 @end itemize
28639
28640 @noindent
28641 By following this rule a client is assured that calls and instantiations
28642 can be made without risk of an exception.
28643
28644 In this mode GNAT traces all calls that are potentially made from
28645 elaboration code, and puts in any missing implicit @code{Elaborate}
28646 and @code{Elaborate_All} pragmas.
28647 The advantage of this approach is that no elaboration problems
28648 are possible if the binder can find an elaboration order that is
28649 consistent with these implicit @code{Elaborate} and
28650 @code{Elaborate_All} pragmas. The
28651 disadvantage of this approach is that no such order may exist.
28652
28653 If the binder does not generate any diagnostics, then it means that it has
28654 found an elaboration order that is guaranteed to be safe. However, the binder
28655 may still be relying on implicitly generated @code{Elaborate} and
28656 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
28657 guaranteed.
28658
28659 If it is important to guarantee portability, then the compilations should
28660 use the
28661 @option{-gnatwl}
28662 (warn on elaboration problems) switch. This will cause warning messages
28663 to be generated indicating the missing @code{Elaborate} and
28664 @code{Elaborate_All} pragmas.
28665 Consider the following source program:
28666
28667 @smallexample @c ada
28668 @group
28669 @cartouche
28670 with k;
28671 package j is
28672   m : integer := k.r;
28673 end;
28674 @end cartouche
28675 @end group
28676 @end smallexample
28677
28678 @noindent
28679 where it is clear that there
28680 should be a pragma @code{Elaborate_All}
28681 for unit @code{k}. An implicit pragma will be generated, and it is
28682 likely that the binder will be able to honor it. However, if you want
28683 to port this program to some other Ada compiler than GNAT.
28684 it is safer to include the pragma explicitly in the source. If this
28685 unit is compiled with the
28686 @option{-gnatwl}
28687 switch, then the compiler outputs a warning:
28688
28689 @smallexample
28690 @group
28691 @cartouche
28692 1. with k;
28693 2. package j is
28694 3.   m : integer := k.r;
28695                      |
28696    >>> warning: call to "r" may raise Program_Error
28697    >>> warning: missing pragma Elaborate_All for "k"
28698
28699 4. end;
28700 @end cartouche
28701 @end group
28702 @end smallexample
28703
28704 @noindent
28705 and these warnings can be used as a guide for supplying manually
28706 the missing pragmas. It is usually a bad idea to use this warning
28707 option during development. That's because it will warn you when
28708 you need to put in a pragma, but cannot warn you when it is time
28709 to take it out. So the use of pragma @code{Elaborate_All} may lead to
28710 unnecessary dependencies and even false circularities.
28711
28712 This default mode is more restrictive than the Ada Reference
28713 Manual, and it is possible to construct programs which will compile
28714 using the dynamic model described there, but will run into a
28715 circularity using the safer static model we have described.
28716
28717 Of course any Ada compiler must be able to operate in a mode
28718 consistent with the requirements of the Ada Reference Manual,
28719 and in particular must have the capability of implementing the
28720 standard dynamic model of elaboration with run-time checks.
28721
28722 In GNAT, this standard mode can be achieved either by the use of
28723 the @option{-gnatE} switch on the compiler (@command{gcc} or
28724 @command{gnatmake}) command, or by the use of the configuration pragma:
28725
28726 @smallexample @c ada
28727 pragma Elaboration_Checks (DYNAMIC);
28728 @end smallexample
28729
28730 @noindent
28731 Either approach will cause the unit affected to be compiled using the
28732 standard dynamic run-time elaboration checks described in the Ada
28733 Reference Manual. The static model is generally preferable, since it
28734 is clearly safer to rely on compile and link time checks rather than
28735 run-time checks. However, in the case of legacy code, it may be
28736 difficult to meet the requirements of the static model. This
28737 issue is further discussed in
28738 @ref{What to Do If the Default Elaboration Behavior Fails}.
28739
28740 Note that the static model provides a strict subset of the allowed
28741 behavior and programs of the Ada Reference Manual, so if you do
28742 adhere to the static model and no circularities exist,
28743 then you are assured that your program will
28744 work using the dynamic model, providing that you remove any
28745 pragma Elaborate statements from the source.
28746
28747 @node Treatment of Pragma Elaborate
28748 @section Treatment of Pragma Elaborate
28749 @cindex Pragma Elaborate
28750
28751 @noindent
28752 The use of @code{pragma Elaborate}
28753 should generally be avoided in Ada 95 and Ada 2005 programs,
28754 since there is no guarantee that transitive calls
28755 will be properly handled. Indeed at one point, this pragma was placed
28756 in Annex J (Obsolescent Features), on the grounds that it is never useful.
28757
28758 Now that's a bit restrictive. In practice, the case in which
28759 @code{pragma Elaborate} is useful is when the caller knows that there
28760 are no transitive calls, or that the called unit contains all necessary
28761 transitive @code{pragma Elaborate} statements, and legacy code often
28762 contains such uses.
28763
28764 Strictly speaking the static mode in GNAT should ignore such pragmas,
28765 since there is no assurance at compile time that the necessary safety
28766 conditions are met. In practice, this would cause GNAT to be incompatible
28767 with correctly written Ada 83 code that had all necessary
28768 @code{pragma Elaborate} statements in place. Consequently, we made the
28769 decision that GNAT in its default mode will believe that if it encounters
28770 a @code{pragma Elaborate} then the programmer knows what they are doing,
28771 and it will trust that no elaboration errors can occur.
28772
28773 The result of this decision is two-fold. First to be safe using the
28774 static mode, you should remove all @code{pragma Elaborate} statements.
28775 Second, when fixing circularities in existing code, you can selectively
28776 use @code{pragma Elaborate} statements to convince the static mode of
28777 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
28778 statement.
28779
28780 When using the static mode with @option{-gnatwl}, any use of
28781 @code{pragma Elaborate} will generate a warning about possible
28782 problems.
28783
28784 @node Elaboration Issues for Library Tasks
28785 @section Elaboration Issues for Library Tasks
28786 @cindex Library tasks, elaboration issues
28787 @cindex Elaboration of library tasks
28788
28789 @noindent
28790 In this section we examine special elaboration issues that arise for
28791 programs that declare library level tasks.
28792
28793 Generally the model of execution of an Ada program is that all units are
28794 elaborated, and then execution of the program starts. However, the
28795 declaration of library tasks definitely does not fit this model. The
28796 reason for this is that library tasks start as soon as they are declared
28797 (more precisely, as soon as the statement part of the enclosing package
28798 body is reached), that is to say before elaboration
28799 of the program is complete. This means that if such a task calls a
28800 subprogram, or an entry in another task, the callee may or may not be
28801 elaborated yet, and in the standard
28802 Reference Manual model of dynamic elaboration checks, you can even
28803 get timing dependent Program_Error exceptions, since there can be
28804 a race between the elaboration code and the task code.
28805
28806 The static model of elaboration in GNAT seeks to avoid all such
28807 dynamic behavior, by being conservative, and the conservative
28808 approach in this particular case is to assume that all the code
28809 in a task body is potentially executed at elaboration time if
28810 a task is declared at the library level.
28811
28812 This can definitely result in unexpected circularities. Consider
28813 the following example
28814
28815 @smallexample @c ada
28816 package Decls is
28817   task Lib_Task is
28818      entry Start;
28819   end Lib_Task;
28820
28821   type My_Int is new Integer;
28822
28823   function Ident (M : My_Int) return My_Int;
28824 end Decls;
28825
28826 with Utils;
28827 package body Decls is
28828   task body Lib_Task is
28829   begin
28830      accept Start;
28831      Utils.Put_Val (2);
28832   end Lib_Task;
28833
28834   function Ident (M : My_Int) return My_Int is
28835   begin
28836      return M;
28837   end Ident;
28838 end Decls;
28839
28840 with Decls;
28841 package Utils is
28842   procedure Put_Val (Arg : Decls.My_Int);
28843 end Utils;
28844
28845 with Text_IO;
28846 package body Utils is
28847   procedure Put_Val (Arg : Decls.My_Int) is
28848   begin
28849      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28850   end Put_Val;
28851 end Utils;
28852
28853 with Decls;
28854 procedure Main is
28855 begin
28856    Decls.Lib_Task.Start;
28857 end;
28858 @end smallexample
28859
28860 @noindent
28861 If the above example is compiled in the default static elaboration
28862 mode, then a circularity occurs. The circularity comes from the call
28863 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
28864 this call occurs in elaboration code, we need an implicit pragma
28865 @code{Elaborate_All} for @code{Utils}. This means that not only must
28866 the spec and body of @code{Utils} be elaborated before the body
28867 of @code{Decls}, but also the spec and body of any unit that is
28868 @code{with'ed} by the body of @code{Utils} must also be elaborated before
28869 the body of @code{Decls}. This is the transitive implication of
28870 pragma @code{Elaborate_All} and it makes sense, because in general
28871 the body of @code{Put_Val} might have a call to something in a
28872 @code{with'ed} unit.
28873
28874 In this case, the body of Utils (actually its spec) @code{with's}
28875 @code{Decls}. Unfortunately this means that the body of @code{Decls}
28876 must be elaborated before itself, in case there is a call from the
28877 body of @code{Utils}.
28878
28879 Here is the exact chain of events we are worrying about:
28880
28881 @enumerate
28882 @item
28883 In the body of @code{Decls} a call is made from within the body of a library
28884 task to a subprogram in the package @code{Utils}. Since this call may
28885 occur at elaboration time (given that the task is activated at elaboration
28886 time), we have to assume the worst, i.e., that the
28887 call does happen at elaboration time.
28888
28889 @item
28890 This means that the body and spec of @code{Util} must be elaborated before
28891 the body of @code{Decls} so that this call does not cause an access before
28892 elaboration.
28893
28894 @item
28895 Within the body of @code{Util}, specifically within the body of
28896 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
28897 by this package.
28898
28899 @item
28900 One such @code{with}'ed package is package @code{Decls}, so there
28901 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
28902 In fact there is such a call in this example, but we would have to
28903 assume that there was such a call even if it were not there, since
28904 we are not supposed to write the body of @code{Decls} knowing what
28905 is in the body of @code{Utils}; certainly in the case of the
28906 static elaboration model, the compiler does not know what is in
28907 other bodies and must assume the worst.
28908
28909 @item
28910 This means that the spec and body of @code{Decls} must also be
28911 elaborated before we elaborate the unit containing the call, but
28912 that unit is @code{Decls}! This means that the body of @code{Decls}
28913 must be elaborated before itself, and that's a circularity.
28914 @end enumerate
28915
28916 @noindent
28917 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
28918 the body of @code{Decls} you will get a true Ada Reference Manual
28919 circularity that makes the program illegal.
28920
28921 In practice, we have found that problems with the static model of
28922 elaboration in existing code often arise from library tasks, so
28923 we must address this particular situation.
28924
28925 Note that if we compile and run the program above, using the dynamic model of
28926 elaboration (that is to say use the @option{-gnatE} switch),
28927 then it compiles, binds,
28928 links, and runs, printing the expected result of 2. Therefore in some sense
28929 the circularity here is only apparent, and we need to capture
28930 the properties of this program that  distinguish it from other library-level
28931 tasks that have real elaboration problems.
28932
28933 We have four possible answers to this question:
28934
28935 @itemize @bullet
28936
28937 @item
28938 Use the dynamic model of elaboration.
28939
28940 If we use the @option{-gnatE} switch, then as noted above, the program works.
28941 Why is this? If we examine the task body, it is apparent that the task cannot
28942 proceed past the
28943 @code{accept} statement until after elaboration has been completed, because
28944 the corresponding entry call comes from the main program, not earlier.
28945 This is why the dynamic model works here. But that's really giving
28946 up on a precise analysis, and we prefer to take this approach only if we cannot
28947 solve the
28948 problem in any other manner. So let us examine two ways to reorganize
28949 the program to avoid the potential elaboration problem.
28950
28951 @item
28952 Split library tasks into separate packages.
28953
28954 Write separate packages, so that library tasks are isolated from
28955 other declarations as much as possible. Let us look at a variation on
28956 the above program.
28957
28958 @smallexample @c ada
28959 package Decls1 is
28960   task Lib_Task is
28961      entry Start;
28962   end Lib_Task;
28963 end Decls1;
28964
28965 with Utils;
28966 package body Decls1 is
28967   task body Lib_Task is
28968   begin
28969      accept Start;
28970      Utils.Put_Val (2);
28971   end Lib_Task;
28972 end Decls1;
28973
28974 package Decls2 is
28975   type My_Int is new Integer;
28976   function Ident (M : My_Int) return My_Int;
28977 end Decls2;
28978
28979 with Utils;
28980 package body Decls2 is
28981   function Ident (M : My_Int) return My_Int is
28982   begin
28983      return M;
28984   end Ident;
28985 end Decls2;
28986
28987 with Decls2;
28988 package Utils is
28989   procedure Put_Val (Arg : Decls2.My_Int);
28990 end Utils;
28991
28992 with Text_IO;
28993 package body Utils is
28994   procedure Put_Val (Arg : Decls2.My_Int) is
28995   begin
28996      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
28997   end Put_Val;
28998 end Utils;
28999
29000 with Decls1;
29001 procedure Main is
29002 begin
29003    Decls1.Lib_Task.Start;
29004 end;
29005 @end smallexample
29006
29007 @noindent
29008 All we have done is to split @code{Decls} into two packages, one
29009 containing the library task, and one containing everything else. Now
29010 there is no cycle, and the program compiles, binds, links and executes
29011 using the default static model of elaboration.
29012
29013 @item
29014 Declare separate task types.
29015
29016 A significant part of the problem arises because of the use of the
29017 single task declaration form. This means that the elaboration of
29018 the task type, and the elaboration of the task itself (i.e.@: the
29019 creation of the task) happen at the same time. A good rule
29020 of style in Ada is to always create explicit task types. By
29021 following the additional step of placing task objects in separate
29022 packages from the task type declaration, many elaboration problems
29023 are avoided. Here is another modified example of the example program:
29024
29025 @smallexample @c ada
29026 package Decls is
29027   task type Lib_Task_Type is
29028      entry Start;
29029   end Lib_Task_Type;
29030
29031   type My_Int is new Integer;
29032
29033   function Ident (M : My_Int) return My_Int;
29034 end Decls;
29035
29036 with Utils;
29037 package body Decls is
29038   task body Lib_Task_Type is
29039   begin
29040      accept Start;
29041      Utils.Put_Val (2);
29042   end Lib_Task_Type;
29043
29044   function Ident (M : My_Int) return My_Int is
29045   begin
29046      return M;
29047   end Ident;
29048 end Decls;
29049
29050 with Decls;
29051 package Utils is
29052   procedure Put_Val (Arg : Decls.My_Int);
29053 end Utils;
29054
29055 with Text_IO;
29056 package body Utils is
29057   procedure Put_Val (Arg : Decls.My_Int) is
29058   begin
29059      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
29060   end Put_Val;
29061 end Utils;
29062
29063 with Decls;
29064 package Declst is
29065    Lib_Task : Decls.Lib_Task_Type;
29066 end Declst;
29067
29068 with Declst;
29069 procedure Main is
29070 begin
29071    Declst.Lib_Task.Start;
29072 end;
29073 @end smallexample
29074
29075 @noindent
29076 What we have done here is to replace the @code{task} declaration in
29077 package @code{Decls} with a @code{task type} declaration. Then we
29078 introduce a separate package @code{Declst} to contain the actual
29079 task object. This separates the elaboration issues for
29080 the @code{task type}
29081 declaration, which causes no trouble, from the elaboration issues
29082 of the task object, which is also unproblematic, since it is now independent
29083 of the elaboration of  @code{Utils}.
29084 This separation of concerns also corresponds to
29085 a generally sound engineering principle of separating declarations
29086 from instances. This version of the program also compiles, binds, links,
29087 and executes, generating the expected output.
29088
29089 @item
29090 Use No_Entry_Calls_In_Elaboration_Code restriction.
29091 @cindex No_Entry_Calls_In_Elaboration_Code
29092
29093 The previous two approaches described how a program can be restructured
29094 to avoid the special problems caused by library task bodies. in practice,
29095 however, such restructuring may be difficult to apply to existing legacy code,
29096 so we must consider solutions that do not require massive rewriting.
29097
29098 Let us consider more carefully why our original sample program works
29099 under the dynamic model of elaboration. The reason is that the code
29100 in the task body blocks immediately on the @code{accept}
29101 statement. Now of course there is nothing to prohibit elaboration
29102 code from making entry calls (for example from another library level task),
29103 so we cannot tell in isolation that
29104 the task will not execute the accept statement  during elaboration.
29105
29106 However, in practice it is very unusual to see elaboration code
29107 make any entry calls, and the pattern of tasks starting
29108 at elaboration time and then immediately blocking on @code{accept} or
29109 @code{select} statements is very common. What this means is that
29110 the compiler is being too pessimistic when it analyzes the
29111 whole package body as though it might be executed at elaboration
29112 time.
29113
29114 If we know that the elaboration code contains no entry calls, (a very safe
29115 assumption most of the time, that could almost be made the default
29116 behavior), then we can compile all units of the program under control
29117 of the following configuration pragma:
29118
29119 @smallexample
29120 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
29121 @end smallexample
29122
29123 @noindent
29124 This pragma can be placed in the @file{gnat.adc} file in the usual
29125 manner. If we take our original unmodified program and compile it
29126 in the presence of a @file{gnat.adc} containing the above pragma,
29127 then once again, we can compile, bind, link, and execute, obtaining
29128 the expected result. In the presence of this pragma, the compiler does
29129 not trace calls in a task body, that appear after the first @code{accept}
29130 or @code{select} statement, and therefore does not report a potential
29131 circularity in the original program.
29132
29133 The compiler will check to the extent it can that the above
29134 restriction is not violated, but it is not always possible to do a
29135 complete check at compile time, so it is important to use this
29136 pragma only if the stated restriction is in fact met, that is to say
29137 no task receives an entry call before elaboration of all units is completed.
29138
29139 @end itemize
29140
29141 @node Mixing Elaboration Models
29142 @section Mixing Elaboration Models
29143 @noindent
29144 So far, we have assumed that the entire program is either compiled
29145 using the dynamic model or static model, ensuring consistency. It
29146 is possible to mix the two models, but rules have to be followed
29147 if this mixing is done to ensure that elaboration checks are not
29148 omitted.
29149
29150 The basic rule is that @emph{a unit compiled with the static model cannot
29151 be @code{with'ed} by a unit compiled with the dynamic model}. The
29152 reason for this is that in the static model, a unit assumes that
29153 its clients guarantee to use (the equivalent of) pragma
29154 @code{Elaborate_All} so that no elaboration checks are required
29155 in inner subprograms, and this assumption is violated if the
29156 client is compiled with dynamic checks.
29157
29158 The precise rule is as follows. A unit that is compiled with dynamic
29159 checks can only @code{with} a unit that meets at least one of the
29160 following criteria:
29161
29162 @itemize @bullet
29163
29164 @item
29165 The @code{with'ed} unit is itself compiled with dynamic elaboration
29166 checks (that is with the @option{-gnatE} switch.
29167
29168 @item
29169 The @code{with'ed} unit is an internal GNAT implementation unit from
29170 the System, Interfaces, Ada, or GNAT hierarchies.
29171
29172 @item
29173 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
29174
29175 @item
29176 The @code{with'ing} unit (that is the client) has an explicit pragma
29177 @code{Elaborate_All} for the @code{with'ed} unit.
29178
29179 @end itemize
29180
29181 @noindent
29182 If this rule is violated, that is if a unit with dynamic elaboration
29183 checks @code{with's} a unit that does not meet one of the above four
29184 criteria, then the binder (@code{gnatbind}) will issue a warning
29185 similar to that in the following example:
29186
29187 @smallexample
29188 warning: "x.ads" has dynamic elaboration checks and with's
29189 warning:   "y.ads" which has static elaboration checks
29190 @end smallexample
29191
29192 @noindent
29193 These warnings indicate that the rule has been violated, and that as a result
29194 elaboration checks may be missed in the resulting executable file.
29195 This warning may be suppressed using the @option{-ws} binder switch
29196 in the usual manner.
29197
29198 One useful application of this mixing rule is in the case of a subsystem
29199 which does not itself @code{with} units from the remainder of the
29200 application. In this case, the entire subsystem can be compiled with
29201 dynamic checks to resolve a circularity in the subsystem, while
29202 allowing the main application that uses this subsystem to be compiled
29203 using the more reliable default static model.
29204
29205 @node What to Do If the Default Elaboration Behavior Fails
29206 @section What to Do If the Default Elaboration Behavior Fails
29207
29208 @noindent
29209 If the binder cannot find an acceptable order, it outputs detailed
29210 diagnostics. For example:
29211 @smallexample
29212 @group
29213 @iftex
29214 @leftskip=0cm
29215 @end iftex
29216 error: elaboration circularity detected
29217 info:   "proc (body)" must be elaborated before "pack (body)"
29218 info:     reason: Elaborate_All probably needed in unit "pack (body)"
29219 info:     recompile "pack (body)" with -gnatwl
29220 info:                             for full details
29221 info:       "proc (body)"
29222 info:         is needed by its spec:
29223 info:       "proc (spec)"
29224 info:         which is withed by:
29225 info:       "pack (body)"
29226 info:  "pack (body)" must be elaborated before "proc (body)"
29227 info:     reason: pragma Elaborate in unit "proc (body)"
29228 @end group
29229
29230 @end smallexample
29231
29232 @noindent
29233 In this case we have a cycle that the binder cannot break. On the one
29234 hand, there is an explicit pragma Elaborate in @code{proc} for
29235 @code{pack}. This means that the body of @code{pack} must be elaborated
29236 before the body of @code{proc}. On the other hand, there is elaboration
29237 code in @code{pack} that calls a subprogram in @code{proc}. This means
29238 that for maximum safety, there should really be a pragma
29239 Elaborate_All in @code{pack} for @code{proc} which would require that
29240 the body of @code{proc} be elaborated before the body of
29241 @code{pack}. Clearly both requirements cannot be satisfied.
29242 Faced with a circularity of this kind, you have three different options.
29243
29244 @table @asis
29245 @item Fix the program
29246 The most desirable option from the point of view of long-term maintenance
29247 is to rearrange the program so that the elaboration problems are avoided.
29248 One useful technique is to place the elaboration code into separate
29249 child packages. Another is to move some of the initialization code to
29250 explicitly called subprograms, where the program controls the order
29251 of initialization explicitly. Although this is the most desirable option,
29252 it may be impractical and involve too much modification, especially in
29253 the case of complex legacy code.
29254
29255 @item Perform dynamic checks
29256 If the compilations are done using the
29257 @option{-gnatE}
29258 (dynamic elaboration check) switch, then GNAT behaves in a quite different
29259 manner. Dynamic checks are generated for all calls that could possibly result
29260 in raising an exception. With this switch, the compiler does not generate
29261 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
29262 exactly as specified in the @cite{Ada Reference Manual}.
29263 The binder will generate
29264 an executable program that may or may not raise @code{Program_Error}, and then
29265 it is the programmer's job to ensure that it does not raise an exception. Note
29266 that it is important to compile all units with the switch, it cannot be used
29267 selectively.
29268
29269 @item Suppress checks
29270 The drawback of dynamic checks is that they generate a
29271 significant overhead at run time, both in space and time. If you
29272 are absolutely sure that your program cannot raise any elaboration
29273 exceptions, and you still want to use the dynamic elaboration model,
29274 then you can use the configuration pragma
29275 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
29276 example this pragma could be placed in the @file{gnat.adc} file.
29277
29278 @item Suppress checks selectively
29279 When you know that certain calls or instantiations in elaboration code cannot
29280 possibly lead to an elaboration error, and the binder nevertheless complains
29281 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
29282 elaboration circularities, it is possible to remove those warnings locally and
29283 obtain a program that will bind. Clearly this can be unsafe, and it is the
29284 responsibility of the programmer to make sure that the resulting program has no
29285 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
29286 used with different granularity to suppress warnings and break elaboration
29287 circularities:
29288
29289 @itemize @bullet
29290 @item
29291 Place the pragma that names the called subprogram in the declarative part
29292 that contains the call.
29293
29294 @item
29295 Place the pragma in the declarative part, without naming an entity. This
29296 disables warnings on all calls in the corresponding  declarative region.
29297
29298 @item
29299 Place the pragma in the package spec that declares the called subprogram,
29300 and name the subprogram. This disables warnings on all elaboration calls to
29301 that subprogram.
29302
29303 @item
29304 Place the pragma in the package spec that declares the called subprogram,
29305 without naming any entity. This disables warnings on all elaboration calls to
29306 all subprograms declared in this spec.
29307
29308 @item Use Pragma Elaborate
29309 As previously described in section @xref{Treatment of Pragma Elaborate},
29310 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
29311 that no elaboration checks are required on calls to the designated unit.
29312 There may be cases in which the caller knows that no transitive calls
29313 can occur, so that a @code{pragma Elaborate} will be sufficient in a
29314 case where @code{pragma Elaborate_All} would cause a circularity.
29315 @end itemize
29316
29317 @noindent
29318 These five cases are listed in order of decreasing safety, and therefore
29319 require increasing programmer care in their application. Consider the
29320 following program:
29321
29322 @smallexample @c adanocomment
29323 package Pack1 is
29324   function F1 return Integer;
29325   X1 : Integer;
29326 end Pack1;
29327
29328 package Pack2 is
29329   function F2 return Integer;
29330   function Pure (x : integer) return integer;
29331   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
29332   --  pragma Suppress (Elaboration_Check);              -- (4)
29333 end Pack2;
29334
29335 with Pack2;
29336 package body Pack1 is
29337   function F1 return Integer is
29338   begin
29339     return 100;
29340   end F1;
29341   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
29342 begin
29343   declare
29344     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
29345     --  pragma Suppress(Elaboration_Check);             -- (2)
29346   begin
29347     X1 := Pack2.F2 + 1;                --  Elab. call (2)
29348   end;
29349 end Pack1;
29350
29351 with Pack1;
29352 package body Pack2 is
29353   function F2 return Integer is
29354   begin
29355      return Pack1.F1;
29356   end F2;
29357   function Pure (x : integer) return integer is
29358   begin
29359      return x ** 3 - 3 * x;
29360   end;
29361 end Pack2;
29362
29363 with Pack1, Ada.Text_IO;
29364 procedure Proc3 is
29365 begin
29366   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
29367 end Proc3;
29368 @end smallexample
29369 In the absence of any pragmas, an attempt to bind this program produces
29370 the following diagnostics:
29371 @smallexample
29372 @group
29373 @iftex
29374 @leftskip=.5cm
29375 @end iftex
29376 error: elaboration circularity detected
29377 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
29378 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
29379 info:       recompile "pack1 (body)" with -gnatwl for full details
29380 info:          "pack1 (body)"
29381 info:             must be elaborated along with its spec:
29382 info:          "pack1 (spec)"
29383 info:             which is withed by:
29384 info:          "pack2 (body)"
29385 info:             which must be elaborated along with its spec:
29386 info:          "pack2 (spec)"
29387 info:             which is withed by:
29388 info:          "pack1 (body)"
29389 @end group
29390 @end smallexample
29391 The sources of the circularity are the two calls to @code{Pack2.Pure} and
29392 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
29393 F2 is safe, even though F2 calls F1, because the call appears after the
29394 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
29395 remove the warning on the call. It is also possible to use pragma (2)
29396 because there are no other potentially unsafe calls in the block.
29397
29398 @noindent
29399 The call to @code{Pure} is safe because this function does not depend on the
29400 state of @code{Pack2}. Therefore any call to this function is safe, and it
29401 is correct to place pragma (3) in the corresponding package spec.
29402
29403 @noindent
29404 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
29405 warnings on all calls to functions declared therein. Note that this is not
29406 necessarily safe, and requires more detailed examination of the subprogram
29407 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
29408 be already elaborated.
29409 @end table
29410
29411 @noindent
29412 It is hard to generalize on which of these four approaches should be
29413 taken. Obviously if it is possible to fix the program so that the default
29414 treatment works, this is preferable, but this may not always be practical.
29415 It is certainly simple enough to use
29416 @option{-gnatE}
29417 but the danger in this case is that, even if the GNAT binder
29418 finds a correct elaboration order, it may not always do so,
29419 and certainly a binder from another Ada compiler might not. A
29420 combination of testing and analysis (for which the warnings generated
29421 with the
29422 @option{-gnatwl}
29423 switch can be useful) must be used to ensure that the program is free
29424 of errors. One switch that is useful in this testing is the
29425 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
29426 switch for
29427 @code{gnatbind}.
29428 Normally the binder tries to find an order that has the best chance
29429 of avoiding elaboration problems. However, if this switch is used, the binder
29430 plays a devil's advocate role, and tries to choose the order that
29431 has the best chance of failing. If your program works even with this
29432 switch, then it has a better chance of being error free, but this is still
29433 not a guarantee.
29434
29435 For an example of this approach in action, consider the C-tests (executable
29436 tests) from the ACVC suite. If these are compiled and run with the default
29437 treatment, then all but one of them succeed without generating any error
29438 diagnostics from the binder. However, there is one test that fails, and
29439 this is not surprising, because the whole point of this test is to ensure
29440 that the compiler can handle cases where it is impossible to determine
29441 a correct order statically, and it checks that an exception is indeed
29442 raised at run time.
29443
29444 This one test must be compiled and run using the
29445 @option{-gnatE}
29446 switch, and then it passes. Alternatively, the entire suite can
29447 be run using this switch. It is never wrong to run with the dynamic
29448 elaboration switch if your code is correct, and we assume that the
29449 C-tests are indeed correct (it is less efficient, but efficiency is
29450 not a factor in running the ACVC tests.)
29451
29452 @node Elaboration for Access-to-Subprogram Values
29453 @section Elaboration for Access-to-Subprogram Values
29454 @cindex Access-to-subprogram
29455
29456 @noindent
29457 Access-to-subprogram types (introduced in Ada 95) complicate
29458 the handling of elaboration. The trouble is that it becomes
29459 impossible to tell at compile time which procedure
29460 is being called. This means that it is not possible for the binder
29461 to analyze the elaboration requirements in this case.
29462
29463 If at the point at which the access value is created
29464 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
29465 the body of the subprogram is
29466 known to have been elaborated, then the access value is safe, and its use
29467 does not require a check. This may be achieved by appropriate arrangement
29468 of the order of declarations if the subprogram is in the current unit,
29469 or, if the subprogram is in another unit, by using pragma
29470 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
29471 on the referenced unit.
29472
29473 If the referenced body is not known to have been elaborated at the point
29474 the access value is created, then any use of the access value must do a
29475 dynamic check, and this dynamic check will fail and raise a
29476 @code{Program_Error} exception if the body has not been elaborated yet.
29477 GNAT will generate the necessary checks, and in addition, if the
29478 @option{-gnatwl}
29479 switch is set, will generate warnings that such checks are required.
29480
29481 The use of dynamic dispatching for tagged types similarly generates
29482 a requirement for dynamic checks, and premature calls to any primitive
29483 operation of a tagged type before the body of the operation has been
29484 elaborated, will result in the raising of @code{Program_Error}.
29485
29486 @node Summary of Procedures for Elaboration Control
29487 @section Summary of Procedures for Elaboration Control
29488 @cindex Elaboration control
29489
29490 @noindent
29491 First, compile your program with the default options, using none of
29492 the special elaboration control switches. If the binder successfully
29493 binds your program, then you can be confident that, apart from issues
29494 raised by the use of access-to-subprogram types and dynamic dispatching,
29495 the program is free of elaboration errors. If it is important that the
29496 program be portable, then use the
29497 @option{-gnatwl}
29498 switch to generate warnings about missing @code{Elaborate} or
29499 @code{Elaborate_All} pragmas, and supply the missing pragmas.
29500
29501 If the program fails to bind using the default static elaboration
29502 handling, then you can fix the program to eliminate the binder
29503 message, or recompile the entire program with the
29504 @option{-gnatE} switch to generate dynamic elaboration checks,
29505 and, if you are sure there really are no elaboration problems,
29506 use a global pragma @code{Suppress (Elaboration_Check)}.
29507
29508 @node Other Elaboration Order Considerations
29509 @section Other Elaboration Order Considerations
29510 @noindent
29511 This section has been entirely concerned with the issue of finding a valid
29512 elaboration order, as defined by the Ada Reference Manual. In a case
29513 where several elaboration orders are valid, the task is to find one
29514 of the possible valid elaboration orders (and the static model in GNAT
29515 will ensure that this is achieved).
29516
29517 The purpose of the elaboration rules in the Ada Reference Manual is to
29518 make sure that no entity is accessed before it has been elaborated. For
29519 a subprogram, this means that the spec and body must have been elaborated
29520 before the subprogram is called. For an object, this means that the object
29521 must have been elaborated before its value is read or written. A violation
29522 of either of these two requirements is an access before elaboration order,
29523 and this section has been all about avoiding such errors.
29524
29525 In the case where more than one order of elaboration is possible, in the
29526 sense that access before elaboration errors are avoided, then any one of
29527 the orders is ``correct'' in the sense that it meets the requirements of
29528 the Ada Reference Manual, and no such error occurs.
29529
29530 However, it may be the case for a given program, that there are
29531 constraints on the order of elaboration that come not from consideration
29532 of avoiding elaboration errors, but rather from extra-lingual logic
29533 requirements. Consider this example:
29534
29535 @smallexample @c ada
29536 with Init_Constants;
29537 package Constants is
29538    X : Integer := 0;
29539    Y : Integer := 0;
29540 end Constants;
29541
29542 package Init_Constants is
29543    procedure P; -- require a body
29544 end Init_Constants;
29545
29546 with Constants;
29547 package body Init_Constants is
29548    procedure P is begin null; end;
29549 begin
29550    Constants.X := 3;
29551    Constants.Y := 4;
29552 end Init_Constants;
29553
29554 with Constants;
29555 package Calc is
29556    Z : Integer := Constants.X + Constants.Y;
29557 end Calc;
29558
29559 with Calc;
29560 with Text_IO; use Text_IO;
29561 procedure Main is
29562 begin
29563    Put_Line (Calc.Z'Img);
29564 end Main;
29565 @end smallexample
29566
29567 @noindent
29568 In this example, there is more than one valid order of elaboration. For
29569 example both the following are correct orders:
29570
29571 @smallexample
29572 Init_Constants spec
29573 Constants spec
29574 Calc spec
29575 Init_Constants body
29576 Main body
29577
29578   and
29579
29580 Init_Constants spec
29581 Init_Constants body
29582 Constants spec
29583 Calc spec
29584 Main body
29585 @end smallexample
29586
29587 @noindent
29588 There is no language rule to prefer one or the other, both are correct
29589 from an order of elaboration point of view. But the programmatic effects
29590 of the two orders are very different. In the first, the elaboration routine
29591 of @code{Calc} initializes @code{Z} to zero, and then the main program
29592 runs with this value of zero. But in the second order, the elaboration
29593 routine of @code{Calc} runs after the body of Init_Constants has set
29594 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
29595 runs.
29596
29597 One could perhaps by applying pretty clever non-artificial intelligence
29598 to the situation guess that it is more likely that the second order of
29599 elaboration is the one desired, but there is no formal linguistic reason
29600 to prefer one over the other. In fact in this particular case, GNAT will
29601 prefer the second order, because of the rule that bodies are elaborated
29602 as soon as possible, but it's just luck that this is what was wanted
29603 (if indeed the second order was preferred).
29604
29605 If the program cares about the order of elaboration routines in a case like
29606 this, it is important to specify the order required. In this particular
29607 case, that could have been achieved by adding to the spec of Calc:
29608
29609 @smallexample @c ada
29610 pragma Elaborate_All (Constants);
29611 @end smallexample
29612
29613 @noindent
29614 which requires that the body (if any) and spec of @code{Constants},
29615 as well as the body and spec of any unit @code{with}'ed by
29616 @code{Constants} be elaborated before @code{Calc} is elaborated.
29617
29618 Clearly no automatic method can always guess which alternative you require,
29619 and if you are working with legacy code that had constraints of this kind
29620 which were not properly specified by adding @code{Elaborate} or
29621 @code{Elaborate_All} pragmas, then indeed it is possible that two different
29622 compilers can choose different orders.
29623
29624 However, GNAT does attempt to diagnose the common situation where there
29625 are uninitialized variables in the visible part of a package spec, and the
29626 corresponding package body has an elaboration block that directly or
29627 indirectly initialized one or more of these variables. This is the situation
29628 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
29629 a warning that suggests this addition if it detects this situation.
29630
29631 The @code{gnatbind}
29632 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
29633 out problems. This switch causes bodies to be elaborated as late as possible
29634 instead of as early as possible. In the example above, it would have forced
29635 the choice of the first elaboration order. If you get different results
29636 when using this switch, and particularly if one set of results is right,
29637 and one is wrong as far as you are concerned, it shows that you have some
29638 missing @code{Elaborate} pragmas. For the example above, we have the
29639 following output:
29640
29641 @smallexample
29642 gnatmake -f -q main
29643 main
29644  7
29645 gnatmake -f -q main -bargs -p
29646 main
29647  0
29648 @end smallexample
29649
29650 @noindent
29651 It is of course quite unlikely that both these results are correct, so
29652 it is up to you in a case like this to investigate the source of the
29653 difference, by looking at the two elaboration orders that are chosen,
29654 and figuring out which is correct, and then adding the necessary
29655 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
29656
29657
29658
29659 @c *******************************
29660 @node Conditional Compilation
29661 @appendix Conditional Compilation
29662 @c *******************************
29663 @cindex Conditional compilation
29664
29665 @noindent
29666 It is often necessary to arrange for a single source program
29667 to serve multiple purposes, where it is compiled in different
29668 ways to achieve these different goals. Some examples of the
29669 need for this feature are
29670
29671 @itemize @bullet
29672 @item  Adapting a program to a different hardware environment
29673 @item  Adapting a program to a different target architecture
29674 @item  Turning debugging features on and off
29675 @item  Arranging for a program to compile with different compilers
29676 @end itemize
29677
29678 @noindent
29679 In C, or C++, the typical approach would be to use the preprocessor
29680 that is defined as part of the language. The Ada language does not
29681 contain such a feature. This is not an oversight, but rather a very
29682 deliberate design decision, based on the experience that overuse of
29683 the preprocessing features in C and C++ can result in programs that
29684 are extremely difficult to maintain. For example, if we have ten
29685 switches that can be on or off, this means that there are a thousand
29686 separate programs, any one of which might not even be syntactically
29687 correct, and even if syntactically correct, the resulting program
29688 might not work correctly. Testing all combinations can quickly become
29689 impossible.
29690
29691 Nevertheless, the need to tailor programs certainly exists, and in
29692 this Appendix we will discuss how this can
29693 be achieved using Ada in general, and GNAT in particular.
29694
29695 @menu
29696 * Use of Boolean Constants::
29697 * Debugging - A Special Case::
29698 * Conditionalizing Declarations::
29699 * Use of Alternative Implementations::
29700 * Preprocessing::
29701 @end menu
29702
29703 @node Use of Boolean Constants
29704 @section Use of Boolean Constants
29705
29706 @noindent
29707 In the case where the difference is simply which code
29708 sequence is executed, the cleanest solution is to use Boolean
29709 constants to control which code is executed.
29710
29711 @smallexample @c ada
29712 @group
29713 FP_Initialize_Required : constant Boolean := True;
29714 @dots{}
29715 if FP_Initialize_Required then
29716 @dots{}
29717 end if;
29718 @end group
29719 @end smallexample
29720
29721 @noindent
29722 Not only will the code inside the @code{if} statement not be executed if
29723 the constant Boolean is @code{False}, but it will also be completely
29724 deleted from the program.
29725 However, the code is only deleted after the @code{if} statement
29726 has been checked for syntactic and semantic correctness.
29727 (In contrast, with preprocessors the code is deleted before the
29728 compiler ever gets to see it, so it is not checked until the switch
29729 is turned on.)
29730 @cindex Preprocessors (contrasted with conditional compilation)
29731
29732 Typically the Boolean constants will be in a separate package,
29733 something like:
29734
29735 @smallexample @c ada
29736 @group
29737 package Config is
29738    FP_Initialize_Required : constant Boolean := True;
29739    Reset_Available        : constant Boolean := False;
29740    @dots{}
29741 end Config;
29742 @end group
29743 @end smallexample
29744
29745 @noindent
29746 The @code{Config} package exists in multiple forms for the various targets,
29747 with an appropriate script selecting the version of @code{Config} needed.
29748 Then any other unit requiring conditional compilation can do a @code{with}
29749 of @code{Config} to make the constants visible.
29750
29751
29752 @node Debugging - A Special Case
29753 @section Debugging - A Special Case
29754
29755 @noindent
29756 A common use of conditional code is to execute statements (for example
29757 dynamic checks, or output of intermediate results) under control of a
29758 debug switch, so that the debugging behavior can be turned on and off.
29759 This can be done using a Boolean constant to control whether the code
29760 is active:
29761
29762 @smallexample @c ada
29763 @group
29764 if Debugging then
29765    Put_Line ("got to the first stage!");
29766 end if;
29767 @end group
29768 @end smallexample
29769
29770 @noindent
29771 or
29772
29773 @smallexample @c ada
29774 @group
29775 if Debugging and then Temperature > 999.0 then
29776    raise Temperature_Crazy;
29777 end if;
29778 @end group
29779 @end smallexample
29780
29781 @noindent
29782 Since this is a common case, there are special features to deal with
29783 this in a convenient manner. For the case of tests, Ada 2005 has added
29784 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
29785 @cindex pragma @code{Assert}
29786 on the @code{Assert} pragma that has always been available in GNAT, so this
29787 feature may be used with GNAT even if you are not using Ada 2005 features.
29788 The use of pragma @code{Assert} is described in
29789 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
29790 example, the last test could be written:
29791
29792 @smallexample @c ada
29793 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
29794 @end smallexample
29795
29796 @noindent
29797 or simply
29798
29799 @smallexample @c ada
29800 pragma Assert (Temperature <= 999.0);
29801 @end smallexample
29802
29803 @noindent
29804 In both cases, if assertions are active and the temperature is excessive,
29805 the exception @code{Assert_Failure} will be raised, with the given string in
29806 the first case or a string indicating the location of the pragma in the second
29807 case used as the exception message.
29808
29809 You can turn assertions on and off by using the @code{Assertion_Policy}
29810 pragma.
29811 @cindex pragma @code{Assertion_Policy}
29812 This is an Ada 2005 pragma which is implemented in all modes by
29813 GNAT, but only in the latest versions of GNAT which include Ada 2005
29814 capability. Alternatively, you can use the @option{-gnata} switch
29815 @cindex @option{-gnata} switch
29816 to enable assertions from the command line (this is recognized by all versions
29817 of GNAT).
29818
29819 For the example above with the @code{Put_Line}, the GNAT-specific pragma
29820 @code{Debug} can be used:
29821 @cindex pragma @code{Debug}
29822
29823 @smallexample @c ada
29824 pragma Debug (Put_Line ("got to the first stage!"));
29825 @end smallexample
29826
29827 @noindent
29828 If debug pragmas are enabled, the argument, which must be of the form of
29829 a procedure call, is executed (in this case, @code{Put_Line} will be called).
29830 Only one call can be present, but of course a special debugging procedure
29831 containing any code you like can be included in the program and then
29832 called in a pragma @code{Debug} argument as needed.
29833
29834 One advantage of pragma @code{Debug} over the @code{if Debugging then}
29835 construct is that pragma @code{Debug} can appear in declarative contexts,
29836 such as at the very beginning of a procedure, before local declarations have
29837 been elaborated.
29838
29839 Debug pragmas are enabled using either the @option{-gnata} switch that also
29840 controls assertions, or with a separate Debug_Policy pragma.
29841 @cindex pragma @code{Debug_Policy}
29842 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
29843 in Ada 95 and Ada 83 programs as well), and is analogous to
29844 pragma @code{Assertion_Policy} to control assertions.
29845
29846 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
29847 and thus they can appear in @file{gnat.adc} if you are not using a
29848 project file, or in the file designated to contain configuration pragmas
29849 in a project file.
29850 They then apply to all subsequent compilations. In practice the use of
29851 the @option{-gnata} switch is often the most convenient method of controlling
29852 the status of these pragmas.
29853
29854 Note that a pragma is not a statement, so in contexts where a statement
29855 sequence is required, you can't just write a pragma on its own. You have
29856 to add a @code{null} statement.
29857
29858 @smallexample @c ada
29859 @group
29860 if @dots{} then
29861    @dots{} -- some statements
29862 else
29863    pragma Assert (Num_Cases < 10);
29864    null;
29865 end if;
29866 @end group
29867 @end smallexample
29868
29869
29870 @node Conditionalizing Declarations
29871 @section Conditionalizing Declarations
29872
29873 @noindent
29874 In some cases, it may be necessary to conditionalize declarations to meet
29875 different requirements. For example we might want a bit string whose length
29876 is set to meet some hardware message requirement.
29877
29878 In some cases, it may be possible to do this using declare blocks controlled
29879 by conditional constants:
29880
29881 @smallexample @c ada
29882 @group
29883 if Small_Machine then
29884    declare
29885       X : Bit_String (1 .. 10);
29886    begin
29887       @dots{}
29888    end;
29889 else
29890    declare
29891       X : Large_Bit_String (1 .. 1000);
29892    begin
29893       @dots{}
29894    end;
29895 end if;
29896 @end group
29897 @end smallexample
29898
29899 @noindent
29900 Note that in this approach, both declarations are analyzed by the
29901 compiler so this can only be used where both declarations are legal,
29902 even though one of them will not be used.
29903
29904 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
29905 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
29906 that are parameterized by these constants. For example
29907
29908 @smallexample @c ada
29909 @group
29910 for Rec use
29911   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
29912 end record;
29913 @end group
29914 @end smallexample
29915
29916 @noindent
29917 If @code{Bits_Per_Word} is set to 32, this generates either
29918
29919 @smallexample @c ada
29920 @group
29921 for Rec use
29922   Field1 at 0 range 0 .. 32;
29923 end record;
29924 @end group
29925 @end smallexample
29926
29927 @noindent
29928 for the big endian case, or
29929
29930 @smallexample @c ada
29931 @group
29932 for Rec use record
29933   Field1 at 0 range 10 .. 32;
29934 end record;
29935 @end group
29936 @end smallexample
29937
29938 @noindent
29939 for the little endian case. Since a powerful subset of Ada expression
29940 notation is usable for creating static constants, clever use of this
29941 feature can often solve quite difficult problems in conditionalizing
29942 compilation (note incidentally that in Ada 95, the little endian
29943 constant was introduced as @code{System.Default_Bit_Order}, so you do not
29944 need to define this one yourself).
29945
29946
29947 @node Use of Alternative Implementations
29948 @section Use of Alternative Implementations
29949
29950 @noindent
29951 In some cases, none of the approaches described above are adequate. This
29952 can occur for example if the set of declarations required is radically
29953 different for two different configurations.
29954
29955 In this situation, the official Ada way of dealing with conditionalizing
29956 such code is to write separate units for the different cases. As long as
29957 this does not result in excessive duplication of code, this can be done
29958 without creating maintenance problems. The approach is to share common
29959 code as far as possible, and then isolate the code and declarations
29960 that are different. Subunits are often a convenient method for breaking
29961 out a piece of a unit that is to be conditionalized, with separate files
29962 for different versions of the subunit for different targets, where the
29963 build script selects the right one to give to the compiler.
29964 @cindex Subunits (and conditional compilation)
29965
29966 As an example, consider a situation where a new feature in Ada 2005
29967 allows something to be done in a really nice way. But your code must be able
29968 to compile with an Ada 95 compiler. Conceptually you want to say:
29969
29970 @smallexample @c ada
29971 @group
29972 if Ada_2005 then
29973    @dots{} neat Ada 2005 code
29974 else
29975    @dots{} not quite as neat Ada 95 code
29976 end if;
29977 @end group
29978 @end smallexample
29979
29980 @noindent
29981 where @code{Ada_2005} is a Boolean constant.
29982
29983 But this won't work when @code{Ada_2005} is set to @code{False},
29984 since the @code{then} clause will be illegal for an Ada 95 compiler.
29985 (Recall that although such unreachable code would eventually be deleted
29986 by the compiler, it still needs to be legal.  If it uses features
29987 introduced in Ada 2005, it will be illegal in Ada 95.)
29988
29989 So instead we write
29990
29991 @smallexample @c ada
29992 procedure Insert is separate;
29993 @end smallexample
29994
29995 @noindent
29996 Then we have two files for the subunit @code{Insert}, with the two sets of
29997 code.
29998 If the package containing this is called @code{File_Queries}, then we might
29999 have two files
30000
30001 @itemize @bullet
30002 @item    @file{file_queries-insert-2005.adb}
30003 @item    @file{file_queries-insert-95.adb}
30004 @end itemize
30005
30006 @noindent
30007 and the build script renames the appropriate file to
30008
30009 @smallexample
30010 file_queries-insert.adb
30011 @end smallexample
30012
30013 @noindent
30014 and then carries out the compilation.
30015
30016 This can also be done with project files' naming schemes. For example:
30017
30018 @smallexample @c project
30019 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
30020 @end smallexample
30021
30022 @noindent
30023 Note also that with project files it is desirable to use a different extension
30024 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
30025 conflict may arise through another commonly used feature: to declare as part
30026 of the project a set of directories containing all the sources obeying the
30027 default naming scheme.
30028
30029 The use of alternative units is certainly feasible in all situations,
30030 and for example the Ada part of the GNAT run-time is conditionalized
30031 based on the target architecture using this approach. As a specific example,
30032 consider the implementation of the AST feature in VMS. There is one
30033 spec:
30034
30035 @smallexample
30036 s-asthan.ads
30037 @end smallexample
30038
30039 @noindent
30040 which is the same for all architectures, and three bodies:
30041
30042 @table @file
30043 @item    s-asthan.adb
30044 used for all non-VMS operating systems
30045 @item    s-asthan-vms-alpha.adb
30046 used for VMS on the Alpha
30047 @item    s-asthan-vms-ia64.adb
30048 used for VMS on the ia64
30049 @end table
30050
30051 @noindent
30052 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
30053 this operating system feature is not available, and the two remaining
30054 versions interface with the corresponding versions of VMS to provide
30055 VMS-compatible AST handling. The GNAT build script knows the architecture
30056 and operating system, and automatically selects the right version,
30057 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
30058
30059 Another style for arranging alternative implementations is through Ada's
30060 access-to-subprogram facility.
30061 In case some functionality is to be conditionally included,
30062 you can declare an access-to-procedure variable @code{Ref} that is initialized
30063 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
30064 when appropriate.
30065 In some library package, set @code{Ref} to @code{Proc'Access} for some
30066 procedure @code{Proc} that performs the relevant processing.
30067 The initialization only occurs if the library package is included in the
30068 program.
30069 The same idea can also be implemented using tagged types and dispatching
30070 calls.
30071
30072
30073 @node Preprocessing
30074 @section Preprocessing
30075 @cindex Preprocessing
30076
30077 @noindent
30078 Although it is quite possible to conditionalize code without the use of
30079 C-style preprocessing, as described earlier in this section, it is
30080 nevertheless convenient in some cases to use the C approach. Moreover,
30081 older Ada compilers have often provided some preprocessing capability,
30082 so legacy code may depend on this approach, even though it is not
30083 standard.
30084
30085 To accommodate such use, GNAT provides a preprocessor (modeled to a large
30086 extent on the various preprocessors that have been used
30087 with legacy code on other compilers, to enable easier transition).
30088
30089 The preprocessor may be used in two separate modes. It can be used quite
30090 separately from the compiler, to generate a separate output source file
30091 that is then fed to the compiler as a separate step. This is the
30092 @code{gnatprep} utility, whose use is fully described in
30093 @ref{Preprocessing Using gnatprep}.
30094 @cindex @code{gnatprep}
30095
30096 The preprocessing language allows such constructs as
30097
30098 @smallexample
30099 @group
30100 #if DEBUG or PRIORITY > 4 then
30101    bunch of declarations
30102 #else
30103    completely different bunch of declarations
30104 #end if;
30105 @end group
30106 @end smallexample
30107
30108 @noindent
30109 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
30110 defined either on the command line or in a separate file.
30111
30112 The other way of running the preprocessor is even closer to the C style and
30113 often more convenient. In this approach the preprocessing is integrated into
30114 the compilation process. The compiler is fed the preprocessor input which
30115 includes @code{#if} lines etc, and then the compiler carries out the
30116 preprocessing internally and processes the resulting output.
30117 For more details on this approach, see @ref{Integrated Preprocessing}.
30118
30119
30120 @c *******************************
30121 @node Inline Assembler
30122 @appendix Inline Assembler
30123 @c *******************************
30124
30125 @noindent
30126 If you need to write low-level software that interacts directly
30127 with the hardware, Ada provides two ways to incorporate assembly
30128 language code into your program.  First, you can import and invoke
30129 external routines written in assembly language, an Ada feature fully
30130 supported by GNAT@.  However, for small sections of code it may be simpler
30131 or more efficient to include assembly language statements directly
30132 in your Ada source program, using the facilities of the implementation-defined
30133 package @code{System.Machine_Code}, which incorporates the gcc
30134 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
30135 including the following:
30136
30137 @itemize @bullet
30138 @item No need to use non-Ada tools
30139 @item Consistent interface over different targets
30140 @item Automatic usage of the proper calling conventions
30141 @item Access to Ada constants and variables
30142 @item Definition of intrinsic routines
30143 @item Possibility of inlining a subprogram comprising assembler code
30144 @item Code optimizer can take Inline Assembler code into account
30145 @end itemize
30146
30147 This chapter presents a series of examples to show you how to use
30148 the Inline Assembler.  Although it focuses on the Intel x86,
30149 the general approach applies also to other processors.
30150 It is assumed that you are familiar with Ada
30151 and with assembly language programming.
30152
30153 @menu
30154 * Basic Assembler Syntax::
30155 * A Simple Example of Inline Assembler::
30156 * Output Variables in Inline Assembler::
30157 * Input Variables in Inline Assembler::
30158 * Inlining Inline Assembler Code::
30159 * Other Asm Functionality::
30160 @end menu
30161
30162 @c ---------------------------------------------------------------------------
30163 @node Basic Assembler Syntax
30164 @section Basic Assembler Syntax
30165
30166 @noindent
30167 The assembler used by GNAT and gcc is based not on the Intel assembly
30168 language, but rather on a language that descends from the AT&T Unix
30169 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
30170 The following table summarizes the main features of @emph{as} syntax
30171 and points out the differences from the Intel conventions.
30172 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
30173 pre-processor) documentation for further information.
30174
30175 @table @asis
30176 @item Register names
30177 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
30178 @*
30179 Intel: No extra punctuation; for example @code{eax}
30180
30181 @item Immediate operand
30182 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
30183 @*
30184 Intel: No extra punctuation; for example @code{4}
30185
30186 @item Address
30187 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
30188 @*
30189 Intel: No extra punctuation; for example @code{loc}
30190
30191 @item Memory contents
30192 gcc / @emph{as}: No extra punctuation; for example @code{loc}
30193 @*
30194 Intel: Square brackets; for example @code{[loc]}
30195
30196 @item Register contents
30197 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
30198 @*
30199 Intel: Square brackets; for example @code{[eax]}
30200
30201 @item Hexadecimal numbers
30202 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
30203 @*
30204 Intel: Trailing ``h''; for example @code{A0h}
30205
30206 @item Operand size
30207 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
30208 a 16-bit word
30209 @*
30210 Intel: Implicit, deduced by assembler; for example @code{mov}
30211
30212 @item Instruction repetition
30213 gcc / @emph{as}: Split into two lines; for example
30214 @*
30215 @code{rep}
30216 @*
30217 @code{stosl}
30218 @*
30219 Intel: Keep on one line; for example @code{rep stosl}
30220
30221 @item Order of operands
30222 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
30223 @*
30224 Intel: Destination first; for example @code{mov eax, 4}
30225 @end table
30226
30227 @c ---------------------------------------------------------------------------
30228 @node A Simple Example of Inline Assembler
30229 @section A Simple Example of Inline Assembler
30230
30231 @noindent
30232 The following example will generate a single assembly language statement,
30233 @code{nop}, which does nothing.  Despite its lack of run-time effect,
30234 the example will be useful in illustrating the basics of
30235 the Inline Assembler facility.
30236
30237 @smallexample @c ada
30238 @group
30239 with System.Machine_Code; use System.Machine_Code;
30240 procedure Nothing is
30241 begin
30242    Asm ("nop");
30243 end Nothing;
30244 @end group
30245 @end smallexample
30246
30247 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
30248 here it takes one parameter, a @emph{template string} that must be a static
30249 expression and that will form the generated instruction.
30250 @code{Asm} may be regarded as a compile-time procedure that parses
30251 the template string and additional parameters (none here),
30252 from which it generates a sequence of assembly language instructions.
30253
30254 The examples in this chapter will illustrate several of the forms
30255 for invoking @code{Asm}; a complete specification of the syntax
30256 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
30257 Manual}.
30258
30259 Under the standard GNAT conventions, the @code{Nothing} procedure
30260 should be in a file named @file{nothing.adb}.
30261 You can build the executable in the usual way:
30262 @smallexample
30263 gnatmake nothing
30264 @end smallexample
30265 However, the interesting aspect of this example is not its run-time behavior
30266 but rather the generated assembly code.
30267 To see this output, invoke the compiler as follows:
30268 @smallexample
30269    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
30270 @end smallexample
30271 where the options are:
30272
30273 @table @code
30274 @item -c
30275 compile only (no bind or link)
30276 @item -S
30277 generate assembler listing
30278 @item -fomit-frame-pointer
30279 do not set up separate stack frames
30280 @item -gnatp
30281 do not add runtime checks
30282 @end table
30283
30284 This gives a human-readable assembler version of the code. The resulting
30285 file will have the same name as the Ada source file, but with a @code{.s}
30286 extension. In our example, the file @file{nothing.s} has the following
30287 contents:
30288
30289 @smallexample
30290 @group
30291 .file "nothing.adb"
30292 gcc2_compiled.:
30293 ___gnu_compiled_ada:
30294 .text
30295    .align 4
30296 .globl __ada_nothing
30297 __ada_nothing:
30298 #APP
30299    nop
30300 #NO_APP
30301    jmp L1
30302    .align 2,0x90
30303 L1:
30304    ret
30305 @end group
30306 @end smallexample
30307
30308 The assembly code you included is clearly indicated by
30309 the compiler, between the @code{#APP} and @code{#NO_APP}
30310 delimiters. The character before the 'APP' and 'NOAPP'
30311 can differ on different targets. For example, GNU/Linux uses '#APP' while
30312 on NT you will see '/APP'.
30313
30314 If you make a mistake in your assembler code (such as using the
30315 wrong size modifier, or using a wrong operand for the instruction) GNAT
30316 will report this error in a temporary file, which will be deleted when
30317 the compilation is finished.  Generating an assembler file will help
30318 in such cases, since you can assemble this file separately using the
30319 @emph{as} assembler that comes with gcc.
30320
30321 Assembling the file using the command
30322
30323 @smallexample
30324 as @file{nothing.s}
30325 @end smallexample
30326 @noindent
30327 will give you error messages whose lines correspond to the assembler
30328 input file, so you can easily find and correct any mistakes you made.
30329 If there are no errors, @emph{as} will generate an object file
30330 @file{nothing.out}.
30331
30332 @c ---------------------------------------------------------------------------
30333 @node Output Variables in Inline Assembler
30334 @section Output Variables in Inline Assembler
30335
30336 @noindent
30337 The examples in this section, showing how to access the processor flags,
30338 illustrate how to specify the destination operands for assembly language
30339 statements.
30340
30341 @smallexample @c ada
30342 @group
30343 with Interfaces; use Interfaces;
30344 with Ada.Text_IO; use Ada.Text_IO;
30345 with System.Machine_Code; use System.Machine_Code;
30346 procedure Get_Flags is
30347    Flags : Unsigned_32;
30348    use ASCII;
30349 begin
30350    Asm ("pushfl"          & LF & HT & -- push flags on stack
30351         "popl %%eax"      & LF & HT & -- load eax with flags
30352         "movl %%eax, %0",             -- store flags in variable
30353         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30354    Put_Line ("Flags register:" & Flags'Img);
30355 end Get_Flags;
30356 @end group
30357 @end smallexample
30358
30359 In order to have a nicely aligned assembly listing, we have separated
30360 multiple assembler statements in the Asm template string with linefeed
30361 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
30362 The resulting section of the assembly output file is:
30363
30364 @smallexample
30365 @group
30366 #APP
30367    pushfl
30368    popl %eax
30369    movl %eax, -40(%ebp)
30370 #NO_APP
30371 @end group
30372 @end smallexample
30373
30374 It would have been legal to write the Asm invocation as:
30375
30376 @smallexample
30377 Asm ("pushfl popl %%eax movl %%eax, %0")
30378 @end smallexample
30379
30380 but in the generated assembler file, this would come out as:
30381
30382 @smallexample
30383 #APP
30384    pushfl popl %eax movl %eax, -40(%ebp)
30385 #NO_APP
30386 @end smallexample
30387
30388 which is not so convenient for the human reader.
30389
30390 We use Ada comments
30391 at the end of each line to explain what the assembler instructions
30392 actually do.  This is a useful convention.
30393
30394 When writing Inline Assembler instructions, you need to precede each register
30395 and variable name with a percent sign.  Since the assembler already requires
30396 a percent sign at the beginning of a register name, you need two consecutive
30397 percent signs for such names in the Asm template string, thus @code{%%eax}.
30398 In the generated assembly code, one of the percent signs will be stripped off.
30399
30400 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
30401 variables: operands you later define using @code{Input} or @code{Output}
30402 parameters to @code{Asm}.
30403 An output variable is illustrated in
30404 the third statement in the Asm template string:
30405 @smallexample
30406 movl %%eax, %0
30407 @end smallexample
30408 The intent is to store the contents of the eax register in a variable that can
30409 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
30410 necessarily work, since the compiler might optimize by using a register
30411 to hold Flags, and the expansion of the @code{movl} instruction would not be
30412 aware of this optimization.  The solution is not to store the result directly
30413 but rather to advise the compiler to choose the correct operand form;
30414 that is the purpose of the @code{%0} output variable.
30415
30416 Information about the output variable is supplied in the @code{Outputs}
30417 parameter to @code{Asm}:
30418 @smallexample
30419 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30420 @end smallexample
30421
30422 The output is defined by the @code{Asm_Output} attribute of the target type;
30423 the general format is
30424 @smallexample
30425 Type'Asm_Output (constraint_string, variable_name)
30426 @end smallexample
30427
30428 The constraint string directs the compiler how
30429 to store/access the associated variable.  In the example
30430 @smallexample
30431 Unsigned_32'Asm_Output ("=m", Flags);
30432 @end smallexample
30433 the @code{"m"} (memory) constraint tells the compiler that the variable
30434 @code{Flags} should be stored in a memory variable, thus preventing
30435 the optimizer from keeping it in a register.  In contrast,
30436 @smallexample
30437 Unsigned_32'Asm_Output ("=r", Flags);
30438 @end smallexample
30439 uses the @code{"r"} (register) constraint, telling the compiler to
30440 store the variable in a register.
30441
30442 If the constraint is preceded by the equal character (@strong{=}), it tells
30443 the compiler that the variable will be used to store data into it.
30444
30445 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
30446 allowing the optimizer to choose whatever it deems best.
30447
30448 There are a fairly large number of constraints, but the ones that are
30449 most useful (for the Intel x86 processor) are the following:
30450
30451 @table @code
30452 @item =
30453 output constraint
30454 @item g
30455 global (i.e.@: can be stored anywhere)
30456 @item m
30457 in memory
30458 @item I
30459 a constant
30460 @item a
30461 use eax
30462 @item b
30463 use ebx
30464 @item c
30465 use ecx
30466 @item d
30467 use edx
30468 @item S
30469 use esi
30470 @item D
30471 use edi
30472 @item r
30473 use one of eax, ebx, ecx or edx
30474 @item q
30475 use one of eax, ebx, ecx, edx, esi or edi
30476 @end table
30477
30478 The full set of constraints is described in the gcc and @emph{as}
30479 documentation; note that it is possible to combine certain constraints
30480 in one constraint string.
30481
30482 You specify the association of an output variable with an assembler operand
30483 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
30484 integer.  Thus in
30485 @smallexample @c ada
30486 @group
30487 Asm ("pushfl"          & LF & HT & -- push flags on stack
30488      "popl %%eax"      & LF & HT & -- load eax with flags
30489      "movl %%eax, %0",             -- store flags in variable
30490      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30491 @end group
30492 @end smallexample
30493 @noindent
30494 @code{%0} will be replaced in the expanded code by the appropriate operand,
30495 whatever
30496 the compiler decided for the @code{Flags} variable.
30497
30498 In general, you may have any number of output variables:
30499 @itemize @bullet
30500 @item
30501 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
30502 @item
30503 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
30504 of @code{Asm_Output} attributes
30505 @end itemize
30506
30507 For example:
30508 @smallexample @c ada
30509 @group
30510 Asm ("movl %%eax, %0" & LF & HT &
30511      "movl %%ebx, %1" & LF & HT &
30512      "movl %%ecx, %2",
30513      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
30514                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
30515                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
30516 @end group
30517 @end smallexample
30518 @noindent
30519 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
30520 in the Ada program.
30521
30522 As a variation on the @code{Get_Flags} example, we can use the constraints
30523 string to direct the compiler to store the eax register into the @code{Flags}
30524 variable, instead of including the store instruction explicitly in the
30525 @code{Asm} template string:
30526
30527 @smallexample @c ada
30528 @group
30529 with Interfaces; use Interfaces;
30530 with Ada.Text_IO; use Ada.Text_IO;
30531 with System.Machine_Code; use System.Machine_Code;
30532 procedure Get_Flags_2 is
30533    Flags : Unsigned_32;
30534    use ASCII;
30535 begin
30536    Asm ("pushfl"      & LF & HT & -- push flags on stack
30537         "popl %%eax",             -- save flags in eax
30538         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
30539    Put_Line ("Flags register:" & Flags'Img);
30540 end Get_Flags_2;
30541 @end group
30542 @end smallexample
30543
30544 @noindent
30545 The @code{"a"} constraint tells the compiler that the @code{Flags}
30546 variable will come from the eax register. Here is the resulting code:
30547
30548 @smallexample
30549 @group
30550 #APP
30551    pushfl
30552    popl %eax
30553 #NO_APP
30554    movl %eax,-40(%ebp)
30555 @end group
30556 @end smallexample
30557
30558 @noindent
30559 The compiler generated the store of eax into Flags after
30560 expanding the assembler code.
30561
30562 Actually, there was no need to pop the flags into the eax register;
30563 more simply, we could just pop the flags directly into the program variable:
30564
30565 @smallexample @c ada
30566 @group
30567 with Interfaces; use Interfaces;
30568 with Ada.Text_IO; use Ada.Text_IO;
30569 with System.Machine_Code; use System.Machine_Code;
30570 procedure Get_Flags_3 is
30571    Flags : Unsigned_32;
30572    use ASCII;
30573 begin
30574    Asm ("pushfl"  & LF & HT & -- push flags on stack
30575         "pop %0",             -- save flags in Flags
30576         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30577    Put_Line ("Flags register:" & Flags'Img);
30578 end Get_Flags_3;
30579 @end group
30580 @end smallexample
30581
30582 @c ---------------------------------------------------------------------------
30583 @node Input Variables in Inline Assembler
30584 @section Input Variables in Inline Assembler
30585
30586 @noindent
30587 The example in this section illustrates how to specify the source operands
30588 for assembly language statements.
30589 The program simply increments its input value by 1:
30590
30591 @smallexample @c ada
30592 @group
30593 with Interfaces; use Interfaces;
30594 with Ada.Text_IO; use Ada.Text_IO;
30595 with System.Machine_Code; use System.Machine_Code;
30596 procedure Increment is
30597
30598    function Incr (Value : Unsigned_32) return Unsigned_32 is
30599       Result : Unsigned_32;
30600    begin
30601       Asm ("incl %0",
30602            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30603            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30604       return Result;
30605    end Incr;
30606
30607    Value : Unsigned_32;
30608
30609 begin
30610    Value := 5;
30611    Put_Line ("Value before is" & Value'Img);
30612    Value := Incr (Value);
30613    Put_Line ("Value after is" & Value'Img);
30614 end Increment;
30615 @end group
30616 @end smallexample
30617
30618 The @code{Outputs} parameter to @code{Asm} specifies
30619 that the result will be in the eax register and that it is to be stored
30620 in the @code{Result} variable.
30621
30622 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
30623 but with an @code{Asm_Input} attribute.
30624 The @code{"="} constraint, indicating an output value, is not present.
30625
30626 You can have multiple input variables, in the same way that you can have more
30627 than one output variable.
30628
30629 The parameter count (%0, %1) etc, now starts at the first input
30630 statement, and continues with the output statements.
30631 When both parameters use the same variable, the
30632 compiler will treat them as the same %n operand, which is the case here.
30633
30634 Just as the @code{Outputs} parameter causes the register to be stored into the
30635 target variable after execution of the assembler statements, so does the
30636 @code{Inputs} parameter cause its variable to be loaded into the register
30637 before execution of the assembler statements.
30638
30639 Thus the effect of the @code{Asm} invocation is:
30640 @enumerate
30641 @item load the 32-bit value of @code{Value} into eax
30642 @item execute the @code{incl %eax} instruction
30643 @item store the contents of eax into the @code{Result} variable
30644 @end enumerate
30645
30646 The resulting assembler file (with @option{-O2} optimization) contains:
30647 @smallexample
30648 @group
30649 _increment__incr.1:
30650    subl $4,%esp
30651    movl 8(%esp),%eax
30652 #APP
30653    incl %eax
30654 #NO_APP
30655    movl %eax,%edx
30656    movl %ecx,(%esp)
30657    addl $4,%esp
30658    ret
30659 @end group
30660 @end smallexample
30661
30662 @c ---------------------------------------------------------------------------
30663 @node Inlining Inline Assembler Code
30664 @section Inlining Inline Assembler Code
30665
30666 @noindent
30667 For a short subprogram such as the @code{Incr} function in the previous
30668 section, the overhead of the call and return (creating / deleting the stack
30669 frame) can be significant, compared to the amount of code in the subprogram
30670 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
30671 which directs the compiler to expand invocations of the subprogram at the
30672 point(s) of call, instead of setting up a stack frame for out-of-line calls.
30673 Here is the resulting program:
30674
30675 @smallexample @c ada
30676 @group
30677 with Interfaces; use Interfaces;
30678 with Ada.Text_IO; use Ada.Text_IO;
30679 with System.Machine_Code; use System.Machine_Code;
30680 procedure Increment_2 is
30681
30682    function Incr (Value : Unsigned_32) return Unsigned_32 is
30683       Result : Unsigned_32;
30684    begin
30685       Asm ("incl %0",
30686            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30687            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30688       return Result;
30689    end Incr;
30690    pragma Inline (Increment);
30691
30692    Value : Unsigned_32;
30693
30694 begin
30695    Value := 5;
30696    Put_Line ("Value before is" & Value'Img);
30697    Value := Increment (Value);
30698    Put_Line ("Value after is" & Value'Img);
30699 end Increment_2;
30700 @end group
30701 @end smallexample
30702
30703 Compile the program with both optimization (@option{-O2}) and inlining
30704 (@option{-gnatn}) enabled.
30705
30706 The @code{Incr} function is still compiled as usual, but at the
30707 point in @code{Increment} where our function used to be called:
30708
30709 @smallexample
30710 @group
30711 pushl %edi
30712 call _increment__incr.1
30713 @end group
30714 @end smallexample
30715
30716 @noindent
30717 the code for the function body directly appears:
30718
30719 @smallexample
30720 @group
30721 movl %esi,%eax
30722 #APP
30723    incl %eax
30724 #NO_APP
30725    movl %eax,%edx
30726 @end group
30727 @end smallexample
30728
30729 @noindent
30730 thus saving the overhead of stack frame setup and an out-of-line call.
30731
30732 @c ---------------------------------------------------------------------------
30733 @node Other Asm Functionality
30734 @section Other @code{Asm} Functionality
30735
30736 @noindent
30737 This section describes two important parameters to the @code{Asm}
30738 procedure: @code{Clobber}, which identifies register usage;
30739 and @code{Volatile}, which inhibits unwanted optimizations.
30740
30741 @menu
30742 * The Clobber Parameter::
30743 * The Volatile Parameter::
30744 @end menu
30745
30746 @c ---------------------------------------------------------------------------
30747 @node The Clobber Parameter
30748 @subsection The @code{Clobber} Parameter
30749
30750 @noindent
30751 One of the dangers of intermixing assembly language and a compiled language
30752 such as Ada is that the compiler needs to be aware of which registers are
30753 being used by the assembly code.  In some cases, such as the earlier examples,
30754 the constraint string is sufficient to indicate register usage (e.g.,
30755 @code{"a"} for
30756 the eax register).  But more generally, the compiler needs an explicit
30757 identification of the registers that are used by the Inline Assembly
30758 statements.
30759
30760 Using a register that the compiler doesn't know about
30761 could be a side effect of an instruction (like @code{mull}
30762 storing its result in both eax and edx).
30763 It can also arise from explicit register usage in your
30764 assembly code; for example:
30765 @smallexample
30766 @group
30767 Asm ("movl %0, %%ebx" & LF & HT &
30768      "movl %%ebx, %1",
30769      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30770      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
30771 @end group
30772 @end smallexample
30773 @noindent
30774 where the compiler (since it does not analyze the @code{Asm} template string)
30775 does not know you are using the ebx register.
30776
30777 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
30778 to identify the registers that will be used by your assembly code:
30779
30780 @smallexample
30781 @group
30782 Asm ("movl %0, %%ebx" & LF & HT &
30783      "movl %%ebx, %1",
30784      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30785      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30786      Clobber => "ebx");
30787 @end group
30788 @end smallexample
30789
30790 The Clobber parameter is a static string expression specifying the
30791 register(s) you are using.  Note that register names are @emph{not} prefixed
30792 by a percent sign. Also, if more than one register is used then their names
30793 are separated by commas; e.g., @code{"eax, ebx"}
30794
30795 The @code{Clobber} parameter has several additional uses:
30796 @enumerate
30797 @item Use ``register'' name @code{cc} to indicate that flags might have changed
30798 @item Use ``register'' name @code{memory} if you changed a memory location
30799 @end enumerate
30800
30801 @c ---------------------------------------------------------------------------
30802 @node The Volatile Parameter
30803 @subsection The @code{Volatile} Parameter
30804 @cindex Volatile parameter
30805
30806 @noindent
30807 Compiler optimizations in the presence of Inline Assembler may sometimes have
30808 unwanted effects.  For example, when an @code{Asm} invocation with an input
30809 variable is inside a loop, the compiler might move the loading of the input
30810 variable outside the loop, regarding it as a one-time initialization.
30811
30812 If this effect is not desired, you can disable such optimizations by setting
30813 the @code{Volatile} parameter to @code{True}; for example:
30814
30815 @smallexample @c ada
30816 @group
30817 Asm ("movl %0, %%ebx" & LF & HT &
30818      "movl %%ebx, %1",
30819      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
30820      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
30821      Clobber  => "ebx",
30822      Volatile => True);
30823 @end group
30824 @end smallexample
30825
30826 By default, @code{Volatile} is set to @code{False} unless there is no
30827 @code{Outputs} parameter.
30828
30829 Although setting @code{Volatile} to @code{True} prevents unwanted
30830 optimizations, it will also disable other optimizations that might be
30831 important for efficiency. In general, you should set @code{Volatile}
30832 to @code{True} only if the compiler's optimizations have created
30833 problems.
30834 @c END OF INLINE ASSEMBLER CHAPTER
30835 @c ===============================
30836
30837 @c ***********************************
30838 @c * Compatibility and Porting Guide *
30839 @c ***********************************
30840 @node Compatibility and Porting Guide
30841 @appendix Compatibility and Porting Guide
30842
30843 @noindent
30844 This chapter describes the compatibility issues that may arise between
30845 GNAT and other Ada compilation systems (including those for Ada 83),
30846 and shows how GNAT can expedite porting
30847 applications developed in other Ada environments.
30848
30849 @menu
30850 * Compatibility with Ada 83::
30851 * Compatibility between Ada 95 and Ada 2005::
30852 * Implementation-dependent characteristics::
30853 * Compatibility with Other Ada Systems::
30854 * Representation Clauses::
30855 @ifclear vms
30856 @c Brief section is only in non-VMS version
30857 @c Full chapter is in VMS version
30858 * Compatibility with HP Ada 83::
30859 @end ifclear
30860 @ifset vms
30861 * Transitioning to 64-Bit GNAT for OpenVMS::
30862 @end ifset
30863 @end menu
30864
30865 @node Compatibility with Ada 83
30866 @section Compatibility with Ada 83
30867 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
30868
30869 @noindent
30870 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
30871 particular, the design intention was that the difficulties associated
30872 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
30873 that occur when moving from one Ada 83 system to another.
30874
30875 However, there are a number of points at which there are minor
30876 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
30877 full details of these issues,
30878 and should be consulted for a complete treatment.
30879 In practice the
30880 following subsections treat the most likely issues to be encountered.
30881
30882 @menu
30883 * Legal Ada 83 programs that are illegal in Ada 95::
30884 * More deterministic semantics::
30885 * Changed semantics::
30886 * Other language compatibility issues::
30887 @end menu
30888
30889 @node Legal Ada 83 programs that are illegal in Ada 95
30890 @subsection Legal Ada 83 programs that are illegal in Ada 95
30891
30892 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
30893 Ada 95 and thus also in Ada 2005:
30894
30895 @table @emph
30896 @item Character literals
30897 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
30898 @code{Wide_Character} as a new predefined character type, some uses of
30899 character literals that were legal in Ada 83 are illegal in Ada 95.
30900 For example:
30901 @smallexample @c ada
30902    for Char in 'A' .. 'Z' loop @dots{} end loop;
30903 @end smallexample
30904
30905 @noindent
30906 The problem is that @code{'A'} and @code{'Z'} could be from either
30907 @code{Character} or @code{Wide_Character}.  The simplest correction
30908 is to make the type explicit; e.g.:
30909 @smallexample @c ada
30910    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
30911 @end smallexample
30912
30913 @item New reserved words
30914 The identifiers @code{abstract}, @code{aliased}, @code{protected},
30915 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
30916 Existing Ada 83 code using any of these identifiers must be edited to
30917 use some alternative name.
30918
30919 @item Freezing rules
30920 The rules in Ada 95 are slightly different with regard to the point at
30921 which entities are frozen, and representation pragmas and clauses are
30922 not permitted past the freeze point.  This shows up most typically in
30923 the form of an error message complaining that a representation item
30924 appears too late, and the appropriate corrective action is to move
30925 the item nearer to the declaration of the entity to which it refers.
30926
30927 A particular case is that representation pragmas
30928 @ifset vms
30929 (including the
30930 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
30931 @end ifset
30932 cannot be applied to a subprogram body.  If necessary, a separate subprogram
30933 declaration must be introduced to which the pragma can be applied.
30934
30935 @item Optional bodies for library packages
30936 In Ada 83, a package that did not require a package body was nevertheless
30937 allowed to have one.  This lead to certain surprises in compiling large
30938 systems (situations in which the body could be unexpectedly ignored by the
30939 binder).  In Ada 95, if a package does not require a body then it is not
30940 permitted to have a body.  To fix this problem, simply remove a redundant
30941 body if it is empty, or, if it is non-empty, introduce a dummy declaration
30942 into the spec that makes the body required.  One approach is to add a private
30943 part to the package declaration (if necessary), and define a parameterless
30944 procedure called @code{Requires_Body}, which must then be given a dummy
30945 procedure body in the package body, which then becomes required.
30946 Another approach (assuming that this does not introduce elaboration
30947 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
30948 since one effect of this pragma is to require the presence of a package body.
30949
30950 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
30951 In Ada 95, the exception @code{Numeric_Error} is a renaming of
30952 @code{Constraint_Error}.
30953 This means that it is illegal to have separate exception handlers for
30954 the two exceptions.  The fix is simply to remove the handler for the
30955 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
30956 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
30957
30958 @item Indefinite subtypes in generics
30959 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
30960 as the actual for a generic formal private type, but then the instantiation
30961 would be illegal if there were any instances of declarations of variables
30962 of this type in the generic body.  In Ada 95, to avoid this clear violation
30963 of the methodological principle known as the ``contract model'',
30964 the generic declaration explicitly indicates whether
30965 or not such instantiations are permitted.  If a generic formal parameter
30966 has explicit unknown discriminants, indicated by using @code{(<>)} after the
30967 type name, then it can be instantiated with indefinite types, but no
30968 stand-alone variables can be declared of this type.  Any attempt to declare
30969 such a variable will result in an illegality at the time the generic is
30970 declared.  If the @code{(<>)} notation is not used, then it is illegal
30971 to instantiate the generic with an indefinite type.
30972 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
30973 It will show up as a compile time error, and
30974 the fix is usually simply to add the @code{(<>)} to the generic declaration.
30975 @end table
30976
30977 @node More deterministic semantics
30978 @subsection More deterministic semantics
30979
30980 @table @emph
30981 @item Conversions
30982 Conversions from real types to integer types round away from 0.  In Ada 83
30983 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
30984 implementation freedom was intended to support unbiased rounding in
30985 statistical applications, but in practice it interfered with portability.
30986 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
30987 is required.  Numeric code may be affected by this change in semantics.
30988 Note, though, that this issue is no worse than already existed in Ada 83
30989 when porting code from one vendor to another.
30990
30991 @item Tasking
30992 The Real-Time Annex introduces a set of policies that define the behavior of
30993 features that were implementation dependent in Ada 83, such as the order in
30994 which open select branches are executed.
30995 @end table
30996
30997 @node Changed semantics
30998 @subsection Changed semantics
30999
31000 @noindent
31001 The worst kind of incompatibility is one where a program that is legal in
31002 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
31003 possible in Ada 83.  Fortunately this is extremely rare, but the one
31004 situation that you should be alert to is the change in the predefined type
31005 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
31006
31007 @table @emph
31008 @item Range of type @code{Character}
31009 The range of @code{Standard.Character} is now the full 256 characters
31010 of Latin-1, whereas in most Ada 83 implementations it was restricted
31011 to 128 characters. Although some of the effects of
31012 this change will be manifest in compile-time rejection of legal
31013 Ada 83 programs it is possible for a working Ada 83 program to have
31014 a different effect in Ada 95, one that was not permitted in Ada 83.
31015 As an example, the expression
31016 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
31017 delivers @code{255} as its value.
31018 In general, you should look at the logic of any
31019 character-processing Ada 83 program and see whether it needs to be adapted
31020 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
31021 character handling package that may be relevant if code needs to be adapted
31022 to account for the additional Latin-1 elements.
31023 The desirable fix is to
31024 modify the program to accommodate the full character set, but in some cases
31025 it may be convenient to define a subtype or derived type of Character that
31026 covers only the restricted range.
31027 @cindex Latin-1
31028 @end table
31029
31030 @node Other language compatibility issues
31031 @subsection Other language compatibility issues
31032
31033 @table @emph
31034 @item @option{-gnat83} switch
31035 All implementations of GNAT provide a switch that causes GNAT to operate
31036 in Ada 83 mode.  In this mode, some but not all compatibility problems
31037 of the type described above are handled automatically.  For example, the
31038 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
31039 as identifiers as in Ada 83.
31040 However,
31041 in practice, it is usually advisable to make the necessary modifications
31042 to the program to remove the need for using this switch.
31043 See @ref{Compiling Different Versions of Ada}.
31044
31045 @item Support for removed Ada 83 pragmas and attributes
31046 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
31047 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
31048 compilers are allowed, but not required, to implement these missing
31049 elements.  In contrast with some other compilers, GNAT implements all
31050 such pragmas and attributes, eliminating this compatibility concern.  These
31051 include @code{pragma Interface} and the floating point type attributes
31052 (@code{Emax}, @code{Mantissa}, etc.), among other items.
31053 @end table
31054
31055
31056 @node Compatibility between Ada 95 and Ada 2005
31057 @section Compatibility between Ada 95 and Ada 2005
31058 @cindex Compatibility between Ada 95 and Ada 2005
31059
31060 @noindent
31061 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
31062 a number of incompatibilities. Several are enumerated below;
31063 for a complete description please see the
31064 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
31065 @cite{Rationale for Ada 2005}.
31066
31067 @table @emph
31068 @item New reserved words.
31069 The words @code{interface}, @code{overriding} and @code{synchronized} are
31070 reserved in Ada 2005.
31071 A pre-Ada 2005 program that uses any of these as an identifier will be
31072 illegal.
31073
31074 @item New declarations in predefined packages.
31075 A number of packages in the predefined environment contain new declarations:
31076 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
31077 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
31078 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
31079 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
31080 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
31081 If an Ada 95 program does a @code{with} and @code{use} of any of these
31082 packages, the new declarations may cause name clashes.
31083
31084 @item Access parameters.
31085 A nondispatching subprogram with an access parameter cannot be renamed
31086 as a dispatching operation.  This was permitted in Ada 95.
31087
31088 @item Access types, discriminants, and constraints.
31089 Rule changes in this area have led to some incompatibilities; for example,
31090 constrained subtypes of some access types are not permitted in Ada 2005.
31091
31092 @item Aggregates for limited types.
31093 The allowance of aggregates for limited types in Ada 2005 raises the
31094 possibility of ambiguities in legal Ada 95 programs, since additional types
31095 now need to be considered in expression resolution.
31096
31097 @item Fixed-point multiplication and division.
31098 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
31099 were legal in Ada 95 and invoked the predefined versions of these operations,
31100 are now ambiguous.
31101 The ambiguity may be resolved either by applying a type conversion to the
31102 expression, or by explicitly invoking the operation from package
31103 @code{Standard}.
31104
31105 @item Return-by-reference types.
31106 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
31107 can declare a function returning a value from an anonymous access type.
31108 @end table
31109
31110
31111 @node Implementation-dependent characteristics
31112 @section Implementation-dependent characteristics
31113 @noindent
31114 Although the Ada language defines the semantics of each construct as
31115 precisely as practical, in some situations (for example for reasons of
31116 efficiency, or where the effect is heavily dependent on the host or target
31117 platform) the implementation is allowed some freedom.  In porting Ada 83
31118 code to GNAT, you need to be aware of whether / how the existing code
31119 exercised such implementation dependencies.  Such characteristics fall into
31120 several categories, and GNAT offers specific support in assisting the
31121 transition from certain Ada 83 compilers.
31122
31123 @menu
31124 * Implementation-defined pragmas::
31125 * Implementation-defined attributes::
31126 * Libraries::
31127 * Elaboration order::
31128 * Target-specific aspects::
31129 @end menu
31130
31131 @node Implementation-defined pragmas
31132 @subsection Implementation-defined pragmas
31133
31134 @noindent
31135 Ada compilers are allowed to supplement the language-defined pragmas, and
31136 these are a potential source of non-portability.  All GNAT-defined pragmas
31137 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
31138 Reference Manual}, and these include several that are specifically
31139 intended to correspond to other vendors' Ada 83 pragmas.
31140 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
31141 For compatibility with HP Ada 83, GNAT supplies the pragmas
31142 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
31143 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
31144 and @code{Volatile}.
31145 Other relevant pragmas include @code{External} and @code{Link_With}.
31146 Some vendor-specific
31147 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
31148 recognized, thus
31149 avoiding compiler rejection of units that contain such pragmas; they are not
31150 relevant in a GNAT context and hence are not otherwise implemented.
31151
31152 @node Implementation-defined attributes
31153 @subsection Implementation-defined attributes
31154
31155 Analogous to pragmas, the set of attributes may be extended by an
31156 implementation.  All GNAT-defined attributes are described in
31157 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
31158 Manual}, and these include several that are specifically intended
31159 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
31160 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
31161 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
31162 @code{Type_Class}.
31163
31164 @node Libraries
31165 @subsection Libraries
31166 @noindent
31167 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
31168 code uses vendor-specific libraries then there are several ways to manage
31169 this in Ada 95 or Ada 2005:
31170 @enumerate
31171 @item
31172 If the source code for the libraries (specs and bodies) are
31173 available, then the libraries can be migrated in the same way as the
31174 application.
31175 @item
31176 If the source code for the specs but not the bodies are
31177 available, then you can reimplement the bodies.
31178 @item
31179 Some features introduced by Ada 95 obviate the need for library support.  For
31180 example most Ada 83 vendors supplied a package for unsigned integers.  The
31181 Ada 95 modular type feature is the preferred way to handle this need, so
31182 instead of migrating or reimplementing the unsigned integer package it may
31183 be preferable to retrofit the application using modular types.
31184 @end enumerate
31185
31186 @node Elaboration order
31187 @subsection Elaboration order
31188 @noindent
31189 The implementation can choose any elaboration order consistent with the unit
31190 dependency relationship.  This freedom means that some orders can result in
31191 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
31192 to invoke a subprogram its body has been elaborated, or to instantiate a
31193 generic before the generic body has been elaborated.  By default GNAT
31194 attempts to choose a safe order (one that will not encounter access before
31195 elaboration problems) by implicitly inserting @code{Elaborate} or
31196 @code{Elaborate_All} pragmas where
31197 needed.  However, this can lead to the creation of elaboration circularities
31198 and a resulting rejection of the program by gnatbind.  This issue is
31199 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
31200 In brief, there are several
31201 ways to deal with this situation:
31202
31203 @itemize @bullet
31204 @item
31205 Modify the program to eliminate the circularities, e.g.@: by moving
31206 elaboration-time code into explicitly-invoked procedures
31207 @item
31208 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
31209 @code{Elaborate} pragmas, and then inhibit the generation of implicit
31210 @code{Elaborate_All}
31211 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
31212 (by selectively suppressing elaboration checks via pragma
31213 @code{Suppress(Elaboration_Check)} when it is safe to do so).
31214 @end itemize
31215
31216 @node Target-specific aspects
31217 @subsection Target-specific aspects
31218 @noindent
31219 Low-level applications need to deal with machine addresses, data
31220 representations, interfacing with assembler code, and similar issues.  If
31221 such an Ada 83 application is being ported to different target hardware (for
31222 example where the byte endianness has changed) then you will need to
31223 carefully examine the program logic; the porting effort will heavily depend
31224 on the robustness of the original design.  Moreover, Ada 95 (and thus
31225 Ada 2005) are sometimes
31226 incompatible with typical Ada 83 compiler practices regarding implicit
31227 packing, the meaning of the Size attribute, and the size of access values.
31228 GNAT's approach to these issues is described in @ref{Representation Clauses}.
31229
31230 @node Compatibility with Other Ada Systems
31231 @section Compatibility with Other Ada Systems
31232
31233 @noindent
31234 If programs avoid the use of implementation dependent and
31235 implementation defined features, as documented in the @cite{Ada
31236 Reference Manual}, there should be a high degree of portability between
31237 GNAT and other Ada systems.  The following are specific items which
31238 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
31239 compilers, but do not affect porting code to GNAT@.
31240 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
31241 the following issues may or may not arise for Ada 2005 programs
31242 when other compilers appear.)
31243
31244 @table @emph
31245 @item Ada 83 Pragmas and Attributes
31246 Ada 95 compilers are allowed, but not required, to implement the missing
31247 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
31248 GNAT implements all such pragmas and attributes, eliminating this as
31249 a compatibility concern, but some other Ada 95 compilers reject these
31250 pragmas and attributes.
31251
31252 @item Specialized Needs Annexes
31253 GNAT implements the full set of special needs annexes.  At the
31254 current time, it is the only Ada 95 compiler to do so.  This means that
31255 programs making use of these features may not be portable to other Ada
31256 95 compilation systems.
31257
31258 @item Representation Clauses
31259 Some other Ada 95 compilers implement only the minimal set of
31260 representation clauses required by the Ada 95 reference manual.  GNAT goes
31261 far beyond this minimal set, as described in the next section.
31262 @end table
31263
31264 @node Representation Clauses
31265 @section Representation Clauses
31266
31267 @noindent
31268 The Ada 83 reference manual was quite vague in describing both the minimal
31269 required implementation of representation clauses, and also their precise
31270 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
31271 minimal set of capabilities required is still quite limited.
31272
31273 GNAT implements the full required set of capabilities in
31274 Ada 95 and Ada 2005, but also goes much further, and in particular
31275 an effort has been made to be compatible with existing Ada 83 usage to the
31276 greatest extent possible.
31277
31278 A few cases exist in which Ada 83 compiler behavior is incompatible with
31279 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
31280 intentional or accidental dependence on specific implementation dependent
31281 characteristics of these Ada 83 compilers.  The following is a list of
31282 the cases most likely to arise in existing Ada 83 code.
31283
31284 @table @emph
31285 @item Implicit Packing
31286 Some Ada 83 compilers allowed a Size specification to cause implicit
31287 packing of an array or record.  This could cause expensive implicit
31288 conversions for change of representation in the presence of derived
31289 types, and the Ada design intends to avoid this possibility.
31290 Subsequent AI's were issued to make it clear that such implicit
31291 change of representation in response to a Size clause is inadvisable,
31292 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
31293 Reference Manuals as implementation advice that is followed by GNAT@.
31294 The problem will show up as an error
31295 message rejecting the size clause.  The fix is simply to provide
31296 the explicit pragma @code{Pack}, or for more fine tuned control, provide
31297 a Component_Size clause.
31298
31299 @item Meaning of Size Attribute
31300 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
31301 the minimal number of bits required to hold values of the type.  For example,
31302 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
31303 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
31304 some 32 in this situation.  This problem will usually show up as a compile
31305 time error, but not always.  It is a good idea to check all uses of the
31306 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
31307 Object_Size can provide a useful way of duplicating the behavior of
31308 some Ada 83 compiler systems.
31309
31310 @item Size of Access Types
31311 A common assumption in Ada 83 code is that an access type is in fact a pointer,
31312 and that therefore it will be the same size as a System.Address value.  This
31313 assumption is true for GNAT in most cases with one exception.  For the case of
31314 a pointer to an unconstrained array type (where the bounds may vary from one
31315 value of the access type to another), the default is to use a ``fat pointer'',
31316 which is represented as two separate pointers, one to the bounds, and one to
31317 the array.  This representation has a number of advantages, including improved
31318 efficiency.  However, it may cause some difficulties in porting existing Ada 83
31319 code which makes the assumption that, for example, pointers fit in 32 bits on
31320 a machine with 32-bit addressing.
31321
31322 To get around this problem, GNAT also permits the use of ``thin pointers'' for
31323 access types in this case (where the designated type is an unconstrained array
31324 type).  These thin pointers are indeed the same size as a System.Address value.
31325 To specify a thin pointer, use a size clause for the type, for example:
31326
31327 @smallexample @c ada
31328 type X is access all String;
31329 for X'Size use Standard'Address_Size;
31330 @end smallexample
31331
31332 @noindent
31333 which will cause the type X to be represented using a single pointer.
31334 When using this representation, the bounds are right behind the array.
31335 This representation is slightly less efficient, and does not allow quite
31336 such flexibility in the use of foreign pointers or in using the
31337 Unrestricted_Access attribute to create pointers to non-aliased objects.
31338 But for any standard portable use of the access type it will work in
31339 a functionally correct manner and allow porting of existing code.
31340 Note that another way of forcing a thin pointer representation
31341 is to use a component size clause for the element size in an array,
31342 or a record representation clause for an access field in a record.
31343 @end table
31344
31345 @ifclear vms
31346 @c This brief section is only in the non-VMS version
31347 @c The complete chapter on HP Ada is in the VMS version
31348 @node Compatibility with HP Ada 83
31349 @section Compatibility with HP Ada 83
31350
31351 @noindent
31352 The VMS version of GNAT fully implements all the pragmas and attributes
31353 provided by HP Ada 83, as well as providing the standard HP Ada 83
31354 libraries, including Starlet.  In addition, data layouts and parameter
31355 passing conventions are highly compatible.  This means that porting
31356 existing HP Ada 83 code to GNAT in VMS systems should be easier than
31357 most other porting efforts.  The following are some of the most
31358 significant differences between GNAT and HP Ada 83.
31359
31360 @table @emph
31361 @item Default floating-point representation
31362 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
31363 it is VMS format.  GNAT does implement the necessary pragmas
31364 (Long_Float, Float_Representation) for changing this default.
31365
31366 @item System
31367 The package System in GNAT exactly corresponds to the definition in the
31368 Ada 95 reference manual, which means that it excludes many of the
31369 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
31370 that contains the additional definitions, and a special pragma,
31371 Extend_System allows this package to be treated transparently as an
31372 extension of package System.
31373
31374 @item To_Address
31375 The definitions provided by Aux_DEC are exactly compatible with those
31376 in the HP Ada 83 version of System, with one exception.
31377 HP Ada provides the following declarations:
31378
31379 @smallexample @c ada
31380 TO_ADDRESS (INTEGER)
31381 TO_ADDRESS (UNSIGNED_LONGWORD)
31382 TO_ADDRESS (@i{universal_integer})
31383 @end smallexample
31384
31385 @noindent
31386 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
31387 an extension to Ada 83 not strictly compatible with the reference manual.
31388 In GNAT, we are constrained to be exactly compatible with the standard,
31389 and this means we cannot provide this capability.  In HP Ada 83, the
31390 point of this definition is to deal with a call like:
31391
31392 @smallexample @c ada
31393 TO_ADDRESS (16#12777#);
31394 @end smallexample
31395
31396 @noindent
31397 Normally, according to the Ada 83 standard, one would expect this to be
31398 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
31399 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
31400 definition using @i{universal_integer} takes precedence.
31401
31402 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
31403 is not possible to be 100% compatible.  Since there are many programs using
31404 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
31405 to change the name of the function in the UNSIGNED_LONGWORD case, so the
31406 declarations provided in the GNAT version of AUX_Dec are:
31407
31408 @smallexample @c ada
31409 function To_Address (X : Integer) return Address;
31410 pragma Pure_Function (To_Address);
31411
31412 function To_Address_Long (X : Unsigned_Longword)
31413  return Address;
31414 pragma Pure_Function (To_Address_Long);
31415 @end smallexample
31416
31417 @noindent
31418 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
31419 change the name to TO_ADDRESS_LONG@.
31420
31421 @item Task_Id values
31422 The Task_Id values assigned will be different in the two systems, and GNAT
31423 does not provide a specified value for the Task_Id of the environment task,
31424 which in GNAT is treated like any other declared task.
31425 @end table
31426
31427 @noindent
31428 For full details on these and other less significant compatibility issues,
31429 see appendix E of the HP publication entitled @cite{HP Ada, Technical
31430 Overview and Comparison on HP Platforms}.
31431
31432 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
31433 attributes are recognized, although only a subset of them can sensibly
31434 be implemented.  The description of pragmas in @ref{Implementation
31435 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
31436 indicates whether or not they are applicable to non-VMS systems.
31437 @end ifclear
31438
31439 @ifset vms
31440 @node Transitioning to 64-Bit GNAT for OpenVMS
31441 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
31442
31443 @noindent
31444 This section is meant to assist users of pre-2006 @value{EDITION}
31445 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
31446 the version of the GNAT technology supplied in 2006 and later for
31447 OpenVMS on both Alpha and I64.
31448
31449 @menu
31450 * Introduction to transitioning::
31451 * Migration of 32 bit code::
31452 * Taking advantage of 64 bit addressing::
31453 * Technical details::
31454 @end menu
31455
31456 @node Introduction to transitioning
31457 @subsection Introduction
31458
31459 @noindent
31460 64-bit @value{EDITION} for Open VMS has been designed to meet
31461 three main goals:
31462
31463 @enumerate
31464 @item
31465 Providing a full conforming implementation of Ada 95 and Ada 2005
31466
31467 @item
31468 Allowing maximum backward compatibility, thus easing migration of existing
31469 Ada source code
31470
31471 @item
31472 Supplying a path for exploiting the full 64-bit address range
31473 @end enumerate
31474
31475 @noindent
31476 Ada's strong typing semantics has made it
31477 impractical to have different 32-bit and 64-bit modes. As soon as
31478 one object could possibly be outside the 32-bit address space, this
31479 would make it necessary for the @code{System.Address} type to be 64 bits.
31480 In particular, this would cause inconsistencies if 32-bit code is
31481 called from 64-bit code that raises an exception.
31482
31483 This issue has been resolved by always using 64-bit addressing
31484 at the system level, but allowing for automatic conversions between
31485 32-bit and 64-bit addresses where required. Thus users who
31486 do not currently require 64-bit addressing capabilities, can
31487 recompile their code with only minimal changes (and indeed
31488 if the code is written in portable Ada, with no assumptions about
31489 the size of the @code{Address} type, then no changes at all are necessary).
31490 At the same time,
31491 this approach provides a simple, gradual upgrade path to future
31492 use of larger memories than available for 32-bit systems.
31493 Also, newly written applications or libraries will by default
31494 be fully compatible with future systems exploiting 64-bit
31495 addressing capabilities.
31496
31497 @ref{Migration of 32 bit code}, will focus on porting applications
31498 that do not require more than 2 GB of
31499 addressable memory. This code will be referred to as
31500 @emph{32-bit code}.
31501 For applications intending to exploit the full 64-bit address space,
31502 @ref{Taking advantage of 64 bit addressing},
31503 will consider further changes that may be required.
31504 Such code will be referred to below as @emph{64-bit code}.
31505
31506 @node Migration of 32 bit code
31507 @subsection Migration of 32-bit code
31508
31509 @menu
31510 * Address types::
31511 * Access types::
31512 * Unchecked conversions::
31513 * Predefined constants::
31514 * Interfacing with C::
31515 * Experience with source compatibility::
31516 @end menu
31517
31518 @node Address types
31519 @subsubsection Address types
31520
31521 @noindent
31522 To solve the problem of mixing 64-bit and 32-bit addressing,
31523 while maintaining maximum backward compatibility, the following
31524 approach has been taken:
31525
31526 @itemize @bullet
31527 @item
31528 @code{System.Address} always has a size of 64 bits
31529
31530 @item
31531 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
31532 @end itemize
31533
31534 @noindent
31535 Since @code{System.Short_Address} is a subtype of @code{System.Address},
31536 a @code{Short_Address}
31537 may be used where an @code{Address} is required, and vice versa, without
31538 needing explicit type conversions.
31539 By virtue of the Open VMS parameter passing conventions,
31540 even imported
31541 and exported subprograms that have 32-bit address parameters are
31542 compatible with those that have 64-bit address parameters.
31543 (See @ref{Making code 64 bit clean} for details.)
31544
31545 The areas that may need attention are those where record types have
31546 been defined that contain components of the type @code{System.Address}, and
31547 where objects of this type are passed to code expecting a record layout with
31548 32-bit addresses.
31549
31550 Different compilers on different platforms cannot be
31551 expected to represent the same type in the same way,
31552 since alignment constraints
31553 and other system-dependent properties affect the compiler's decision.
31554 For that reason, Ada code
31555 generally uses representation clauses to specify the expected
31556 layout where required.
31557
31558 If such a representation clause uses 32 bits for a component having
31559 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
31560 will detect that error and produce a specific diagnostic message.
31561 The developer should then determine whether the representation
31562 should be 64 bits or not and make either of two changes:
31563 change the size to 64 bits and leave the type as @code{System.Address}, or
31564 leave the size as 32 bits and change the type to @code{System.Short_Address}.
31565 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
31566 required in any code setting or accessing the field; the compiler will
31567 automatically perform any needed conversions between address
31568 formats.
31569
31570 @node Access types
31571 @subsubsection Access types
31572
31573 @noindent
31574 By default, objects designated by access values are always
31575 allocated in the 32-bit
31576 address space. Thus legacy code will never contain
31577 any objects that are not addressable with 32-bit addresses, and
31578 the compiler will never raise exceptions as result of mixing
31579 32-bit and 64-bit addresses.
31580
31581 However, the access values themselves are represented in 64 bits, for optimum
31582 performance and future compatibility with 64-bit code. As was
31583 the case with @code{System.Address}, the compiler will give an error message
31584 if an object or record component has a representation clause that
31585 requires the access value to fit in 32 bits. In such a situation,
31586 an explicit size clause for the access type, specifying 32 bits,
31587 will have the desired effect.
31588
31589 General access types (declared with @code{access all}) can never be
31590 32 bits, as values of such types must be able to refer to any object
31591 of the  designated type,
31592 including objects residing outside the 32-bit address range.
31593 Existing Ada 83 code will not contain such type definitions,
31594 however, since general access types were introduced in Ada 95.
31595
31596 @node Unchecked conversions
31597 @subsubsection Unchecked conversions
31598
31599 @noindent
31600 In the case of an @code{Unchecked_Conversion} where the source type is a
31601 64-bit access type or the type @code{System.Address}, and the target
31602 type is a 32-bit type, the compiler will generate a warning.
31603 Even though the generated code will still perform the required
31604 conversions, it is highly recommended in these cases to use
31605 respectively a 32-bit access type or @code{System.Short_Address}
31606 as the source type.
31607
31608 @node Predefined constants
31609 @subsubsection Predefined constants
31610
31611 @noindent
31612 The following table shows the correspondence between pre-2006 versions of
31613 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
31614 (``New''):
31615
31616 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
31617 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
31618 @item   @code{System.Word_Size}          @tab 32      @tab 64
31619 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
31620 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
31621 @item   @code{System.Address_Size}       @tab 32      @tab 64
31622 @end multitable
31623
31624 @noindent
31625 If you need to refer to the specific
31626 memory size of a 32-bit implementation, instead of the
31627 actual memory size, use @code{System.Short_Memory_Size}
31628 rather than @code{System.Memory_Size}.
31629 Similarly, references to @code{System.Address_Size} may need
31630 to be replaced by @code{System.Short_Address'Size}.
31631 The program @command{gnatfind} may be useful for locating
31632 references to the above constants, so that you can verify that they
31633 are still correct.
31634
31635 @node Interfacing with C
31636 @subsubsection Interfacing with C
31637
31638 @noindent
31639 In order to minimize the impact of the transition to 64-bit addresses on
31640 legacy programs, some fundamental types in the @code{Interfaces.C}
31641 package hierarchy continue to be represented in 32 bits.
31642 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
31643 This eases integration with the default HP C layout choices, for example
31644 as found in the system routines in @code{DECC$SHR.EXE}.
31645 Because of this implementation choice, the type fully compatible with
31646 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
31647 Depending on the context the compiler will issue a
31648 warning or an error when type @code{Address} is used, alerting the user to a
31649 potential problem. Otherwise 32-bit programs that use
31650 @code{Interfaces.C} should normally not require code modifications
31651
31652 The other issue arising with C interfacing concerns pragma @code{Convention}.
31653 For VMS 64-bit systems, there is an issue of the appropriate default size
31654 of C convention pointers in the absence of an explicit size clause. The HP
31655 C compiler can choose either 32 or 64 bits depending on compiler options.
31656 GNAT chooses 32-bits rather than 64-bits in the default case where no size
31657 clause is given. This proves a better choice for porting 32-bit legacy
31658 applications. In order to have a 64-bit representation, it is necessary to
31659 specify a size representation clause. For example:
31660
31661 @smallexample @c ada
31662 type int_star is access Interfaces.C.int;
31663 pragma Convention(C, int_star);
31664 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
31665 @end smallexample
31666
31667 @node Experience with source compatibility
31668 @subsubsection Experience with source compatibility
31669
31670 @noindent
31671 The Security Server and STARLET on I64 provide an interesting ``test case''
31672 for source compatibility issues, since it is in such system code
31673 where assumptions about @code{Address} size might be expected to occur.
31674 Indeed, there were a small number of occasions in the Security Server
31675 file @file{jibdef.ads}
31676 where a representation clause for a record type specified
31677 32 bits for a component of type @code{Address}.
31678 All of these errors were detected by the compiler.
31679 The repair was obvious and immediate; to simply replace @code{Address} by
31680 @code{Short_Address}.
31681
31682 In the case of STARLET, there were several record types that should
31683 have had representation clauses but did not.  In these record types
31684 there was an implicit assumption that an @code{Address} value occupied
31685 32 bits.
31686 These compiled without error, but their usage resulted in run-time error
31687 returns from STARLET system calls.
31688 Future GNAT technology enhancements may include a tool that detects and flags
31689 these sorts of potential source code porting problems.
31690
31691 @c ****************************************
31692 @node Taking advantage of 64 bit addressing
31693 @subsection Taking advantage of 64-bit addressing
31694
31695 @menu
31696 * Making code 64 bit clean::
31697 * Allocating memory from the 64 bit storage pool::
31698 * Restrictions on use of 64 bit objects::
31699 * Using 64 bit storage pools by default::
31700 * General access types::
31701 * STARLET and other predefined libraries::
31702 @end menu
31703
31704 @node Making code 64 bit clean
31705 @subsubsection Making code 64-bit clean
31706
31707 @noindent
31708 In order to prevent problems that may occur when (parts of) a
31709 system start using memory outside the 32-bit address range,
31710 we recommend some additional guidelines:
31711
31712 @itemize @bullet
31713 @item
31714 For imported subprograms that take parameters of the
31715 type @code{System.Address}, ensure that these subprograms can
31716 indeed handle 64-bit addresses. If not, or when in doubt,
31717 change the subprogram declaration to specify
31718 @code{System.Short_Address} instead.
31719
31720 @item
31721 Resolve all warnings related to size mismatches in
31722 unchecked conversions. Failing to do so causes
31723 erroneous execution if the source object is outside
31724 the 32-bit address space.
31725
31726 @item
31727 (optional) Explicitly use the 32-bit storage pool
31728 for access types used in a 32-bit context, or use
31729 generic access types where possible
31730 (@pxref{Restrictions on use of 64 bit objects}).
31731 @end itemize
31732
31733 @noindent
31734 If these rules are followed, the compiler will automatically insert
31735 any necessary checks to ensure that no addresses or access values
31736 passed to 32-bit code ever refer to objects outside the 32-bit
31737 address range.
31738 Any attempt to do this will raise @code{Constraint_Error}.
31739
31740 @node Allocating memory from the 64 bit storage pool
31741 @subsubsection Allocating memory from the 64-bit storage pool
31742
31743 @noindent
31744 For any access type @code{T} that potentially requires memory allocations
31745 beyond the 32-bit address space,
31746 use the following representation clause:
31747
31748 @smallexample @c ada
31749    for T'Storage_Pool use System.Pool_64;
31750 @end smallexample
31751
31752 @node Restrictions on use of 64 bit objects
31753 @subsubsection Restrictions on use of 64-bit objects
31754
31755 @noindent
31756 Taking the address of an object allocated from a 64-bit storage pool,
31757 and then passing this address to a subprogram expecting
31758 @code{System.Short_Address},
31759 or assigning it to a variable of type @code{Short_Address}, will cause
31760 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
31761 (@pxref{Making code 64 bit clean}), or checks are suppressed,
31762 no exception is raised and execution
31763 will become erroneous.
31764
31765 @node Using 64 bit storage pools by default
31766 @subsubsection Using 64-bit storage pools by default
31767
31768 @noindent
31769 In some cases it may be desirable to have the compiler allocate
31770 from 64-bit storage pools by default. This may be the case for
31771 libraries that are 64-bit clean, but may be used in both 32-bit
31772 and 64-bit contexts. For these cases the following configuration
31773 pragma may be specified:
31774
31775 @smallexample @c ada
31776   pragma Pool_64_Default;
31777 @end smallexample
31778
31779 @noindent
31780 Any code compiled in the context of this pragma will by default
31781 use the @code{System.Pool_64} storage pool. This default may be overridden
31782 for a specific access type @code{T} by the representation clause:
31783
31784 @smallexample @c ada
31785    for T'Storage_Pool use System.Pool_32;
31786 @end smallexample
31787
31788 @noindent
31789 Any object whose address may be passed to a subprogram with a
31790 @code{Short_Address} argument, or assigned to a variable of type
31791 @code{Short_Address}, needs to be allocated from this pool.
31792
31793 @node General access types
31794 @subsubsection General access types
31795
31796 @noindent
31797 Objects designated by access values from a
31798 general access type (declared with @code{access all}) are never allocated
31799 from a 64-bit storage pool. Code that uses general access types will
31800 accept objects allocated in either 32-bit or 64-bit address spaces,
31801 but never allocate objects outside the 32-bit address space.
31802 Using general access types ensures maximum compatibility with both
31803 32-bit and 64-bit code.
31804
31805 @node STARLET and other predefined libraries
31806 @subsubsection STARLET and other predefined libraries
31807
31808 @noindent
31809 All code that comes as part of GNAT is 64-bit clean, but the
31810 restrictions given in @ref{Restrictions on use of 64 bit objects},
31811 still apply. Look at the package
31812 specs to see in which contexts objects allocated
31813 in 64-bit address space are acceptable.
31814
31815 @node Technical details
31816 @subsection Technical details
31817
31818 @noindent
31819 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
31820 Ada standard with respect to the type of @code{System.Address}. Previous
31821 versions of GNAT Pro have defined this type as private and implemented it as a
31822 modular type.
31823
31824 In order to allow defining @code{System.Short_Address} as a proper subtype,
31825 and to match the implicit sign extension in parameter passing,
31826 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
31827 visible (i.e., non-private) integer type.
31828 Standard operations on the type, such as the binary operators ``+'', ``-'',
31829 etc., that take @code{Address} operands and return an @code{Address} result,
31830 have been hidden by declaring these
31831 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
31832 ambiguities that would otherwise result from overloading.
31833 (Note that, although @code{Address} is a visible integer type,
31834 good programming practice dictates against exploiting the type's
31835 integer properties such as literals, since this will compromise
31836 code portability.)
31837
31838 Defining @code{Address} as a visible integer type helps achieve
31839 maximum compatibility for existing Ada code,
31840 without sacrificing the capabilities of the 64-bit architecture.
31841 @end ifset
31842
31843 @c ************************************************
31844 @ifset unw
31845 @node Microsoft Windows Topics
31846 @appendix Microsoft Windows Topics
31847 @cindex Windows NT
31848 @cindex Windows 95
31849 @cindex Windows 98
31850
31851 @noindent
31852 This chapter describes topics that are specific to the Microsoft Windows
31853 platforms (NT, 2000, and XP Professional).
31854
31855 @menu
31856 * Using GNAT on Windows::
31857 * Using a network installation of GNAT::
31858 * CONSOLE and WINDOWS subsystems::
31859 * Temporary Files::
31860 * Mixed-Language Programming on Windows::
31861 * Windows Calling Conventions::
31862 * Introduction to Dynamic Link Libraries (DLLs)::
31863 * Using DLLs with GNAT::
31864 * Building DLLs with GNAT::
31865 * Building DLLs with GNAT Project files::
31866 * Building DLLs with gnatdll::
31867 * GNAT and Windows Resources::
31868 * Debugging a DLL::
31869 * Setting Stack Size from gnatlink::
31870 * Setting Heap Size from gnatlink::
31871 @end menu
31872
31873 @node Using GNAT on Windows
31874 @section Using GNAT on Windows
31875
31876 @noindent
31877 One of the strengths of the GNAT technology is that its tool set
31878 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
31879 @code{gdb} debugger, etc.) is used in the same way regardless of the
31880 platform.
31881
31882 On Windows this tool set is complemented by a number of Microsoft-specific
31883 tools that have been provided to facilitate interoperability with Windows
31884 when this is required. With these tools:
31885
31886 @itemize @bullet
31887
31888 @item
31889 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
31890 subsystems.
31891
31892 @item
31893 You can use any Dynamically Linked Library (DLL) in your Ada code (both
31894 relocatable and non-relocatable DLLs are supported).
31895
31896 @item
31897 You can build Ada DLLs for use in other applications. These applications
31898 can be written in a language other than Ada (e.g., C, C++, etc). Again both
31899 relocatable and non-relocatable Ada DLLs are supported.
31900
31901 @item
31902 You can include Windows resources in your Ada application.
31903
31904 @item
31905 You can use or create COM/DCOM objects.
31906 @end itemize
31907
31908 @noindent
31909 Immediately below are listed all known general GNAT-for-Windows restrictions.
31910 Other restrictions about specific features like Windows Resources and DLLs
31911 are listed in separate sections below.
31912
31913 @itemize @bullet
31914
31915 @item
31916 It is not possible to use @code{GetLastError} and @code{SetLastError}
31917 when tasking, protected records, or exceptions are used. In these
31918 cases, in order to implement Ada semantics, the GNAT run-time system
31919 calls certain Win32 routines that set the last error variable to 0 upon
31920 success. It should be possible to use @code{GetLastError} and
31921 @code{SetLastError} when tasking, protected record, and exception
31922 features are not used, but it is not guaranteed to work.
31923
31924 @item
31925 It is not possible to link against Microsoft libraries except for
31926 import libraries. The library must be built to be compatible with
31927 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
31928 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
31929 not be compatible with the GNAT runtime. Even if the library is
31930 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
31931
31932 @item
31933 When the compilation environment is located on FAT32 drives, users may
31934 experience recompilations of the source files that have not changed if
31935 Daylight Saving Time (DST) state has changed since the last time files
31936 were compiled. NTFS drives do not have this problem.
31937
31938 @item
31939 No components of the GNAT toolset use any entries in the Windows
31940 registry. The only entries that can be created are file associations and
31941 PATH settings, provided the user has chosen to create them at installation
31942 time, as well as some minimal book-keeping information needed to correctly
31943 uninstall or integrate different GNAT products.
31944 @end itemize
31945
31946 @node Using a network installation of GNAT
31947 @section Using a network installation of GNAT
31948
31949 @noindent
31950 Make sure the system on which GNAT is installed is accessible from the
31951 current machine, i.e., the install location is shared over the network.
31952 Shared resources are accessed on Windows by means of UNC paths, which
31953 have the format @code{\\server\sharename\path}
31954
31955 In order to use such a network installation, simply add the UNC path of the
31956 @file{bin} directory of your GNAT installation in front of your PATH. For
31957 example, if GNAT is installed in @file{\GNAT} directory of a share location
31958 called @file{c-drive} on a machine @file{LOKI}, the following command will
31959 make it available:
31960
31961 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
31962
31963 Be aware that every compilation using the network installation results in the
31964 transfer of large amounts of data across the network and will likely cause
31965 serious performance penalty.
31966
31967 @node CONSOLE and WINDOWS subsystems
31968 @section CONSOLE and WINDOWS subsystems
31969 @cindex CONSOLE Subsystem
31970 @cindex WINDOWS Subsystem
31971 @cindex -mwindows
31972
31973 @noindent
31974 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
31975 (which is the default subsystem) will always create a console when
31976 launching the application. This is not something desirable when the
31977 application has a Windows GUI. To get rid of this console the
31978 application must be using the @code{WINDOWS} subsystem. To do so
31979 the @option{-mwindows} linker option must be specified.
31980
31981 @smallexample
31982 $ gnatmake winprog -largs -mwindows
31983 @end smallexample
31984
31985 @node Temporary Files
31986 @section Temporary Files
31987 @cindex Temporary files
31988
31989 @noindent
31990 It is possible to control where temporary files gets created by setting
31991 the @env{TMP} environment variable. The file will be created:
31992
31993 @itemize
31994 @item Under the directory pointed to by the @env{TMP} environment variable if
31995 this directory exists.
31996
31997 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
31998 set (or not pointing to a directory) and if this directory exists.
31999
32000 @item Under the current working directory otherwise.
32001 @end itemize
32002
32003 @noindent
32004 This allows you to determine exactly where the temporary
32005 file will be created. This is particularly useful in networked
32006 environments where you may not have write access to some
32007 directories.
32008
32009 @node Mixed-Language Programming on Windows
32010 @section Mixed-Language Programming on Windows
32011
32012 @noindent
32013 Developing pure Ada applications on Windows is no different than on
32014 other GNAT-supported platforms. However, when developing or porting an
32015 application that contains a mix of Ada and C/C++, the choice of your
32016 Windows C/C++ development environment conditions your overall
32017 interoperability strategy.
32018
32019 If you use @command{gcc} to compile the non-Ada part of your application,
32020 there are no Windows-specific restrictions that affect the overall
32021 interoperability with your Ada code. If you plan to use
32022 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
32023 the following limitations:
32024
32025 @itemize @bullet
32026 @item
32027 You cannot link your Ada code with an object or library generated with
32028 Microsoft tools if these use the @code{.tls} section (Thread Local
32029 Storage section) since the GNAT linker does not yet support this section.
32030
32031 @item
32032 You cannot link your Ada code with an object or library generated with
32033 Microsoft tools if these use I/O routines other than those provided in
32034 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
32035 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
32036 libraries can cause a conflict with @code{msvcrt.dll} services. For
32037 instance Visual C++ I/O stream routines conflict with those in
32038 @code{msvcrt.dll}.
32039 @end itemize
32040
32041 @noindent
32042 If you do want to use the Microsoft tools for your non-Ada code and hit one
32043 of the above limitations, you have two choices:
32044
32045 @enumerate
32046 @item
32047 Encapsulate your non-Ada code in a DLL to be linked with your Ada
32048 application. In this case, use the Microsoft or whatever environment to
32049 build the DLL and use GNAT to build your executable
32050 (@pxref{Using DLLs with GNAT}).
32051
32052 @item
32053 Or you can encapsulate your Ada code in a DLL to be linked with the
32054 other part of your application. In this case, use GNAT to build the DLL
32055 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
32056 environment to build your executable.
32057 @end enumerate
32058
32059 @node Windows Calling Conventions
32060 @section Windows Calling Conventions
32061 @findex Stdcall
32062 @findex APIENTRY
32063
32064 @menu
32065 * C Calling Convention::
32066 * Stdcall Calling Convention::
32067 * Win32 Calling Convention::
32068 * DLL Calling Convention::
32069 @end menu
32070
32071 @noindent
32072 When a subprogram @code{F} (caller) calls a subprogram @code{G}
32073 (callee), there are several ways to push @code{G}'s parameters on the
32074 stack and there are several possible scenarios to clean up the stack
32075 upon @code{G}'s return. A calling convention is an agreed upon software
32076 protocol whereby the responsibilities between the caller (@code{F}) and
32077 the callee (@code{G}) are clearly defined. Several calling conventions
32078 are available for Windows:
32079
32080 @itemize @bullet
32081 @item
32082 @code{C} (Microsoft defined)
32083
32084 @item
32085 @code{Stdcall} (Microsoft defined)
32086
32087 @item
32088 @code{Win32} (GNAT specific)
32089
32090 @item
32091 @code{DLL} (GNAT specific)
32092 @end itemize
32093
32094 @node C Calling Convention
32095 @subsection @code{C} Calling Convention
32096
32097 @noindent
32098 This is the default calling convention used when interfacing to C/C++
32099 routines compiled with either @command{gcc} or Microsoft Visual C++.
32100
32101 In the @code{C} calling convention subprogram parameters are pushed on the
32102 stack by the caller from right to left. The caller itself is in charge of
32103 cleaning up the stack after the call. In addition, the name of a routine
32104 with @code{C} calling convention is mangled by adding a leading underscore.
32105
32106 The name to use on the Ada side when importing (or exporting) a routine
32107 with @code{C} calling convention is the name of the routine. For
32108 instance the C function:
32109
32110 @smallexample
32111 int get_val (long);
32112 @end smallexample
32113
32114 @noindent
32115 should be imported from Ada as follows:
32116
32117 @smallexample @c ada
32118 @group
32119 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32120 pragma Import (C, Get_Val, External_Name => "get_val");
32121 @end group
32122 @end smallexample
32123
32124 @noindent
32125 Note that in this particular case the @code{External_Name} parameter could
32126 have been omitted since, when missing, this parameter is taken to be the
32127 name of the Ada entity in lower case. When the @code{Link_Name} parameter
32128 is missing, as in the above example, this parameter is set to be the
32129 @code{External_Name} with a leading underscore.
32130
32131 When importing a variable defined in C, you should always use the @code{C}
32132 calling convention unless the object containing the variable is part of a
32133 DLL (in which case you should use the @code{Stdcall} calling
32134 convention, @pxref{Stdcall Calling Convention}).
32135
32136 @node Stdcall Calling Convention
32137 @subsection @code{Stdcall} Calling Convention
32138
32139 @noindent
32140 This convention, which was the calling convention used for Pascal
32141 programs, is used by Microsoft for all the routines in the Win32 API for
32142 efficiency reasons. It must be used to import any routine for which this
32143 convention was specified.
32144
32145 In the @code{Stdcall} calling convention subprogram parameters are pushed
32146 on the stack by the caller from right to left. The callee (and not the
32147 caller) is in charge of cleaning the stack on routine exit. In addition,
32148 the name of a routine with @code{Stdcall} calling convention is mangled by
32149 adding a leading underscore (as for the @code{C} calling convention) and a
32150 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
32151 bytes) of the parameters passed to the routine.
32152
32153 The name to use on the Ada side when importing a C routine with a
32154 @code{Stdcall} calling convention is the name of the C routine. The leading
32155 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
32156 the compiler. For instance the Win32 function:
32157
32158 @smallexample
32159 @b{APIENTRY} int get_val (long);
32160 @end smallexample
32161
32162 @noindent
32163 should be imported from Ada as follows:
32164
32165 @smallexample @c ada
32166 @group
32167 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32168 pragma Import (Stdcall, Get_Val);
32169 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
32170 @end group
32171 @end smallexample
32172
32173 @noindent
32174 As for the @code{C} calling convention, when the @code{External_Name}
32175 parameter is missing, it is taken to be the name of the Ada entity in lower
32176 case. If instead of writing the above import pragma you write:
32177
32178 @smallexample @c ada
32179 @group
32180 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32181 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
32182 @end group
32183 @end smallexample
32184
32185 @noindent
32186 then the imported routine is @code{_retrieve_val@@4}. However, if instead
32187 of specifying the @code{External_Name} parameter you specify the
32188 @code{Link_Name} as in the following example:
32189
32190 @smallexample @c ada
32191 @group
32192 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32193 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
32194 @end group
32195 @end smallexample
32196
32197 @noindent
32198 then the imported routine is @code{retrieve_val}, that is, there is no
32199 decoration at all. No leading underscore and no Stdcall suffix
32200 @code{@@}@code{@var{nn}}.
32201
32202 @noindent
32203 This is especially important as in some special cases a DLL's entry
32204 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
32205 name generated for a call has it.
32206
32207 @noindent
32208 It is also possible to import variables defined in a DLL by using an
32209 import pragma for a variable. As an example, if a DLL contains a
32210 variable defined as:
32211
32212 @smallexample
32213 int my_var;
32214 @end smallexample
32215
32216 @noindent
32217 then, to access this variable from Ada you should write:
32218
32219 @smallexample @c ada
32220 @group
32221 My_Var : Interfaces.C.int;
32222 pragma Import (Stdcall, My_Var);
32223 @end group
32224 @end smallexample
32225
32226 @noindent
32227 Note that to ease building cross-platform bindings this convention
32228 will be handled as a @code{C} calling convention on non-Windows platforms.
32229
32230 @node Win32 Calling Convention
32231 @subsection @code{Win32} Calling Convention
32232
32233 @noindent
32234 This convention, which is GNAT-specific is fully equivalent to the
32235 @code{Stdcall} calling convention described above.
32236
32237 @node DLL Calling Convention
32238 @subsection @code{DLL} Calling Convention
32239
32240 @noindent
32241 This convention, which is GNAT-specific is fully equivalent to the
32242 @code{Stdcall} calling convention described above.
32243
32244 @node Introduction to Dynamic Link Libraries (DLLs)
32245 @section Introduction to Dynamic Link Libraries (DLLs)
32246 @findex DLL
32247
32248 @noindent
32249 A Dynamically Linked Library (DLL) is a library that can be shared by
32250 several applications running under Windows. A DLL can contain any number of
32251 routines and variables.
32252
32253 One advantage of DLLs is that you can change and enhance them without
32254 forcing all the applications that depend on them to be relinked or
32255 recompiled. However, you should be aware than all calls to DLL routines are
32256 slower since, as you will understand below, such calls are indirect.
32257
32258 To illustrate the remainder of this section, suppose that an application
32259 wants to use the services of a DLL @file{API.dll}. To use the services
32260 provided by @file{API.dll} you must statically link against the DLL or
32261 an import library which contains a jump table with an entry for each
32262 routine and variable exported by the DLL. In the Microsoft world this
32263 import library is called @file{API.lib}. When using GNAT this import
32264 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
32265 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
32266
32267 After you have linked your application with the DLL or the import library
32268 and you run your application, here is what happens:
32269
32270 @enumerate
32271 @item
32272 Your application is loaded into memory.
32273
32274 @item
32275 The DLL @file{API.dll} is mapped into the address space of your
32276 application. This means that:
32277
32278 @itemize @bullet
32279 @item
32280 The DLL will use the stack of the calling thread.
32281
32282 @item
32283 The DLL will use the virtual address space of the calling process.
32284
32285 @item
32286 The DLL will allocate memory from the virtual address space of the calling
32287 process.
32288
32289 @item
32290 Handles (pointers) can be safely exchanged between routines in the DLL
32291 routines and routines in the application using the DLL.
32292 @end itemize
32293
32294 @item
32295 The entries in the jump table (from the import library @file{libAPI.dll.a}
32296 or @file{API.lib} or automatically created when linking against a DLL)
32297 which is part of your application are initialized with the addresses
32298 of the routines and variables in @file{API.dll}.
32299
32300 @item
32301 If present in @file{API.dll}, routines @code{DllMain} or
32302 @code{DllMainCRTStartup} are invoked. These routines typically contain
32303 the initialization code needed for the well-being of the routines and
32304 variables exported by the DLL.
32305 @end enumerate
32306
32307 @noindent
32308 There is an additional point which is worth mentioning. In the Windows
32309 world there are two kind of DLLs: relocatable and non-relocatable
32310 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
32311 in the target application address space. If the addresses of two
32312 non-relocatable DLLs overlap and these happen to be used by the same
32313 application, a conflict will occur and the application will run
32314 incorrectly. Hence, when possible, it is always preferable to use and
32315 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
32316 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
32317 User's Guide) removes the debugging symbols from the DLL but the DLL can
32318 still be relocated.
32319
32320 As a side note, an interesting difference between Microsoft DLLs and
32321 Unix shared libraries, is the fact that on most Unix systems all public
32322 routines are exported by default in a Unix shared library, while under
32323 Windows it is possible (but not required) to list exported routines in
32324 a definition file (@pxref{The Definition File}).
32325
32326 @node Using DLLs with GNAT
32327 @section Using DLLs with GNAT
32328
32329 @menu
32330 * Creating an Ada Spec for the DLL Services::
32331 * Creating an Import Library::
32332 @end menu
32333
32334 @noindent
32335 To use the services of a DLL, say @file{API.dll}, in your Ada application
32336 you must have:
32337
32338 @enumerate
32339 @item
32340 The Ada spec for the routines and/or variables you want to access in
32341 @file{API.dll}. If not available this Ada spec must be built from the C/C++
32342 header files provided with the DLL.
32343
32344 @item
32345 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
32346 mentioned an import library is a statically linked library containing the
32347 import table which will be filled at load time to point to the actual
32348 @file{API.dll} routines. Sometimes you don't have an import library for the
32349 DLL you want to use. The following sections will explain how to build
32350 one. Note that this is optional.
32351
32352 @item
32353 The actual DLL, @file{API.dll}.
32354 @end enumerate
32355
32356 @noindent
32357 Once you have all the above, to compile an Ada application that uses the
32358 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
32359 you simply issue the command
32360
32361 @smallexample
32362 $ gnatmake my_ada_app -largs -lAPI
32363 @end smallexample
32364
32365 @noindent
32366 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
32367 tells the GNAT linker to look first for a library named @file{API.lib}
32368 (Microsoft-style name) and if not found for a libraries named
32369 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
32370 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
32371 contains the following pragma
32372
32373 @smallexample @c ada
32374 pragma Linker_Options ("-lAPI");
32375 @end smallexample
32376
32377 @noindent
32378 you do not have to add @option{-largs -lAPI} at the end of the
32379 @command{gnatmake} command.
32380
32381 If any one of the items above is missing you will have to create it
32382 yourself. The following sections explain how to do so using as an
32383 example a fictitious DLL called @file{API.dll}.
32384
32385 @node Creating an Ada Spec for the DLL Services
32386 @subsection Creating an Ada Spec for the DLL Services
32387
32388 @noindent
32389 A DLL typically comes with a C/C++ header file which provides the
32390 definitions of the routines and variables exported by the DLL. The Ada
32391 equivalent of this header file is a package spec that contains definitions
32392 for the imported entities. If the DLL you intend to use does not come with
32393 an Ada spec you have to generate one such spec yourself. For example if
32394 the header file of @file{API.dll} is a file @file{api.h} containing the
32395 following two definitions:
32396
32397 @smallexample
32398 @group
32399 @cartouche
32400 int some_var;
32401 int get (char *);
32402 @end cartouche
32403 @end group
32404 @end smallexample
32405
32406 @noindent
32407 then the equivalent Ada spec could be:
32408
32409 @smallexample @c ada
32410 @group
32411 @cartouche
32412 with Interfaces.C.Strings;
32413 package API is
32414    use Interfaces;
32415
32416    Some_Var : C.int;
32417    function Get (Str : C.Strings.Chars_Ptr) return C.int;
32418
32419 private
32420    pragma Import (C, Get);
32421    pragma Import (DLL, Some_Var);
32422 end API;
32423 @end cartouche
32424 @end group
32425 @end smallexample
32426
32427 @noindent
32428 Note that a variable is
32429 @strong{always imported with a Stdcall convention}. A function
32430 can have @code{C} or @code{Stdcall} convention.
32431 (@pxref{Windows Calling Conventions}).
32432
32433 @node Creating an Import Library
32434 @subsection Creating an Import Library
32435 @cindex Import library
32436
32437 @menu
32438 * The Definition File::
32439 * GNAT-Style Import Library::
32440 * Microsoft-Style Import Library::
32441 @end menu
32442
32443 @noindent
32444 If a Microsoft-style import library @file{API.lib} or a GNAT-style
32445 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
32446 with @file{API.dll} you can skip this section. You can also skip this
32447 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
32448 as in this case it is possible to link directly against the
32449 DLL. Otherwise read on.
32450
32451 @node The Definition File
32452 @subsubsection The Definition File
32453 @cindex Definition file
32454 @findex .def
32455
32456 @noindent
32457 As previously mentioned, and unlike Unix systems, the list of symbols
32458 that are exported from a DLL must be provided explicitly in Windows.
32459 The main goal of a definition file is precisely that: list the symbols
32460 exported by a DLL. A definition file (usually a file with a @code{.def}
32461 suffix) has the following structure:
32462
32463 @smallexample
32464 @group
32465 @cartouche
32466 @r{[}LIBRARY @var{name}@r{]}
32467 @r{[}DESCRIPTION @var{string}@r{]}
32468 EXPORTS
32469    @var{symbol1}
32470    @var{symbol2}
32471    @dots{}
32472 @end cartouche
32473 @end group
32474 @end smallexample
32475
32476 @table @code
32477 @item LIBRARY @var{name}
32478 This section, which is optional, gives the name of the DLL.
32479
32480 @item DESCRIPTION @var{string}
32481 This section, which is optional, gives a description string that will be
32482 embedded in the import library.
32483
32484 @item EXPORTS
32485 This section gives the list of exported symbols (procedures, functions or
32486 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
32487 section of @file{API.def} looks like:
32488
32489 @smallexample
32490 @group
32491 @cartouche
32492 EXPORTS
32493    some_var
32494    get
32495 @end cartouche
32496 @end group
32497 @end smallexample
32498 @end table
32499
32500 @noindent
32501 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
32502 (@pxref{Windows Calling Conventions}) for a Stdcall
32503 calling convention function in the exported symbols list.
32504
32505 @noindent
32506 There can actually be other sections in a definition file, but these
32507 sections are not relevant to the discussion at hand.
32508
32509 @node GNAT-Style Import Library
32510 @subsubsection GNAT-Style Import Library
32511
32512 @noindent
32513 To create a static import library from @file{API.dll} with the GNAT tools
32514 you should proceed as follows:
32515
32516 @enumerate
32517 @item
32518 Create the definition file @file{API.def} (@pxref{The Definition File}).
32519 For that use the @code{dll2def} tool as follows:
32520
32521 @smallexample
32522 $ dll2def API.dll > API.def
32523 @end smallexample
32524
32525 @noindent
32526 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
32527 to standard output the list of entry points in the DLL. Note that if
32528 some routines in the DLL have the @code{Stdcall} convention
32529 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
32530 suffix then you'll have to edit @file{api.def} to add it, and specify
32531 @option{-k} to @command{gnatdll} when creating the import library.
32532
32533 @noindent
32534 Here are some hints to find the right @code{@@}@var{nn} suffix.
32535
32536 @enumerate
32537 @item
32538 If you have the Microsoft import library (.lib), it is possible to get
32539 the right symbols by using Microsoft @code{dumpbin} tool (see the
32540 corresponding Microsoft documentation for further details).
32541
32542 @smallexample
32543 $ dumpbin /exports api.lib
32544 @end smallexample
32545
32546 @item
32547 If you have a message about a missing symbol at link time the compiler
32548 tells you what symbol is expected. You just have to go back to the
32549 definition file and add the right suffix.
32550 @end enumerate
32551
32552 @item
32553 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
32554 (@pxref{Using gnatdll}) as follows:
32555
32556 @smallexample
32557 $ gnatdll -e API.def -d API.dll
32558 @end smallexample
32559
32560 @noindent
32561 @code{gnatdll} takes as input a definition file @file{API.def} and the
32562 name of the DLL containing the services listed in the definition file
32563 @file{API.dll}. The name of the static import library generated is
32564 computed from the name of the definition file as follows: if the
32565 definition file name is @var{xyz}@code{.def}, the import library name will
32566 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
32567 @option{-e} could have been removed because the name of the definition
32568 file (before the ``@code{.def}'' suffix) is the same as the name of the
32569 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
32570 @end enumerate
32571
32572 @node Microsoft-Style Import Library
32573 @subsubsection Microsoft-Style Import Library
32574
32575 @noindent
32576 With GNAT you can either use a GNAT-style or Microsoft-style import
32577 library. A Microsoft import library is needed only if you plan to make an
32578 Ada DLL available to applications developed with Microsoft
32579 tools (@pxref{Mixed-Language Programming on Windows}).
32580
32581 To create a Microsoft-style import library for @file{API.dll} you
32582 should proceed as follows:
32583
32584 @enumerate
32585 @item
32586 Create the definition file @file{API.def} from the DLL. For this use either
32587 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
32588 tool (see the corresponding Microsoft documentation for further details).
32589
32590 @item
32591 Build the actual import library using Microsoft's @code{lib} utility:
32592
32593 @smallexample
32594 $ lib -machine:IX86 -def:API.def -out:API.lib
32595 @end smallexample
32596
32597 @noindent
32598 If you use the above command the definition file @file{API.def} must
32599 contain a line giving the name of the DLL:
32600
32601 @smallexample
32602 LIBRARY      "API"
32603 @end smallexample
32604
32605 @noindent
32606 See the Microsoft documentation for further details about the usage of
32607 @code{lib}.
32608 @end enumerate
32609
32610 @node Building DLLs with GNAT
32611 @section Building DLLs with GNAT
32612 @cindex DLLs, building
32613
32614 @noindent
32615 This section explain how to build DLLs using the GNAT built-in DLL
32616 support. With the following procedure it is straight forward to build
32617 and use DLLs with GNAT.
32618
32619 @enumerate
32620
32621 @item building object files
32622
32623 The first step is to build all objects files that are to be included
32624 into the DLL. This is done by using the standard @command{gnatmake} tool.
32625
32626 @item building the DLL
32627
32628 To build the DLL you must use @command{gcc}'s @option{-shared}
32629 option. It is quite simple to use this method:
32630
32631 @smallexample
32632 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
32633 @end smallexample
32634
32635 It is important to note that in this case all symbols found in the
32636 object files are automatically exported. It is possible to restrict
32637 the set of symbols to export by passing to @command{gcc} a definition
32638 file, @pxref{The Definition File}. For example:
32639
32640 @smallexample
32641 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
32642 @end smallexample
32643
32644 If you use a definition file you must export the elaboration procedures
32645 for every package that required one. Elaboration procedures are named
32646 using the package name followed by "_E".
32647
32648 @item preparing DLL to be used
32649
32650 For the DLL to be used by client programs the bodies must be hidden
32651 from it and the .ali set with read-only attribute. This is very important
32652 otherwise GNAT will recompile all packages and will not actually use
32653 the code in the DLL. For example:
32654
32655 @smallexample
32656 $ mkdir apilib
32657 $ copy *.ads *.ali api.dll apilib
32658 $ attrib +R apilib\*.ali
32659 @end smallexample
32660
32661 @end enumerate
32662
32663 At this point it is possible to use the DLL by directly linking
32664 against it. Note that you must use the GNAT shared runtime when using
32665 GNAT shared libraries. This is achieved by using @option{-shared} binder's
32666 option.
32667
32668 @smallexample
32669 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
32670 @end smallexample
32671
32672 @node Building DLLs with GNAT Project files
32673 @section Building DLLs with GNAT Project files
32674 @cindex DLLs, building
32675
32676 @noindent
32677 There is nothing specific to Windows in the build process.
32678 @pxref{Library Projects}.
32679
32680 @noindent
32681 Due to a system limitation, it is not possible under Windows to create threads
32682 when inside the @code{DllMain} routine which is used for auto-initialization
32683 of shared libraries, so it is not possible to have library level tasks in SALs.
32684
32685 @node Building DLLs with gnatdll
32686 @section Building DLLs with gnatdll
32687 @cindex DLLs, building
32688
32689 @menu
32690 * Limitations When Using Ada DLLs from Ada::
32691 * Exporting Ada Entities::
32692 * Ada DLLs and Elaboration::
32693 * Ada DLLs and Finalization::
32694 * Creating a Spec for Ada DLLs::
32695 * Creating the Definition File::
32696 * Using gnatdll::
32697 @end menu
32698
32699 @noindent
32700 Note that it is preferred to use the built-in GNAT DLL support
32701 (@pxref{Building DLLs with GNAT}) or GNAT Project files
32702 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
32703
32704 This section explains how to build DLLs containing Ada code using
32705 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
32706 remainder of this section.
32707
32708 The steps required to build an Ada DLL that is to be used by Ada as well as
32709 non-Ada applications are as follows:
32710
32711 @enumerate
32712 @item
32713 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
32714 @code{Stdcall} calling convention to avoid any Ada name mangling for the
32715 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
32716 skip this step if you plan to use the Ada DLL only from Ada applications.
32717
32718 @item
32719 Your Ada code must export an initialization routine which calls the routine
32720 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
32721 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
32722 routine exported by the Ada DLL must be invoked by the clients of the DLL
32723 to initialize the DLL.
32724
32725 @item
32726 When useful, the DLL should also export a finalization routine which calls
32727 routine @code{adafinal} generated by @command{gnatbind} to perform the
32728 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
32729 The finalization routine exported by the Ada DLL must be invoked by the
32730 clients of the DLL when the DLL services are no further needed.
32731
32732 @item
32733 You must provide a spec for the services exported by the Ada DLL in each
32734 of the programming languages to which you plan to make the DLL available.
32735
32736 @item
32737 You must provide a definition file listing the exported entities
32738 (@pxref{The Definition File}).
32739
32740 @item
32741 Finally you must use @code{gnatdll} to produce the DLL and the import
32742 library (@pxref{Using gnatdll}).
32743 @end enumerate
32744
32745 @noindent
32746 Note that a relocatable DLL stripped using the @code{strip}
32747 binutils tool will not be relocatable anymore. To build a DLL without
32748 debug information pass @code{-largs -s} to @code{gnatdll}. This
32749 restriction does not apply to a DLL built using a Library Project.
32750 @pxref{Library Projects}.
32751
32752 @node Limitations When Using Ada DLLs from Ada
32753 @subsection Limitations When Using Ada DLLs from Ada
32754
32755 @noindent
32756 When using Ada DLLs from Ada applications there is a limitation users
32757 should be aware of. Because on Windows the GNAT run time is not in a DLL of
32758 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
32759 each Ada DLL includes the services of the GNAT run time that are necessary
32760 to the Ada code inside the DLL. As a result, when an Ada program uses an
32761 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
32762 one in the main program.
32763
32764 It is therefore not possible to exchange GNAT run-time objects between the
32765 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
32766 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
32767 types, etc.
32768
32769 It is completely safe to exchange plain elementary, array or record types,
32770 Windows object handles, etc.
32771
32772 @node Exporting Ada Entities
32773 @subsection Exporting Ada Entities
32774 @cindex Export table
32775
32776 @noindent
32777 Building a DLL is a way to encapsulate a set of services usable from any
32778 application. As a result, the Ada entities exported by a DLL should be
32779 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
32780 any Ada name mangling. As an example here is an Ada package
32781 @code{API}, spec and body, exporting two procedures, a function, and a
32782 variable:
32783
32784 @smallexample @c ada
32785 @group
32786 @cartouche
32787 with Interfaces.C; use Interfaces;
32788 package API is
32789    Count : C.int := 0;
32790    function Factorial (Val : C.int) return C.int;
32791
32792    procedure Initialize_API;
32793    procedure Finalize_API;
32794    --  Initialization & Finalization routines. More in the next section.
32795 private
32796    pragma Export (C, Initialize_API);
32797    pragma Export (C, Finalize_API);
32798    pragma Export (C, Count);
32799    pragma Export (C, Factorial);
32800 end API;
32801 @end cartouche
32802 @end group
32803 @end smallexample
32804
32805 @smallexample @c ada
32806 @group
32807 @cartouche
32808 package body API is
32809    function Factorial (Val : C.int) return C.int is
32810       Fact : C.int := 1;
32811    begin
32812       Count := Count + 1;
32813       for K in 1 .. Val loop
32814          Fact := Fact * K;
32815       end loop;
32816       return Fact;
32817    end Factorial;
32818
32819    procedure Initialize_API is
32820       procedure Adainit;
32821       pragma Import (C, Adainit);
32822    begin
32823       Adainit;
32824    end Initialize_API;
32825
32826    procedure Finalize_API is
32827       procedure Adafinal;
32828       pragma Import (C, Adafinal);
32829    begin
32830       Adafinal;
32831    end Finalize_API;
32832 end API;
32833 @end cartouche
32834 @end group
32835 @end smallexample
32836
32837 @noindent
32838 If the Ada DLL you are building will only be used by Ada applications
32839 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
32840 convention. As an example, the previous package could be written as
32841 follows:
32842
32843 @smallexample @c ada
32844 @group
32845 @cartouche
32846 package API is
32847    Count : Integer := 0;
32848    function Factorial (Val : Integer) return Integer;
32849
32850    procedure Initialize_API;
32851    procedure Finalize_API;
32852    --  Initialization and Finalization routines.
32853 end API;
32854 @end cartouche
32855 @end group
32856 @end smallexample
32857
32858 @smallexample @c ada
32859 @group
32860 @cartouche
32861 package body API is
32862    function Factorial (Val : Integer) return Integer is
32863       Fact : Integer := 1;
32864    begin
32865       Count := Count + 1;
32866       for K in 1 .. Val loop
32867          Fact := Fact * K;
32868       end loop;
32869       return Fact;
32870    end Factorial;
32871
32872    @dots{}
32873    --  The remainder of this package body is unchanged.
32874 end API;
32875 @end cartouche
32876 @end group
32877 @end smallexample
32878
32879 @noindent
32880 Note that if you do not export the Ada entities with a @code{C} or
32881 @code{Stdcall} convention you will have to provide the mangled Ada names
32882 in the definition file of the Ada DLL
32883 (@pxref{Creating the Definition File}).
32884
32885 @node Ada DLLs and Elaboration
32886 @subsection Ada DLLs and Elaboration
32887 @cindex DLLs and elaboration
32888
32889 @noindent
32890 The DLL that you are building contains your Ada code as well as all the
32891 routines in the Ada library that are needed by it. The first thing a
32892 user of your DLL must do is elaborate the Ada code
32893 (@pxref{Elaboration Order Handling in GNAT}).
32894
32895 To achieve this you must export an initialization routine
32896 (@code{Initialize_API} in the previous example), which must be invoked
32897 before using any of the DLL services. This elaboration routine must call
32898 the Ada elaboration routine @code{adainit} generated by the GNAT binder
32899 (@pxref{Binding with Non-Ada Main Programs}). See the body of
32900 @code{Initialize_Api} for an example. Note that the GNAT binder is
32901 automatically invoked during the DLL build process by the @code{gnatdll}
32902 tool (@pxref{Using gnatdll}).
32903
32904 When a DLL is loaded, Windows systematically invokes a routine called
32905 @code{DllMain}. It would therefore be possible to call @code{adainit}
32906 directly from @code{DllMain} without having to provide an explicit
32907 initialization routine. Unfortunately, it is not possible to call
32908 @code{adainit} from the @code{DllMain} if your program has library level
32909 tasks because access to the @code{DllMain} entry point is serialized by
32910 the system (that is, only a single thread can execute ``through'' it at a
32911 time), which means that the GNAT run time will deadlock waiting for the
32912 newly created task to complete its initialization.
32913
32914 @node Ada DLLs and Finalization
32915 @subsection Ada DLLs and Finalization
32916 @cindex DLLs and finalization
32917
32918 @noindent
32919 When the services of an Ada DLL are no longer needed, the client code should
32920 invoke the DLL finalization routine, if available. The DLL finalization
32921 routine is in charge of releasing all resources acquired by the DLL. In the
32922 case of the Ada code contained in the DLL, this is achieved by calling
32923 routine @code{adafinal} generated by the GNAT binder
32924 (@pxref{Binding with Non-Ada Main Programs}).
32925 See the body of @code{Finalize_Api} for an
32926 example. As already pointed out the GNAT binder is automatically invoked
32927 during the DLL build process by the @code{gnatdll} tool
32928 (@pxref{Using gnatdll}).
32929
32930 @node Creating a Spec for Ada DLLs
32931 @subsection Creating a Spec for Ada DLLs
32932
32933 @noindent
32934 To use the services exported by the Ada DLL from another programming
32935 language (e.g.@: C), you have to translate the specs of the exported Ada
32936 entities in that language. For instance in the case of @code{API.dll},
32937 the corresponding C header file could look like:
32938
32939 @smallexample
32940 @group
32941 @cartouche
32942 extern int *_imp__count;
32943 #define count (*_imp__count)
32944 int factorial (int);
32945 @end cartouche
32946 @end group
32947 @end smallexample
32948
32949 @noindent
32950 It is important to understand that when building an Ada DLL to be used by
32951 other Ada applications, you need two different specs for the packages
32952 contained in the DLL: one for building the DLL and the other for using
32953 the DLL. This is because the @code{DLL} calling convention is needed to
32954 use a variable defined in a DLL, but when building the DLL, the variable
32955 must have either the @code{Ada} or @code{C} calling convention. As an
32956 example consider a DLL comprising the following package @code{API}:
32957
32958 @smallexample @c ada
32959 @group
32960 @cartouche
32961 package API is
32962    Count : Integer := 0;
32963    @dots{}
32964    --  Remainder of the package omitted.
32965 end API;
32966 @end cartouche
32967 @end group
32968 @end smallexample
32969
32970 @noindent
32971 After producing a DLL containing package @code{API}, the spec that
32972 must be used to import @code{API.Count} from Ada code outside of the
32973 DLL is:
32974
32975 @smallexample @c ada
32976 @group
32977 @cartouche
32978 package API is
32979    Count : Integer;
32980    pragma Import (DLL, Count);
32981 end API;
32982 @end cartouche
32983 @end group
32984 @end smallexample
32985
32986 @node Creating the Definition File
32987 @subsection Creating the Definition File
32988
32989 @noindent
32990 The definition file is the last file needed to build the DLL. It lists
32991 the exported symbols. As an example, the definition file for a DLL
32992 containing only package @code{API} (where all the entities are exported
32993 with a @code{C} calling convention) is:
32994
32995 @smallexample
32996 @group
32997 @cartouche
32998 EXPORTS
32999     count
33000     factorial
33001     finalize_api
33002     initialize_api
33003 @end cartouche
33004 @end group
33005 @end smallexample
33006
33007 @noindent
33008 If the @code{C} calling convention is missing from package @code{API},
33009 then the definition file contains the mangled Ada names of the above
33010 entities, which in this case are:
33011
33012 @smallexample
33013 @group
33014 @cartouche
33015 EXPORTS
33016     api__count
33017     api__factorial
33018     api__finalize_api
33019     api__initialize_api
33020 @end cartouche
33021 @end group
33022 @end smallexample
33023
33024 @node Using gnatdll
33025 @subsection Using @code{gnatdll}
33026 @findex gnatdll
33027
33028 @menu
33029 * gnatdll Example::
33030 * gnatdll behind the Scenes::
33031 * Using dlltool::
33032 @end menu
33033
33034 @noindent
33035 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
33036 and non-Ada sources that make up your DLL have been compiled.
33037 @code{gnatdll} is actually in charge of two distinct tasks: build the
33038 static import library for the DLL and the actual DLL. The form of the
33039 @code{gnatdll} command is
33040
33041 @smallexample
33042 @cartouche
33043 $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
33044 @end cartouche
33045 @end smallexample
33046
33047 @noindent
33048 where @var{list-of-files} is a list of ALI and object files. The object
33049 file list must be the exact list of objects corresponding to the non-Ada
33050 sources whose services are to be included in the DLL. The ALI file list
33051 must be the exact list of ALI files for the corresponding Ada sources
33052 whose services are to be included in the DLL. If @var{list-of-files} is
33053 missing, only the static import library is generated.
33054
33055 @noindent
33056 You may specify any of the following switches to @code{gnatdll}:
33057
33058 @table @code
33059 @item -a@ovar{address}
33060 @cindex @option{-a} (@code{gnatdll})
33061 Build a non-relocatable DLL at @var{address}. If @var{address} is not
33062 specified the default address @var{0x11000000} will be used. By default,
33063 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
33064 advise the reader to build relocatable DLL.
33065
33066 @item -b @var{address}
33067 @cindex @option{-b} (@code{gnatdll})
33068 Set the relocatable DLL base address. By default the address is
33069 @code{0x11000000}.
33070
33071 @item -bargs @var{opts}
33072 @cindex @option{-bargs} (@code{gnatdll})
33073 Binder options. Pass @var{opts} to the binder.
33074
33075 @item -d @var{dllfile}
33076 @cindex @option{-d} (@code{gnatdll})
33077 @var{dllfile} is the name of the DLL. This switch must be present for
33078 @code{gnatdll} to do anything. The name of the generated import library is
33079 obtained algorithmically from @var{dllfile} as shown in the following
33080 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
33081 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
33082 by option @option{-e}) is obtained algorithmically from @var{dllfile}
33083 as shown in the following example:
33084 if @var{dllfile} is @code{xyz.dll}, the definition
33085 file used is @code{xyz.def}.
33086
33087 @item -e @var{deffile}
33088 @cindex @option{-e} (@code{gnatdll})
33089 @var{deffile} is the name of the definition file.
33090
33091 @item -g
33092 @cindex @option{-g} (@code{gnatdll})
33093 Generate debugging information. This information is stored in the object
33094 file and copied from there to the final DLL file by the linker,
33095 where it can be read by the debugger. You must use the
33096 @option{-g} switch if you plan on using the debugger or the symbolic
33097 stack traceback.
33098
33099 @item -h
33100 @cindex @option{-h} (@code{gnatdll})
33101 Help mode. Displays @code{gnatdll} switch usage information.
33102
33103 @item -Idir
33104 @cindex @option{-I} (@code{gnatdll})
33105 Direct @code{gnatdll} to search the @var{dir} directory for source and
33106 object files needed to build the DLL.
33107 (@pxref{Search Paths and the Run-Time Library (RTL)}).
33108
33109 @item -k
33110 @cindex @option{-k} (@code{gnatdll})
33111 Removes the @code{@@}@var{nn} suffix from the import library's exported
33112 names, but keeps them for the link names. You must specify this
33113 option if you want to use a @code{Stdcall} function in a DLL for which
33114 the @code{@@}@var{nn} suffix has been removed. This is the case for most
33115 of the Windows NT DLL for example. This option has no effect when
33116 @option{-n} option is specified.
33117
33118 @item -l @var{file}
33119 @cindex @option{-l} (@code{gnatdll})
33120 The list of ALI and object files used to build the DLL are listed in
33121 @var{file}, instead of being given in the command line. Each line in
33122 @var{file} contains the name of an ALI or object file.
33123
33124 @item -n
33125 @cindex @option{-n} (@code{gnatdll})
33126 No Import. Do not create the import library.
33127
33128 @item -q
33129 @cindex @option{-q} (@code{gnatdll})
33130 Quiet mode. Do not display unnecessary messages.
33131
33132 @item -v
33133 @cindex @option{-v} (@code{gnatdll})
33134 Verbose mode. Display extra information.
33135
33136 @item -largs @var{opts}
33137 @cindex @option{-largs} (@code{gnatdll})
33138 Linker options. Pass @var{opts} to the linker.
33139 @end table
33140
33141 @node gnatdll Example
33142 @subsubsection @code{gnatdll} Example
33143
33144 @noindent
33145 As an example the command to build a relocatable DLL from @file{api.adb}
33146 once @file{api.adb} has been compiled and @file{api.def} created is
33147
33148 @smallexample
33149 $ gnatdll -d api.dll api.ali
33150 @end smallexample
33151
33152 @noindent
33153 The above command creates two files: @file{libapi.dll.a} (the import
33154 library) and @file{api.dll} (the actual DLL). If you want to create
33155 only the DLL, just type:
33156
33157 @smallexample
33158 $ gnatdll -d api.dll -n api.ali
33159 @end smallexample
33160
33161 @noindent
33162 Alternatively if you want to create just the import library, type:
33163
33164 @smallexample
33165 $ gnatdll -d api.dll
33166 @end smallexample
33167
33168 @node gnatdll behind the Scenes
33169 @subsubsection @code{gnatdll} behind the Scenes
33170
33171 @noindent
33172 This section details the steps involved in creating a DLL. @code{gnatdll}
33173 does these steps for you. Unless you are interested in understanding what
33174 goes on behind the scenes, you should skip this section.
33175
33176 We use the previous example of a DLL containing the Ada package @code{API},
33177 to illustrate the steps necessary to build a DLL. The starting point is a
33178 set of objects that will make up the DLL and the corresponding ALI
33179 files. In the case of this example this means that @file{api.o} and
33180 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
33181 the following:
33182
33183 @enumerate
33184 @item
33185 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
33186 the information necessary to generate relocation information for the
33187 DLL.
33188
33189 @smallexample
33190 @group
33191 $ gnatbind -n api
33192 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
33193 @end group
33194 @end smallexample
33195
33196 @noindent
33197 In addition to the base file, the @command{gnatlink} command generates an
33198 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
33199 asks @command{gnatlink} to generate the routines @code{DllMain} and
33200 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
33201 is loaded into memory.
33202
33203 @item
33204 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
33205 export table (@file{api.exp}). The export table contains the relocation
33206 information in a form which can be used during the final link to ensure
33207 that the Windows loader is able to place the DLL anywhere in memory.
33208
33209 @smallexample
33210 @group
33211 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33212           --output-exp api.exp
33213 @end group
33214 @end smallexample
33215
33216 @item
33217 @code{gnatdll} builds the base file using the new export table. Note that
33218 @command{gnatbind} must be called once again since the binder generated file
33219 has been deleted during the previous call to @command{gnatlink}.
33220
33221 @smallexample
33222 @group
33223 $ gnatbind -n api
33224 $ gnatlink api -o api.jnk api.exp -mdll
33225       -Wl,--base-file,api.base
33226 @end group
33227 @end smallexample
33228
33229 @item
33230 @code{gnatdll} builds the new export table using the new base file and
33231 generates the DLL import library @file{libAPI.dll.a}.
33232
33233 @smallexample
33234 @group
33235 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33236           --output-exp api.exp --output-lib libAPI.a
33237 @end group
33238 @end smallexample
33239
33240 @item
33241 Finally @code{gnatdll} builds the relocatable DLL using the final export
33242 table.
33243
33244 @smallexample
33245 @group
33246 $ gnatbind -n api
33247 $ gnatlink api api.exp -o api.dll -mdll
33248 @end group
33249 @end smallexample
33250 @end enumerate
33251
33252 @node Using dlltool
33253 @subsubsection Using @code{dlltool}
33254
33255 @noindent
33256 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
33257 DLLs and static import libraries. This section summarizes the most
33258 common @code{dlltool} switches. The form of the @code{dlltool} command
33259 is
33260
33261 @smallexample
33262 $ dlltool @ovar{switches}
33263 @end smallexample
33264
33265 @noindent
33266 @code{dlltool} switches include:
33267
33268 @table @option
33269 @item --base-file @var{basefile}
33270 @cindex @option{--base-file} (@command{dlltool})
33271 Read the base file @var{basefile} generated by the linker. This switch
33272 is used to create a relocatable DLL.
33273
33274 @item --def @var{deffile}
33275 @cindex @option{--def} (@command{dlltool})
33276 Read the definition file.
33277
33278 @item --dllname @var{name}
33279 @cindex @option{--dllname} (@command{dlltool})
33280 Gives the name of the DLL. This switch is used to embed the name of the
33281 DLL in the static import library generated by @code{dlltool} with switch
33282 @option{--output-lib}.
33283
33284 @item -k
33285 @cindex @option{-k} (@command{dlltool})
33286 Kill @code{@@}@var{nn} from exported names
33287 (@pxref{Windows Calling Conventions}
33288 for a discussion about @code{Stdcall}-style symbols.
33289
33290 @item --help
33291 @cindex @option{--help} (@command{dlltool})
33292 Prints the @code{dlltool} switches with a concise description.
33293
33294 @item --output-exp @var{exportfile}
33295 @cindex @option{--output-exp} (@command{dlltool})
33296 Generate an export file @var{exportfile}. The export file contains the
33297 export table (list of symbols in the DLL) and is used to create the DLL.
33298
33299 @item --output-lib @var{libfile}
33300 @cindex @option{--output-lib} (@command{dlltool})
33301 Generate a static import library @var{libfile}.
33302
33303 @item -v
33304 @cindex @option{-v} (@command{dlltool})
33305 Verbose mode.
33306
33307 @item --as @var{assembler-name}
33308 @cindex @option{--as} (@command{dlltool})
33309 Use @var{assembler-name} as the assembler. The default is @code{as}.
33310 @end table
33311
33312 @node GNAT and Windows Resources
33313 @section GNAT and Windows Resources
33314 @cindex Resources, windows
33315
33316 @menu
33317 * Building Resources::
33318 * Compiling Resources::
33319 * Using Resources::
33320 @end menu
33321
33322 @noindent
33323 Resources are an easy way to add Windows specific objects to your
33324 application. The objects that can be added as resources include:
33325
33326 @itemize @bullet
33327 @item
33328 menus
33329
33330 @item
33331 accelerators
33332
33333 @item
33334 dialog boxes
33335
33336 @item
33337 string tables
33338
33339 @item
33340 bitmaps
33341
33342 @item
33343 cursors
33344
33345 @item
33346 icons
33347
33348 @item
33349 fonts
33350 @end itemize
33351
33352 @noindent
33353 This section explains how to build, compile and use resources.
33354
33355 @node Building Resources
33356 @subsection Building Resources
33357 @cindex Resources, building
33358
33359 @noindent
33360 A resource file is an ASCII file. By convention resource files have an
33361 @file{.rc} extension.
33362 The easiest way to build a resource file is to use Microsoft tools
33363 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
33364 @code{dlgedit.exe} to build dialogs.
33365 It is always possible to build an @file{.rc} file yourself by writing a
33366 resource script.
33367
33368 It is not our objective to explain how to write a resource file. A
33369 complete description of the resource script language can be found in the
33370 Microsoft documentation.
33371
33372 @node Compiling Resources
33373 @subsection Compiling Resources
33374 @findex rc
33375 @findex windres
33376 @cindex Resources, compiling
33377
33378 @noindent
33379 This section describes how to build a GNAT-compatible (COFF) object file
33380 containing the resources. This is done using the Resource Compiler
33381 @code{windres} as follows:
33382
33383 @smallexample
33384 $ windres -i myres.rc -o myres.o
33385 @end smallexample
33386
33387 @noindent
33388 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
33389 file. You can specify an alternate preprocessor (usually named
33390 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
33391 parameter. A list of all possible options may be obtained by entering
33392 the command @code{windres} @option{--help}.
33393
33394 It is also possible to use the Microsoft resource compiler @code{rc.exe}
33395 to produce a @file{.res} file (binary resource file). See the
33396 corresponding Microsoft documentation for further details. In this case
33397 you need to use @code{windres} to translate the @file{.res} file to a
33398 GNAT-compatible object file as follows:
33399
33400 @smallexample
33401 $ windres -i myres.res -o myres.o
33402 @end smallexample
33403
33404 @node Using Resources
33405 @subsection Using Resources
33406 @cindex Resources, using
33407
33408 @noindent
33409 To include the resource file in your program just add the
33410 GNAT-compatible object file for the resource(s) to the linker
33411 arguments. With @command{gnatmake} this is done by using the @option{-largs}
33412 option:
33413
33414 @smallexample
33415 $ gnatmake myprog -largs myres.o
33416 @end smallexample
33417
33418 @node Debugging a DLL
33419 @section Debugging a DLL
33420 @cindex DLL debugging
33421
33422 @menu
33423 * Program and DLL Both Built with GCC/GNAT::
33424 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
33425 @end menu
33426
33427 @noindent
33428 Debugging a DLL is similar to debugging a standard program. But
33429 we have to deal with two different executable parts: the DLL and the
33430 program that uses it. We have the following four possibilities:
33431
33432 @enumerate 1
33433 @item
33434 The program and the DLL are built with @code{GCC/GNAT}.
33435 @item
33436 The program is built with foreign tools and the DLL is built with
33437 @code{GCC/GNAT}.
33438 @item
33439 The program is built with @code{GCC/GNAT} and the DLL is built with
33440 foreign tools.
33441 @item
33442 @end enumerate
33443
33444 @noindent
33445 In this section we address only cases one and two above.
33446 There is no point in trying to debug
33447 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
33448 information in it. To do so you must use a debugger compatible with the
33449 tools suite used to build the DLL.
33450
33451 @node Program and DLL Both Built with GCC/GNAT
33452 @subsection Program and DLL Both Built with GCC/GNAT
33453
33454 @noindent
33455 This is the simplest case. Both the DLL and the program have @code{GDB}
33456 compatible debugging information. It is then possible to break anywhere in
33457 the process. Let's suppose here that the main procedure is named
33458 @code{ada_main} and that in the DLL there is an entry point named
33459 @code{ada_dll}.
33460
33461 @noindent
33462 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
33463 program must have been built with the debugging information (see GNAT -g
33464 switch). Here are the step-by-step instructions for debugging it:
33465
33466 @enumerate 1
33467 @item Launch @code{GDB} on the main program.
33468
33469 @smallexample
33470 $ gdb -nw ada_main
33471 @end smallexample
33472
33473 @item Start the program and stop at the beginning of the main procedure
33474
33475 @smallexample
33476 (gdb) start
33477 @end smallexample
33478
33479 @noindent
33480 This step is required to be able to set a breakpoint inside the DLL. As long
33481 as the program is not run, the DLL is not loaded. This has the
33482 consequence that the DLL debugging information is also not loaded, so it is not
33483 possible to set a breakpoint in the DLL.
33484
33485 @item Set a breakpoint inside the DLL
33486
33487 @smallexample
33488 (gdb) break ada_dll
33489 (gdb) cont
33490 @end smallexample
33491
33492 @end enumerate
33493
33494 @noindent
33495 At this stage a breakpoint is set inside the DLL. From there on
33496 you can use the standard approach to debug the whole program
33497 (@pxref{Running and Debugging Ada Programs}).
33498
33499 @ignore
33500 @c This used to work, probably because the DLLs were non-relocatable
33501 @c keep this section around until the problem is sorted out.
33502
33503 To break on the @code{DllMain} routine it is not possible to follow
33504 the procedure above. At the time the program stop on @code{ada_main}
33505 the @code{DllMain} routine as already been called. Either you can use
33506 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
33507
33508 @enumerate 1
33509 @item Launch @code{GDB} on the main program.
33510
33511 @smallexample
33512 $ gdb ada_main
33513 @end smallexample
33514
33515 @item Load DLL symbols
33516
33517 @smallexample
33518 (gdb) add-sym api.dll
33519 @end smallexample
33520
33521 @item Set a breakpoint inside the DLL
33522
33523 @smallexample
33524 (gdb) break ada_dll.adb:45
33525 @end smallexample
33526
33527 Note that at this point it is not possible to break using the routine symbol
33528 directly as the program is not yet running. The solution is to break
33529 on the proper line (break in @file{ada_dll.adb} line 45).
33530
33531 @item Start the program
33532
33533 @smallexample
33534 (gdb) run
33535 @end smallexample
33536
33537 @end enumerate
33538 @end ignore
33539
33540 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
33541 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
33542
33543 @menu
33544 * Debugging the DLL Directly::
33545 * Attaching to a Running Process::
33546 @end menu
33547
33548 @noindent
33549 In this case things are slightly more complex because it is not possible to
33550 start the main program and then break at the beginning to load the DLL and the
33551 associated DLL debugging information. It is not possible to break at the
33552 beginning of the program because there is no @code{GDB} debugging information,
33553 and therefore there is no direct way of getting initial control. This
33554 section addresses this issue by describing some methods that can be used
33555 to break somewhere in the DLL to debug it.
33556
33557 @noindent
33558 First suppose that the main procedure is named @code{main} (this is for
33559 example some C code built with Microsoft Visual C) and that there is a
33560 DLL named @code{test.dll} containing an Ada entry point named
33561 @code{ada_dll}.
33562
33563 @noindent
33564 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
33565 been built with debugging information (see GNAT -g option).
33566
33567 @node Debugging the DLL Directly
33568 @subsubsection Debugging the DLL Directly
33569
33570 @enumerate 1
33571 @item
33572 Find out the executable starting address
33573
33574 @smallexample
33575 $ objdump --file-header main.exe
33576 @end smallexample
33577
33578 The starting address is reported on the last line. For example:
33579
33580 @smallexample
33581 main.exe:     file format pei-i386
33582 architecture: i386, flags 0x0000010a:
33583 EXEC_P, HAS_DEBUG, D_PAGED
33584 start address 0x00401010
33585 @end smallexample
33586
33587 @item
33588 Launch the debugger on the executable.
33589
33590 @smallexample
33591 $ gdb main.exe
33592 @end smallexample
33593
33594 @item
33595 Set a breakpoint at the starting address, and launch the program.
33596
33597 @smallexample
33598 $ (gdb) break *0x00401010
33599 $ (gdb) run
33600 @end smallexample
33601
33602 The program will stop at the given address.
33603
33604 @item
33605 Set a breakpoint on a DLL subroutine.
33606
33607 @smallexample
33608 (gdb) break ada_dll.adb:45
33609 @end smallexample
33610
33611 Or if you want to break using a symbol on the DLL, you need first to
33612 select the Ada language (language used by the DLL).
33613
33614 @smallexample
33615 (gdb) set language ada
33616 (gdb) break ada_dll
33617 @end smallexample
33618
33619 @item
33620 Continue the program.
33621
33622 @smallexample
33623 (gdb) cont
33624 @end smallexample
33625
33626 @noindent
33627 This will run the program until it reaches the breakpoint that has been
33628 set. From that point you can use the standard way to debug a program
33629 as described in (@pxref{Running and Debugging Ada Programs}).
33630
33631 @end enumerate
33632
33633 @noindent
33634 It is also possible to debug the DLL by attaching to a running process.
33635
33636 @node Attaching to a Running Process
33637 @subsubsection Attaching to a Running Process
33638 @cindex DLL debugging, attach to process
33639
33640 @noindent
33641 With @code{GDB} it is always possible to debug a running process by
33642 attaching to it. It is possible to debug a DLL this way. The limitation
33643 of this approach is that the DLL must run long enough to perform the
33644 attach operation. It may be useful for instance to insert a time wasting
33645 loop in the code of the DLL to meet this criterion.
33646
33647 @enumerate 1
33648
33649 @item Launch the main program @file{main.exe}.
33650
33651 @smallexample
33652 $ main
33653 @end smallexample
33654
33655 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
33656 that the process PID for @file{main.exe} is 208.
33657
33658 @item Launch gdb.
33659
33660 @smallexample
33661 $ gdb
33662 @end smallexample
33663
33664 @item Attach to the running process to be debugged.
33665
33666 @smallexample
33667 (gdb) attach 208
33668 @end smallexample
33669
33670 @item Load the process debugging information.
33671
33672 @smallexample
33673 (gdb) symbol-file main.exe
33674 @end smallexample
33675
33676 @item Break somewhere in the DLL.
33677
33678 @smallexample
33679 (gdb) break ada_dll
33680 @end smallexample
33681
33682 @item Continue process execution.
33683
33684 @smallexample
33685 (gdb) cont
33686 @end smallexample
33687
33688 @end enumerate
33689
33690 @noindent
33691 This last step will resume the process execution, and stop at
33692 the breakpoint we have set. From there you can use the standard
33693 approach to debug a program as described in
33694 (@pxref{Running and Debugging Ada Programs}).
33695
33696 @node Setting Stack Size from gnatlink
33697 @section Setting Stack Size from @command{gnatlink}
33698
33699 @noindent
33700 It is possible to specify the program stack size at link time. On modern
33701 versions of Windows, starting with XP, this is mostly useful to set the size of
33702 the main stack (environment task). The other task stacks are set with pragma
33703 Storage_Size or with the @command{gnatbind -d} command.
33704
33705 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
33706 reserve size of individual tasks, the link-time stack size applies to all
33707 tasks, and pragma Storage_Size has no effect.
33708 In particular, Stack Overflow checks are made against this
33709 link-time specified size.
33710
33711 This setting can be done with
33712 @command{gnatlink} using either:
33713
33714 @itemize @bullet
33715
33716 @item using @option{-Xlinker} linker option
33717
33718 @smallexample
33719 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
33720 @end smallexample
33721
33722 This sets the stack reserve size to 0x10000 bytes and the stack commit
33723 size to 0x1000 bytes.
33724
33725 @item using @option{-Wl} linker option
33726
33727 @smallexample
33728 $ gnatlink hello -Wl,--stack=0x1000000
33729 @end smallexample
33730
33731 This sets the stack reserve size to 0x1000000 bytes. Note that with
33732 @option{-Wl} option it is not possible to set the stack commit size
33733 because the coma is a separator for this option.
33734
33735 @end itemize
33736
33737 @node Setting Heap Size from gnatlink
33738 @section Setting Heap Size from @command{gnatlink}
33739
33740 @noindent
33741 Under Windows systems, it is possible to specify the program heap size from
33742 @command{gnatlink} using either:
33743
33744 @itemize @bullet
33745
33746 @item using @option{-Xlinker} linker option
33747
33748 @smallexample
33749 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
33750 @end smallexample
33751
33752 This sets the heap reserve size to 0x10000 bytes and the heap commit
33753 size to 0x1000 bytes.
33754
33755 @item using @option{-Wl} linker option
33756
33757 @smallexample
33758 $ gnatlink hello -Wl,--heap=0x1000000
33759 @end smallexample
33760
33761 This sets the heap reserve size to 0x1000000 bytes. Note that with
33762 @option{-Wl} option it is not possible to set the heap commit size
33763 because the coma is a separator for this option.
33764
33765 @end itemize
33766
33767 @end ifset
33768
33769 @c **********************************
33770 @c * GNU Free Documentation License *
33771 @c **********************************
33772 @include fdl.texi
33773 @c GNU Free Documentation License
33774
33775 @node Index,,GNU Free Documentation License, Top
33776 @unnumbered Index
33777
33778 @printindex cp
33779
33780 @contents
33781 @c Put table of contents at end, otherwise it precedes the "title page" in
33782 @c the .txt version
33783 @c Edit the pdf file to move the contents to the beginning, after the title
33784 @c page
33785
33786 @bye