b7e4bcf16f3aeac9a32917734268e3a58308123d
[platform/upstream/gcc.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c   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 * Predefined Rules::
494
495 Sample Bodies Using gnatstub
496
497 * Running gnatstub::
498 * Switches for gnatstub::
499
500 Other Utility Programs
501
502 * Using Other Utility Programs with GNAT::
503 * The External Symbol Naming Scheme of GNAT::
504 * Converting Ada Files to html with gnathtml::
505
506 @ifclear vms
507 Code Coverage and Profiling
508
509 * Code Coverage of Ada Programs using gcov::
510 * Profiling an Ada Program using gprof::
511 @end ifclear
512
513 Running and Debugging Ada Programs
514
515 * The GNAT Debugger GDB::
516 * Running GDB::
517 * Introduction to GDB Commands::
518 * Using Ada Expressions::
519 * Calling User-Defined Subprograms::
520 * Using the Next Command in a Function::
521 * Ada Exceptions::
522 * Ada Tasks::
523 * Debugging Generic Units::
524 * GNAT Abnormal Termination or Failure to Terminate::
525 * Naming Conventions for GNAT Source Files::
526 * Getting Internal Debugging Information::
527 * Stack Traceback::
528
529 @ifset vms
530 * LSE::
531 @end ifset
532
533 @ifset vms
534 Compatibility with HP Ada
535
536 * Ada Language Compatibility::
537 * Differences in the Definition of Package System::
538 * Language-Related Features::
539 * The Package STANDARD::
540 * The Package SYSTEM::
541 * Tasking and Task-Related Features::
542 * Pragmas and Pragma-Related Features::
543 * Library of Predefined Units::
544 * Bindings::
545 * Main Program Definition::
546 * Implementation-Defined Attributes::
547 * Compiler and Run-Time Interfacing::
548 * Program Compilation and Library Management::
549 * Input-Output::
550 * Implementation Limits::
551 * Tools and Utilities::
552
553 Language-Related Features
554
555 * Integer Types and Representations::
556 * Floating-Point Types and Representations::
557 * Pragmas Float_Representation and Long_Float::
558 * Fixed-Point Types and Representations::
559 * Record and Array Component Alignment::
560 * Address Clauses::
561 * Other Representation Clauses::
562
563 Tasking and Task-Related Features
564
565 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
566 * Assigning Task IDs::
567 * Task IDs and Delays::
568 * Task-Related Pragmas::
569 * Scheduling and Task Priority::
570 * The Task Stack::
571 * External Interrupts::
572
573 Pragmas and Pragma-Related Features
574
575 * Restrictions on the Pragma INLINE::
576 * Restrictions on the Pragma INTERFACE::
577 * Restrictions on the Pragma SYSTEM_NAME::
578
579 Library of Predefined Units
580
581 * Changes to DECLIB::
582
583 Bindings
584
585 * Shared Libraries and Options Files::
586 * Interfaces to C::
587 @end ifset
588
589 Platform-Specific Information for the Run-Time Libraries
590
591 * Summary of Run-Time Configurations::
592 * Specifying a Run-Time Library::
593 * Choosing the Scheduling Policy::
594 * Solaris-Specific Considerations::
595 * Linux-Specific Considerations::
596 * AIX-Specific Considerations::
597 * Irix-Specific Considerations::
598
599 Example of Binder Output File
600
601 Elaboration Order Handling in GNAT
602
603 * Elaboration Code::
604 * Checking the Elaboration Order::
605 * Controlling the Elaboration Order::
606 * Controlling Elaboration in GNAT - Internal Calls::
607 * Controlling Elaboration in GNAT - External Calls::
608 * Default Behavior in GNAT - Ensuring Safety::
609 * Treatment of Pragma Elaborate::
610 * Elaboration Issues for Library Tasks::
611 * Mixing Elaboration Models::
612 * What to Do If the Default Elaboration Behavior Fails::
613 * Elaboration for Access-to-Subprogram Values::
614 * Summary of Procedures for Elaboration Control::
615 * Other Elaboration Order Considerations::
616
617 Conditional Compilation
618 * Use of Boolean Constants::
619 * Debugging - A Special Case::
620 * Conditionalizing Declarations::
621 * Use of Alternative Implementations::
622 * Preprocessing::
623
624 Inline Assembler
625
626 * Basic Assembler Syntax::
627 * A Simple Example of Inline Assembler::
628 * Output Variables in Inline Assembler::
629 * Input Variables in Inline Assembler::
630 * Inlining Inline Assembler Code::
631 * Other Asm Functionality::
632
633 Compatibility and Porting Guide
634
635 * Compatibility with Ada 83::
636 * Compatibility between Ada 95 and Ada 2005::
637 * Implementation-dependent characteristics::
638 @ifclear vms
639 @c This brief section is only in the non-VMS version
640 @c The complete chapter on HP Ada issues is in the VMS version
641 * Compatibility with HP Ada 83::
642 @end ifclear
643 * Compatibility with Other Ada Systems::
644 * Representation Clauses::
645 @ifset vms
646 * Transitioning to 64-Bit GNAT for OpenVMS::
647 @end ifset
648
649 @ifset unw
650 Microsoft Windows Topics
651
652 * Using GNAT on Windows::
653 * CONSOLE and WINDOWS subsystems::
654 * Temporary Files::
655 * Mixed-Language Programming on Windows::
656 * Windows Calling Conventions::
657 * Introduction to Dynamic Link Libraries (DLLs)::
658 * Using DLLs with GNAT::
659 * Building DLLs with GNAT::
660 * GNAT and Windows Resources::
661 * Debugging a DLL::
662 * Setting Stack Size from gnatlink::
663 * Setting Heap Size from gnatlink::
664 @end ifset
665
666 * Index::
667 @end menu
668 @end ifnottex
669
670 @node About This Guide
671 @unnumbered About This Guide
672
673 @noindent
674 @ifset vms
675 This guide describes the use of @value{EDITION},
676 a compiler and software development toolset for the full Ada
677 programming language, implemented on OpenVMS for HP's Alpha and
678 Integrity server (I64) platforms.
679 @end ifset
680 @ifclear vms
681 This guide describes the use of @value{EDITION},
682 a compiler and software development
683 toolset for the full Ada programming language.
684 @end ifclear
685 It documents the features of the compiler and tools, and explains
686 how to use them to build Ada applications.
687
688 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
689 Ada 83 compatibility mode.
690 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
691 but you can override with a compiler switch
692 (@pxref{Compiling Different Versions of Ada})
693 to explicitly specify the language version.
694 Throughout this manual, references to ``Ada'' without a year suffix
695 apply to both the Ada 95 and Ada 2005 versions of the language.
696
697
698 @ifclear FSFEDITION
699 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
700 ``GNAT'' in the remainder of this document.
701 @end ifclear
702
703
704
705
706 @menu
707 * What This Guide Contains::
708 * What You Should Know before Reading This Guide::
709 * Related Information::
710 * Conventions::
711 @end menu
712
713 @node What This Guide Contains
714 @unnumberedsec What This Guide Contains
715
716 @noindent
717 This guide contains the following chapters:
718 @itemize @bullet
719
720 @item
721 @ref{Getting Started with GNAT}, describes how to get started compiling
722 and running Ada programs with the GNAT Ada programming environment.
723 @item
724 @ref{The GNAT Compilation Model}, describes the compilation model used
725 by GNAT.
726
727 @item
728 @ref{Compiling Using gcc}, describes how to compile
729 Ada programs with @command{gcc}, the Ada compiler.
730
731 @item
732 @ref{Binding Using gnatbind}, describes how to
733 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
734 utility.
735
736 @item
737 @ref{Linking Using gnatlink},
738 describes @command{gnatlink}, a
739 program that provides for linking using the GNAT run-time library to
740 construct a program. @command{gnatlink} can also incorporate foreign language
741 object units into the executable.
742
743 @item
744 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
745 utility that automatically determines the set of sources
746 needed by an Ada compilation unit, and executes the necessary compilations
747 binding and link.
748
749 @item
750 @ref{Improving Performance}, shows various techniques for making your
751 Ada program run faster or take less space.
752 It discusses the effect of the compiler's optimization switch and
753 also describes the @command{gnatelim} tool and unused subprogram/data
754 elimination.
755
756 @item
757 @ref{Renaming Files Using gnatchop}, describes
758 @code{gnatchop}, a utility that allows you to preprocess a file that
759 contains Ada source code, and split it into one or more new files, one
760 for each compilation unit.
761
762 @item
763 @ref{Configuration Pragmas}, describes the configuration pragmas
764 handled by GNAT.
765
766 @item
767 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
768 shows how to override the default GNAT file naming conventions,
769 either for an individual unit or globally.
770
771 @item
772 @ref{GNAT Project Manager}, describes how to use project files
773 to organize large projects.
774
775 @item
776 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
777 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
778 way to navigate through sources.
779
780 @item
781 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
782 version of an Ada source file with control over casing, indentation,
783 comment placement, and other elements of program presentation style.
784
785 @item
786 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
787 metrics for an Ada source file, such as the number of types and subprograms,
788 and assorted complexity measures.
789
790 @item
791 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
792 file name krunching utility, used to handle shortened
793 file names on operating systems with a limit on the length of names.
794
795 @item
796 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
797 preprocessor utility that allows a single source file to be used to
798 generate multiple or parameterized source files by means of macro
799 substitution.
800
801 @ifset vms
802 @item
803 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
804 a tool for rebuilding the GNAT run time with user-supplied
805 configuration pragmas.
806 @end ifset
807
808 @item
809 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
810 utility that displays information about compiled units, including dependences
811 on the corresponding sources files, and consistency of compilations.
812
813 @item
814 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
815 to delete files that are produced by the compiler, binder and linker.
816
817 @ifclear vms
818 @item
819 @ref{GNAT and Libraries}, describes the process of creating and using
820 Libraries with GNAT. It also describes how to recompile the GNAT run-time
821 library.
822
823 @item
824 @ref{Using the GNU make Utility}, describes some techniques for using
825 the GNAT toolset in Makefiles.
826 @end ifclear
827
828 @item
829 @ref{Memory Management Issues}, describes some useful predefined storage pools
830 and in particular the GNAT Debug Pool facility, which helps detect incorrect
831 memory references.
832 @ifclear vms
833 It also describes @command{gnatmem}, a utility that monitors dynamic
834 allocation and deallocation and helps detect ``memory leaks''.
835 @end ifclear
836
837 @item
838 @ref{Stack Related Facilities}, describes some useful tools associated with
839 stack checking and analysis.
840
841 @item
842 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
843 a utility that checks Ada code against a set of rules.
844
845 @item
846 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
847 a utility that generates empty but compilable bodies for library units.
848
849 @item
850 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
851 generate automatically Ada bindings from C and C++ headers.
852
853 @item
854 @ref{Other Utility Programs}, discusses several other GNAT utilities,
855 including @code{gnathtml}.
856
857 @ifclear vms
858 @item
859 @ref{Code Coverage and Profiling}, describes how to perform a structural
860 coverage and profile the execution of Ada programs.
861 @end ifclear
862
863 @item
864 @ref{Running and Debugging Ada Programs}, describes how to run and debug
865 Ada programs.
866
867 @ifset vms
868 @item
869 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
870 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
871 developed by Digital Equipment Corporation and currently supported by HP.}
872 for OpenVMS Alpha. This product was formerly known as DEC Ada,
873 @cindex DEC Ada
874 and for
875 historical compatibility reasons, the relevant libraries still use the
876 DEC prefix.
877 @end ifset
878
879 @item
880 @ref{Platform-Specific Information for the Run-Time Libraries},
881 describes the various run-time
882 libraries supported by GNAT on various platforms and explains how to
883 choose a particular library.
884
885 @item
886 @ref{Example of Binder Output File}, shows the source code for the binder
887 output file for a sample program.
888
889 @item
890 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
891 you deal with elaboration order issues.
892
893 @item
894 @ref{Conditional Compilation}, describes how to model conditional compilation,
895 both with Ada in general and with GNAT facilities in particular.
896
897 @item
898 @ref{Inline Assembler}, shows how to use the inline assembly facility
899 in an Ada program.
900
901 @item
902 @ref{Compatibility and Porting Guide}, contains sections on compatibility
903 of GNAT with other Ada development environments (including Ada 83 systems),
904 to assist in porting code from those environments.
905
906 @ifset unw
907 @item
908 @ref{Microsoft Windows Topics}, presents information relevant to the
909 Microsoft Windows platform.
910 @end ifset
911 @end itemize
912
913 @c *************************************************
914 @node What You Should Know before Reading This Guide
915 @c *************************************************
916 @unnumberedsec What You Should Know before Reading This Guide
917
918 @cindex Ada 95 Language Reference Manual
919 @cindex Ada 2005 Language Reference Manual
920 @noindent
921 This guide assumes a basic familiarity with the Ada 95 language, as
922 described in the International Standard ANSI/ISO/IEC-8652:1995, January
923 1995.
924 It does not require knowledge of the new features introduced by Ada 2005,
925 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
926 and Amendment 1).
927 Both reference manuals are included in the GNAT documentation
928 package.
929
930 @node Related Information
931 @unnumberedsec Related Information
932
933 @noindent
934 For further information about related tools, refer to the following
935 documents:
936
937 @itemize @bullet
938 @item
939 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
940 Reference Manual}, which contains all reference material for the GNAT
941 implementation of Ada.
942
943 @ifset unw
944 @item
945 @cite{Using the GNAT Programming Studio}, which describes the GPS
946 Integrated Development Environment.
947
948 @item
949 @cite{GNAT Programming Studio Tutorial}, which introduces the
950 main GPS features through examples.
951 @end ifset
952
953 @item
954 @cite{Ada 95 Reference Manual}, which contains reference
955 material for the Ada 95 programming language.
956
957 @item
958 @cite{Ada 2005 Reference Manual}, which contains reference
959 material for the Ada 2005 programming language.
960
961 @item
962 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
963 @ifset vms
964 in the GNU:[DOCS] directory,
965 @end ifset
966 for all details on the use of the GNU source-level debugger.
967
968 @item
969 @xref{Top,, The extensible self-documenting text editor, emacs,
970 GNU Emacs Manual},
971 @ifset vms
972 located in the GNU:[DOCS] directory if the EMACS kit is installed,
973 @end ifset
974 for full information on the extensible editor and programming
975 environment Emacs.
976
977 @end itemize
978
979 @c **************
980 @node Conventions
981 @unnumberedsec Conventions
982 @cindex Conventions
983 @cindex Typographical conventions
984
985 @noindent
986 Following are examples of the typographical and graphic conventions used
987 in this guide:
988
989 @itemize @bullet
990 @item
991 @code{Functions}, @command{utility program names}, @code{standard names},
992 and @code{classes}.
993
994 @item
995 @option{Option flags}
996
997 @item
998 @file{File names}, @samp{button names}, and @samp{field names}.
999
1000 @item
1001 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1002 variables}.
1003
1004 @item
1005 @emph{Emphasis}.
1006
1007 @item
1008 @r{[}optional information or parameters@r{]}
1009
1010 @item
1011 Examples are described by text
1012 @smallexample
1013 and then shown this way.
1014 @end smallexample
1015 @end itemize
1016
1017 @noindent
1018 Commands that are entered by the user are preceded in this manual by the
1019 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1020 uses this sequence as a prompt, then the commands will appear exactly as
1021 you see them in the manual. If your system uses some other prompt, then
1022 the command will appear with the @code{$} replaced by whatever prompt
1023 character you are using.
1024
1025 @ifset unw
1026 Full file names are shown with the ``@code{/}'' character
1027 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1028 If you are using GNAT on a Windows platform, please note that
1029 the ``@code{\}'' character should be used instead.
1030 @end ifset
1031
1032 @c ****************************
1033 @node Getting Started with GNAT
1034 @chapter Getting Started with GNAT
1035
1036 @noindent
1037 This chapter describes some simple ways of using GNAT to build
1038 executable Ada programs.
1039 @ifset unw
1040 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1041 show how to use the command line environment.
1042 @ref{Introduction to GPS}, provides a brief
1043 introduction to the GNAT Programming Studio, a visually-oriented
1044 Integrated Development Environment for GNAT.
1045 GPS offers a graphical ``look and feel'', support for development in
1046 other programming languages, comprehensive browsing features, and
1047 many other capabilities.
1048 For information on GPS please refer to
1049 @cite{Using the GNAT Programming Studio}.
1050 @end ifset
1051
1052 @menu
1053 * Running GNAT::
1054 * Running a Simple Ada Program::
1055 * Running a Program with Multiple Units::
1056 * Using the gnatmake Utility::
1057 @ifset vms
1058 * Editing with Emacs::
1059 @end ifset
1060 @ifclear vms
1061 * Introduction to GPS::
1062 @end ifclear
1063 @end menu
1064
1065 @node Running GNAT
1066 @section Running GNAT
1067
1068 @noindent
1069 Three steps are needed to create an executable file from an Ada source
1070 file:
1071
1072 @enumerate
1073 @item
1074 The source file(s) must be compiled.
1075 @item
1076 The file(s) must be bound using the GNAT binder.
1077 @item
1078 All appropriate object files must be linked to produce an executable.
1079 @end enumerate
1080
1081 @noindent
1082 All three steps are most commonly handled by using the @command{gnatmake}
1083 utility program that, given the name of the main program, automatically
1084 performs the necessary compilation, binding and linking steps.
1085
1086 @node Running a Simple Ada Program
1087 @section Running a Simple Ada Program
1088
1089 @noindent
1090 Any text editor may be used to prepare an Ada program.
1091 (If @code{Emacs} is
1092 used, the optional Ada mode may be helpful in laying out the program.)
1093 The
1094 program text is a normal text file. We will assume in our initial
1095 example that you have used your editor to prepare the following
1096 standard format text file:
1097
1098 @smallexample @c ada
1099 @cartouche
1100 with Ada.Text_IO; use Ada.Text_IO;
1101 procedure Hello is
1102 begin
1103    Put_Line ("Hello WORLD!");
1104 end Hello;
1105 @end cartouche
1106 @end smallexample
1107
1108 @noindent
1109 This file should be named @file{hello.adb}.
1110 With the normal default file naming conventions, GNAT requires
1111 that each file
1112 contain a single compilation unit whose file name is the
1113 unit name,
1114 with periods replaced by hyphens; the
1115 extension is @file{ads} for a
1116 spec and @file{adb} for a body.
1117 You can override this default file naming convention by use of the
1118 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1119 Alternatively, if you want to rename your files according to this default
1120 convention, which is probably more convenient if you will be using GNAT
1121 for all your compilations, then the @code{gnatchop} utility
1122 can be used to generate correctly-named source files
1123 (@pxref{Renaming Files Using gnatchop}).
1124
1125 You can compile the program using the following command (@code{$} is used
1126 as the command prompt in the examples in this document):
1127
1128 @smallexample
1129 $ gcc -c hello.adb
1130 @end smallexample
1131
1132 @noindent
1133 @command{gcc} is the command used to run the compiler. This compiler is
1134 capable of compiling programs in several languages, including Ada and
1135 C. It assumes that you have given it an Ada program if the file extension is
1136 either @file{.ads} or @file{.adb}, and it will then call
1137 the GNAT compiler to compile the specified file.
1138
1139 @ifclear vms
1140 The @option{-c} switch is required. It tells @command{gcc} to only do a
1141 compilation. (For C programs, @command{gcc} can also do linking, but this
1142 capability is not used directly for Ada programs, so the @option{-c}
1143 switch must always be present.)
1144 @end ifclear
1145
1146 This compile command generates a file
1147 @file{hello.o}, which is the object
1148 file corresponding to your Ada program. It also generates
1149 an ``Ada Library Information'' file @file{hello.ali},
1150 which contains additional information used to check
1151 that an Ada program is consistent.
1152 To build an executable file,
1153 use @code{gnatbind} to bind the program
1154 and @command{gnatlink} to link it. The
1155 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1156 @file{ALI} file, but the default extension of @file{.ali} can
1157 be omitted. This means that in the most common case, the argument
1158 is simply the name of the main program:
1159
1160 @smallexample
1161 $ gnatbind hello
1162 $ gnatlink hello
1163 @end smallexample
1164
1165 @noindent
1166 A simpler method of carrying out these steps is to use
1167 @command{gnatmake},
1168 a master program that invokes all the required
1169 compilation, binding and linking tools in the correct order. In particular,
1170 @command{gnatmake} automatically recompiles any sources that have been
1171 modified since they were last compiled, or sources that depend
1172 on such modified sources, so that ``version skew'' is avoided.
1173 @cindex Version skew (avoided by @command{gnatmake})
1174
1175 @smallexample
1176 $ gnatmake hello.adb
1177 @end smallexample
1178
1179 @noindent
1180 The result is an executable program called @file{hello}, which can be
1181 run by entering:
1182
1183 @smallexample
1184 $ ^hello^RUN HELLO^
1185 @end smallexample
1186
1187 @noindent
1188 assuming that the current directory is on the search path
1189 for executable programs.
1190
1191 @noindent
1192 and, if all has gone well, you will see
1193
1194 @smallexample
1195 Hello WORLD!
1196 @end smallexample
1197
1198 @noindent
1199 appear in response to this command.
1200
1201 @c ****************************************
1202 @node Running a Program with Multiple Units
1203 @section Running a Program with Multiple Units
1204
1205 @noindent
1206 Consider a slightly more complicated example that has three files: a
1207 main program, and the spec and body of a package:
1208
1209 @smallexample @c ada
1210 @cartouche
1211 @group
1212 package Greetings is
1213    procedure Hello;
1214    procedure Goodbye;
1215 end Greetings;
1216
1217 with Ada.Text_IO; use Ada.Text_IO;
1218 package body Greetings is
1219    procedure Hello is
1220    begin
1221       Put_Line ("Hello WORLD!");
1222    end Hello;
1223
1224    procedure Goodbye is
1225    begin
1226       Put_Line ("Goodbye WORLD!");
1227    end Goodbye;
1228 end Greetings;
1229 @end group
1230
1231 @group
1232 with Greetings;
1233 procedure Gmain is
1234 begin
1235    Greetings.Hello;
1236    Greetings.Goodbye;
1237 end Gmain;
1238 @end group
1239 @end cartouche
1240 @end smallexample
1241
1242 @noindent
1243 Following the one-unit-per-file rule, place this program in the
1244 following three separate files:
1245
1246 @table @file
1247 @item greetings.ads
1248 spec of package @code{Greetings}
1249
1250 @item greetings.adb
1251 body of package @code{Greetings}
1252
1253 @item gmain.adb
1254 body of main program
1255 @end table
1256
1257 @noindent
1258 To build an executable version of
1259 this program, we could use four separate steps to compile, bind, and link
1260 the program, as follows:
1261
1262 @smallexample
1263 $ gcc -c gmain.adb
1264 $ gcc -c greetings.adb
1265 $ gnatbind gmain
1266 $ gnatlink gmain
1267 @end smallexample
1268
1269 @noindent
1270 Note that there is no required order of compilation when using GNAT.
1271 In particular it is perfectly fine to compile the main program first.
1272 Also, it is not necessary to compile package specs in the case where
1273 there is an accompanying body; you only need to compile the body. If you want
1274 to submit these files to the compiler for semantic checking and not code
1275 generation, then use the
1276 @option{-gnatc} switch:
1277
1278 @smallexample
1279 $ gcc -c greetings.ads -gnatc
1280 @end smallexample
1281
1282 @noindent
1283 Although the compilation can be done in separate steps as in the
1284 above example, in practice it is almost always more convenient
1285 to use the @command{gnatmake} tool. All you need to know in this case
1286 is the name of the main program's source file. The effect of the above four
1287 commands can be achieved with a single one:
1288
1289 @smallexample
1290 $ gnatmake gmain.adb
1291 @end smallexample
1292
1293 @noindent
1294 In the next section we discuss the advantages of using @command{gnatmake} in
1295 more detail.
1296
1297 @c *****************************
1298 @node Using the gnatmake Utility
1299 @section Using the @command{gnatmake} Utility
1300
1301 @noindent
1302 If you work on a program by compiling single components at a time using
1303 @command{gcc}, you typically keep track of the units you modify. In order to
1304 build a consistent system, you compile not only these units, but also any
1305 units that depend on the units you have modified.
1306 For example, in the preceding case,
1307 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1308 you edit @file{greetings.ads}, you must recompile both
1309 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1310 units that depend on @file{greetings.ads}.
1311
1312 @code{gnatbind} will warn you if you forget one of these compilation
1313 steps, so that it is impossible to generate an inconsistent program as a
1314 result of forgetting to do a compilation. Nevertheless it is tedious and
1315 error-prone to keep track of dependencies among units.
1316 One approach to handle the dependency-bookkeeping is to use a
1317 makefile. However, makefiles present maintenance problems of their own:
1318 if the dependencies change as you change the program, you must make
1319 sure that the makefile is kept up-to-date manually, which is also an
1320 error-prone process.
1321
1322 The @command{gnatmake} utility takes care of these details automatically.
1323 Invoke it using either one of the following forms:
1324
1325 @smallexample
1326 $ gnatmake gmain.adb
1327 $ gnatmake ^gmain^GMAIN^
1328 @end smallexample
1329
1330 @noindent
1331 The argument is the name of the file containing the main program;
1332 you may omit the extension. @command{gnatmake}
1333 examines the environment, automatically recompiles any files that need
1334 recompiling, and binds and links the resulting set of object files,
1335 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1336 In a large program, it
1337 can be extremely helpful to use @command{gnatmake}, because working out by hand
1338 what needs to be recompiled can be difficult.
1339
1340 Note that @command{gnatmake}
1341 takes into account all the Ada rules that
1342 establish dependencies among units. These include dependencies that result
1343 from inlining subprogram bodies, and from
1344 generic instantiation. Unlike some other
1345 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1346 found by the compiler on a previous compilation, which may possibly
1347 be wrong when sources change. @command{gnatmake} determines the exact set of
1348 dependencies from scratch each time it is run.
1349
1350 @ifset vms
1351 @node Editing with Emacs
1352 @section Editing with Emacs
1353 @cindex Emacs
1354
1355 @noindent
1356 Emacs is an extensible self-documenting text editor that is available in a
1357 separate VMSINSTAL kit.
1358
1359 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1360 click on the Emacs Help menu and run the Emacs Tutorial.
1361 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1362 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1363
1364 Documentation on Emacs and other tools is available in Emacs under the
1365 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1366 use the middle mouse button to select a topic (e.g.@: Emacs).
1367
1368 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1369 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1370 get to the Emacs manual.
1371 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1372 prompt.
1373
1374 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1375 which is sufficiently extensible to provide for a complete programming
1376 environment and shell for the sophisticated user.
1377 @end ifset
1378
1379 @ifclear vms
1380 @node Introduction to GPS
1381 @section Introduction to GPS
1382 @cindex GPS (GNAT Programming Studio)
1383 @cindex GNAT Programming Studio (GPS)
1384 @noindent
1385 Although the command line interface (@command{gnatmake}, etc.) alone
1386 is sufficient, a graphical Interactive Development
1387 Environment can make it easier for you to compose, navigate, and debug
1388 programs.  This section describes the main features of GPS
1389 (``GNAT Programming Studio''), the GNAT graphical IDE.
1390 You will see how to use GPS to build and debug an executable, and
1391 you will also learn some of the basics of the GNAT ``project'' facility.
1392
1393 GPS enables you to do much more than is presented here;
1394 e.g., you can produce a call graph, interface to a third-party
1395 Version Control System, and inspect the generated assembly language
1396 for a program.
1397 Indeed, GPS also supports languages other than Ada.
1398 Such additional information, and an explanation of all of the GPS menu
1399 items. may be found in the on-line help, which includes
1400 a user's guide and a tutorial (these are also accessible from the GNAT
1401 startup menu).
1402
1403 @menu
1404 * Building a New Program with GPS::
1405 * Simple Debugging with GPS::
1406 @end menu
1407
1408 @node Building a New Program with GPS
1409 @subsection Building a New Program with GPS
1410 @noindent
1411 GPS invokes the GNAT compilation tools using information
1412 contained in a @emph{project} (also known as a @emph{project file}):
1413 a collection of properties such
1414 as source directories, identities of main subprograms, tool switches, etc.,
1415 and their associated values.
1416 See @ref{GNAT Project Manager} for details.
1417 In order to run GPS, you will need to either create a new project
1418 or else open an existing one.
1419
1420 This section will explain how you can use GPS to create a project,
1421 to associate Ada source files with a project, and to build and run
1422 programs.
1423
1424 @enumerate
1425 @item @emph{Creating a project}
1426
1427 Invoke GPS, either from the command line or the platform's IDE.
1428 After it starts, GPS will display a ``Welcome'' screen with three
1429 radio buttons:
1430
1431 @itemize @bullet
1432 @item
1433 @code{Start with default project in directory}
1434
1435 @item
1436 @code{Create new project with wizard}
1437
1438 @item
1439 @code{Open existing project}
1440 @end itemize
1441
1442 @noindent
1443 Select @code{Create new project with wizard} and press @code{OK}.
1444 A new window will appear.  In the text box labeled with
1445 @code{Enter the name of the project to create}, type @file{sample}
1446 as the project name.
1447 In the next box, browse to choose the directory in which you
1448 would like to create the project file.
1449 After selecting an appropriate directory, press @code{Forward}.
1450
1451 A window will appear with the title
1452 @code{Version Control System Configuration}.
1453 Simply press @code{Forward}.
1454
1455 A window will appear with the title
1456 @code{Please select the source directories for this project}.
1457 The directory that you specified for the project file will be selected
1458 by default as the one to use for sources; simply press @code{Forward}.
1459
1460 A window will appear with the title
1461 @code{Please select the build directory for this project}.
1462 The directory that you specified for the project file will be selected
1463 by default for object files and executables;
1464 simply press @code{Forward}.
1465
1466 A window will appear with the title
1467 @code{Please select the main units for this project}.
1468 You will supply this information later, after creating the source file.
1469 Simply press @code{Forward} for now.
1470
1471 A window will appear with the title
1472 @code{Please select the switches to build the project}.
1473 Press @code{Apply}.  This will create a project file named
1474 @file{sample.prj} in the directory that you had specified.
1475
1476 @item @emph{Creating and saving the source file}
1477
1478 After you create the new project, a GPS window will appear, which is
1479 partitioned into two main sections:
1480
1481 @itemize @bullet
1482 @item
1483 A @emph{Workspace area}, initially greyed out, which you will use for
1484 creating and editing source files
1485
1486 @item
1487 Directly below, a @emph{Messages area}, which initially displays a
1488 ``Welcome'' message.
1489 (If the Messages area is not visible, drag its border upward to expand it.)
1490 @end itemize
1491
1492 @noindent
1493 Select @code{File} on the menu bar, and then the @code{New} command.
1494 The Workspace area will become white, and you can now
1495 enter the source program explicitly.
1496 Type the following text
1497
1498 @smallexample @c ada
1499 @group
1500 with Ada.Text_IO; use Ada.Text_IO;
1501 procedure Hello is
1502 begin
1503   Put_Line("Hello from GPS!");
1504 end Hello;
1505 @end group
1506 @end smallexample
1507
1508 @noindent
1509 Select @code{File}, then @code{Save As}, and enter the source file name
1510 @file{hello.adb}.
1511 The file will be saved in the same directory you specified as the
1512 location of the default project file.
1513
1514 @item @emph{Updating the project file}
1515
1516 You need to add the new source file to the project.
1517 To do this, select
1518 the @code{Project} menu and then @code{Edit project properties}.
1519 Click the @code{Main files} tab on the left, and then the
1520 @code{Add} button.
1521 Choose @file{hello.adb} from the list, and press @code{Open}.
1522 The project settings window will reflect this action.
1523 Click @code{OK}.
1524
1525 @item @emph{Building and running the program}
1526
1527 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1528 and select @file{hello.adb}.
1529 The Messages window will display the resulting invocations of @command{gcc},
1530 @command{gnatbind}, and @command{gnatlink}
1531 (reflecting the default switch settings from the
1532 project file that you created) and then a ``successful compilation/build''
1533 message.
1534
1535 To run the program, choose the @code{Build} menu, then @code{Run}, and
1536 select @command{hello}.
1537 An @emph{Arguments Selection} window will appear.
1538 There are no command line arguments, so just click @code{OK}.
1539
1540 The Messages window will now display the program's output (the string
1541 @code{Hello from GPS}), and at the bottom of the GPS window a status
1542 update is displayed (@code{Run: hello}).
1543 Close the GPS window (or select @code{File}, then @code{Exit}) to
1544 terminate this GPS session.
1545 @end enumerate
1546
1547 @node Simple Debugging with GPS
1548 @subsection Simple Debugging with GPS
1549 @noindent
1550 This section illustrates basic debugging techniques (setting breakpoints,
1551 examining/modifying variables, single stepping).
1552
1553 @enumerate
1554 @item @emph{Opening a project}
1555
1556 Start GPS and select @code{Open existing project}; browse to
1557 specify the project file @file{sample.prj} that you had created in the
1558 earlier example.
1559
1560 @item @emph{Creating a source file}
1561
1562 Select @code{File}, then @code{New}, and type in the following program:
1563
1564 @smallexample @c ada
1565 @group
1566 with Ada.Text_IO; use Ada.Text_IO;
1567 procedure Example is
1568    Line : String (1..80);
1569    N    : Natural;
1570 begin
1571    Put_Line("Type a line of text at each prompt; an empty line to exit");
1572    loop
1573       Put(": ");
1574       Get_Line (Line, N);
1575       Put_Line (Line (1..N) );
1576       exit when N=0;
1577    end loop;
1578 end Example;
1579 @end group
1580 @end smallexample
1581
1582 @noindent
1583 Select @code{File}, then @code{Save as}, and enter the file name
1584 @file{example.adb}.
1585
1586 @item @emph{Updating the project file}
1587
1588 Add @code{Example} as a new main unit for the project:
1589 @enumerate a
1590 @item
1591 Select @code{Project}, then @code{Edit Project Properties}.
1592
1593 @item
1594 Select the @code{Main files} tab, click @code{Add}, then
1595 select the file @file{example.adb} from the list, and
1596 click @code{Open}.
1597 You will see the file name appear in the list of main units
1598
1599 @item
1600 Click @code{OK}
1601 @end enumerate
1602
1603 @item @emph{Building/running the executable}
1604
1605 To build the executable
1606 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1607
1608 Run the program to see its effect (in the Messages area).
1609 Each line that you enter is displayed; an empty line will
1610 cause the loop to exit and the program to terminate.
1611
1612 @item @emph{Debugging the program}
1613
1614 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1615 which are required for debugging, are on by default when you create
1616 a new project.
1617 Thus unless you intentionally remove these settings, you will be able
1618 to debug any program that you develop using GPS.
1619
1620 @enumerate a
1621 @item @emph{Initializing}
1622
1623 Select @code{Debug}, then @code{Initialize}, then @file{example}
1624
1625 @item @emph{Setting a breakpoint}
1626
1627 After performing the initialization step, you will observe a small
1628 icon to the right of each line number.
1629 This serves as a toggle for breakpoints; clicking the icon will
1630 set a breakpoint at the corresponding line (the icon will change to
1631 a red circle with an ``x''), and clicking it again
1632 will remove the breakpoint / reset the icon.
1633
1634 For purposes of this example, set a breakpoint at line 10 (the
1635 statement @code{Put_Line@ (Line@ (1..N));}
1636
1637 @item @emph{Starting program execution}
1638
1639 Select @code{Debug}, then @code{Run}.  When the
1640 @code{Program Arguments} window appears, click @code{OK}.
1641 A console window will appear; enter some line of text,
1642 e.g.@: @code{abcde}, at the prompt.
1643 The program will pause execution when it gets to the
1644 breakpoint, and the corresponding line is highlighted.
1645
1646 @item @emph{Examining a variable}
1647
1648 Move the mouse over one of the occurrences of the variable @code{N}.
1649 You will see the value (5) displayed, in ``tool tip'' fashion.
1650 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1651 You will see information about @code{N} appear in the @code{Debugger Data}
1652 pane, showing the value as 5.
1653
1654 @item @emph{Assigning a new value to a variable}
1655
1656 Right click on the @code{N} in the @code{Debugger Data} pane, and
1657 select @code{Set value of N}.
1658 When the input window appears, enter the value @code{4} and click
1659 @code{OK}.
1660 This value does not automatically appear in the @code{Debugger Data}
1661 pane; to see it, right click again on the @code{N} in the
1662 @code{Debugger Data} pane and select @code{Update value}.
1663 The new value, 4, will appear in red.
1664
1665 @item @emph{Single stepping}
1666
1667 Select @code{Debug}, then @code{Next}.
1668 This will cause the next statement to be executed, in this case the
1669 call of @code{Put_Line} with the string slice.
1670 Notice in the console window that the displayed string is simply
1671 @code{abcd} and not @code{abcde} which you had entered.
1672 This is because the upper bound of the slice is now 4 rather than 5.
1673
1674 @item @emph{Removing a breakpoint}
1675
1676 Toggle the breakpoint icon at line 10.
1677
1678 @item @emph{Resuming execution from a breakpoint}
1679
1680 Select @code{Debug}, then @code{Continue}.
1681 The program will reach the next iteration of the loop, and
1682 wait for input after displaying the prompt.
1683 This time, just hit the @kbd{Enter} key.
1684 The value of @code{N} will be 0, and the program will terminate.
1685 The console window will disappear.
1686 @end enumerate
1687 @end enumerate
1688 @end ifclear
1689
1690 @node The GNAT Compilation Model
1691 @chapter The GNAT Compilation Model
1692 @cindex GNAT compilation model
1693 @cindex Compilation model
1694
1695 @menu
1696 * Source Representation::
1697 * Foreign Language Representation::
1698 * File Naming Rules::
1699 * Using Other File Names::
1700 * Alternative File Naming Schemes::
1701 * Generating Object Files::
1702 * Source Dependencies::
1703 * The Ada Library Information Files::
1704 * Binding an Ada Program::
1705 * Mixed Language Programming::
1706 @ifclear vms
1707 * Building Mixed Ada & C++ Programs::
1708 * Comparison between GNAT and C/C++ Compilation Models::
1709 @end ifclear
1710 * Comparison between GNAT and Conventional Ada Library Models::
1711 @ifset vms
1712 * Placement of temporary files::
1713 @end ifset
1714 @end menu
1715
1716 @noindent
1717 This chapter describes the compilation model used by GNAT. Although
1718 similar to that used by other languages, such as C and C++, this model
1719 is substantially different from the traditional Ada compilation models,
1720 which are based on a library. The model is initially described without
1721 reference to the library-based model. If you have not previously used an
1722 Ada compiler, you need only read the first part of this chapter. The
1723 last section describes and discusses the differences between the GNAT
1724 model and the traditional Ada compiler models. If you have used other
1725 Ada compilers, this section will help you to understand those
1726 differences, and the advantages of the GNAT model.
1727
1728 @node Source Representation
1729 @section Source Representation
1730 @cindex Latin-1
1731
1732 @noindent
1733 Ada source programs are represented in standard text files, using
1734 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1735 7-bit ASCII set, plus additional characters used for
1736 representing foreign languages (@pxref{Foreign Language Representation}
1737 for support of non-USA character sets). The format effector characters
1738 are represented using their standard ASCII encodings, as follows:
1739
1740 @table @code
1741 @item VT
1742 @findex VT
1743 Vertical tab, @code{16#0B#}
1744
1745 @item HT
1746 @findex HT
1747 Horizontal tab, @code{16#09#}
1748
1749 @item CR
1750 @findex CR
1751 Carriage return, @code{16#0D#}
1752
1753 @item LF
1754 @findex LF
1755 Line feed, @code{16#0A#}
1756
1757 @item FF
1758 @findex FF
1759 Form feed, @code{16#0C#}
1760 @end table
1761
1762 @noindent
1763 Source files are in standard text file format. In addition, GNAT will
1764 recognize a wide variety of stream formats, in which the end of
1765 physical lines is marked by any of the following sequences:
1766 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1767 in accommodating files that are imported from other operating systems.
1768
1769 @cindex End of source file
1770 @cindex Source file, end
1771 @findex SUB
1772 The end of a source file is normally represented by the physical end of
1773 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1774 recognized as signalling the end of the source file. Again, this is
1775 provided for compatibility with other operating systems where this
1776 code is used to represent the end of file.
1777
1778 Each file contains a single Ada compilation unit, including any pragmas
1779 associated with the unit. For example, this means you must place a
1780 package declaration (a package @dfn{spec}) and the corresponding body in
1781 separate files. An Ada @dfn{compilation} (which is a sequence of
1782 compilation units) is represented using a sequence of files. Similarly,
1783 you will place each subunit or child unit in a separate file.
1784
1785 @node Foreign Language Representation
1786 @section Foreign Language Representation
1787
1788 @noindent
1789 GNAT supports the standard character sets defined in Ada as well as
1790 several other non-standard character sets for use in localized versions
1791 of the compiler (@pxref{Character Set Control}).
1792 @menu
1793 * Latin-1::
1794 * Other 8-Bit Codes::
1795 * Wide Character Encodings::
1796 @end menu
1797
1798 @node Latin-1
1799 @subsection Latin-1
1800 @cindex Latin-1
1801
1802 @noindent
1803 The basic character set is Latin-1. This character set is defined by ISO
1804 standard 8859, part 1. The lower half (character codes @code{16#00#}
1805 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1806 is used to represent additional characters. These include extended letters
1807 used by European languages, such as French accents, the vowels with umlauts
1808 used in German, and the extra letter A-ring used in Swedish.
1809
1810 @findex Ada.Characters.Latin_1
1811 For a complete list of Latin-1 codes and their encodings, see the source
1812 file of library unit @code{Ada.Characters.Latin_1} in file
1813 @file{a-chlat1.ads}.
1814 You may use any of these extended characters freely in character or
1815 string literals. In addition, the extended characters that represent
1816 letters can be used in identifiers.
1817
1818 @node Other 8-Bit Codes
1819 @subsection Other 8-Bit Codes
1820
1821 @noindent
1822 GNAT also supports several other 8-bit coding schemes:
1823
1824 @table @asis
1825 @item ISO 8859-2 (Latin-2)
1826 @cindex Latin-2
1827 @cindex ISO 8859-2
1828 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1829 equivalence.
1830
1831 @item ISO 8859-3 (Latin-3)
1832 @cindex Latin-3
1833 @cindex ISO 8859-3
1834 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1835 equivalence.
1836
1837 @item ISO 8859-4 (Latin-4)
1838 @cindex Latin-4
1839 @cindex ISO 8859-4
1840 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1841 equivalence.
1842
1843 @item ISO 8859-5 (Cyrillic)
1844 @cindex ISO 8859-5
1845 @cindex Cyrillic
1846 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1847 lowercase equivalence.
1848
1849 @item ISO 8859-15 (Latin-9)
1850 @cindex ISO 8859-15
1851 @cindex Latin-9
1852 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1853 lowercase equivalence
1854
1855 @item IBM PC (code page 437)
1856 @cindex code page 437
1857 This code page is the normal default for PCs in the U.S. It corresponds
1858 to the original IBM PC character set. This set has some, but not all, of
1859 the extended Latin-1 letters, but these letters do not have the same
1860 encoding as Latin-1. In this mode, these letters are allowed in
1861 identifiers with uppercase and lowercase equivalence.
1862
1863 @item IBM PC (code page 850)
1864 @cindex code page 850
1865 This code page is a modification of 437 extended to include all the
1866 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1867 mode, all these letters are allowed in identifiers with uppercase and
1868 lowercase equivalence.
1869
1870 @item Full Upper 8-bit
1871 Any character in the range 80-FF allowed in identifiers, and all are
1872 considered distinct. In other words, there are no uppercase and lowercase
1873 equivalences in this range. This is useful in conjunction with
1874 certain encoding schemes used for some foreign character sets (e.g.,
1875 the typical method of representing Chinese characters on the PC).
1876
1877 @item No Upper-Half
1878 No upper-half characters in the range 80-FF are allowed in identifiers.
1879 This gives Ada 83 compatibility for identifier names.
1880 @end table
1881
1882 @noindent
1883 For precise data on the encodings permitted, and the uppercase and lowercase
1884 equivalences that are recognized, see the file @file{csets.adb} in
1885 the GNAT compiler sources. You will need to obtain a full source release
1886 of GNAT to obtain this file.
1887
1888 @node Wide Character Encodings
1889 @subsection Wide Character Encodings
1890
1891 @noindent
1892 GNAT allows wide character codes to appear in character and string
1893 literals, and also optionally in identifiers, by means of the following
1894 possible encoding schemes:
1895
1896 @table @asis
1897
1898 @item Hex Coding
1899 In this encoding, a wide character is represented by the following five
1900 character sequence:
1901
1902 @smallexample
1903 ESC a b c d
1904 @end smallexample
1905
1906 @noindent
1907 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1908 characters (using uppercase letters) of the wide character code. For
1909 example, ESC A345 is used to represent the wide character with code
1910 @code{16#A345#}.
1911 This scheme is compatible with use of the full Wide_Character set.
1912
1913 @item Upper-Half Coding
1914 @cindex Upper-Half Coding
1915 The wide character with encoding @code{16#abcd#} where the upper bit is on
1916 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1917 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1918 character, but is not required to be in the upper half. This method can
1919 be also used for shift-JIS or EUC, where the internal coding matches the
1920 external coding.
1921
1922 @item Shift JIS Coding
1923 @cindex Shift JIS Coding
1924 A wide character is represented by a two-character sequence,
1925 @code{16#ab#} and
1926 @code{16#cd#}, with the restrictions described for upper-half encoding as
1927 described above. The internal character code is the corresponding JIS
1928 character according to the standard algorithm for Shift-JIS
1929 conversion. Only characters defined in the JIS code set table can be
1930 used with this encoding method.
1931
1932 @item EUC Coding
1933 @cindex EUC Coding
1934 A wide character is represented by a two-character sequence
1935 @code{16#ab#} and
1936 @code{16#cd#}, with both characters being in the upper half. The internal
1937 character code is the corresponding JIS character according to the EUC
1938 encoding algorithm. Only characters defined in the JIS code set table
1939 can be used with this encoding method.
1940
1941 @item UTF-8 Coding
1942 A wide character is represented using
1943 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1944 10646-1/Am.2. Depending on the character value, the representation
1945 is a one, two, or three byte sequence:
1946 @smallexample
1947 @iftex
1948 @leftskip=.7cm
1949 @end iftex
1950 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1951 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1952 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1953
1954 @end smallexample
1955
1956 @noindent
1957 where the @var{xxx} bits correspond to the left-padded bits of the
1958 16-bit character value. Note that all lower half ASCII characters
1959 are represented as ASCII bytes and all upper half characters and
1960 other wide characters are represented as sequences of upper-half
1961 (The full UTF-8 scheme allows for encoding 31-bit characters as
1962 6-byte sequences, but in this implementation, all UTF-8 sequences
1963 of four or more bytes length will be treated as illegal).
1964 @item Brackets Coding
1965 In this encoding, a wide character is represented by the following eight
1966 character sequence:
1967
1968 @smallexample
1969 [ " a b c d " ]
1970 @end smallexample
1971
1972 @noindent
1973 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1974 characters (using uppercase letters) of the wide character code. For
1975 example, [``A345''] is used to represent the wide character with code
1976 @code{16#A345#}. It is also possible (though not required) to use the
1977 Brackets coding for upper half characters. For example, the code
1978 @code{16#A3#} can be represented as @code{[``A3'']}.
1979
1980 This scheme is compatible with use of the full Wide_Character set,
1981 and is also the method used for wide character encoding in the standard
1982 ACVC (Ada Compiler Validation Capability) test suite distributions.
1983
1984 @end table
1985
1986 @noindent
1987 Note: Some of these coding schemes do not permit the full use of the
1988 Ada character set. For example, neither Shift JIS, nor EUC allow the
1989 use of the upper half of the Latin-1 set.
1990
1991 @node File Naming Rules
1992 @section File Naming Rules
1993
1994 @noindent
1995 The default file name is determined by the name of the unit that the
1996 file contains. The name is formed by taking the full expanded name of
1997 the unit and replacing the separating dots with hyphens and using
1998 ^lowercase^uppercase^ for all letters.
1999
2000 An exception arises if the file name generated by the above rules starts
2001 with one of the characters
2002 @ifset vms
2003 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2004 @end ifset
2005 @ifclear vms
2006 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2007 @end ifclear
2008 and the second character is a
2009 minus. In this case, the character ^tilde^dollar sign^ is used in place
2010 of the minus. The reason for this special rule is to avoid clashes with
2011 the standard names for child units of the packages System, Ada,
2012 Interfaces, and GNAT, which use the prefixes
2013 @ifset vms
2014 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2015 @end ifset
2016 @ifclear vms
2017 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2018 @end ifclear
2019 respectively.
2020
2021 The file extension is @file{.ads} for a spec and
2022 @file{.adb} for a body. The following list shows some
2023 examples of these rules.
2024
2025 @table @file
2026 @item main.ads
2027 Main (spec)
2028 @item main.adb
2029 Main (body)
2030 @item arith_functions.ads
2031 Arith_Functions (package spec)
2032 @item arith_functions.adb
2033 Arith_Functions (package body)
2034 @item func-spec.ads
2035 Func.Spec (child package spec)
2036 @item func-spec.adb
2037 Func.Spec (child package body)
2038 @item main-sub.adb
2039 Sub (subunit of Main)
2040 @item ^a~bad.adb^A$BAD.ADB^
2041 A.Bad (child package body)
2042 @end table
2043
2044 @noindent
2045 Following these rules can result in excessively long
2046 file names if corresponding
2047 unit names are long (for example, if child units or subunits are
2048 heavily nested). An option is available to shorten such long file names
2049 (called file name ``krunching''). This may be particularly useful when
2050 programs being developed with GNAT are to be used on operating systems
2051 with limited file name lengths. @xref{Using gnatkr}.
2052
2053 Of course, no file shortening algorithm can guarantee uniqueness over
2054 all possible unit names; if file name krunching is used, it is your
2055 responsibility to ensure no name clashes occur. Alternatively you
2056 can specify the exact file names that you want used, as described
2057 in the next section. Finally, if your Ada programs are migrating from a
2058 compiler with a different naming convention, you can use the gnatchop
2059 utility to produce source files that follow the GNAT naming conventions.
2060 (For details @pxref{Renaming Files Using gnatchop}.)
2061
2062 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2063 systems, case is not significant. So for example on @code{Windows XP}
2064 if the canonical name is @code{main-sub.adb}, you can use the file name
2065 @code{Main-Sub.adb} instead. However, case is significant for other
2066 operating systems, so for example, if you want to use other than
2067 canonically cased file names on a Unix system, you need to follow
2068 the procedures described in the next section.
2069
2070 @node Using Other File Names
2071 @section Using Other File Names
2072 @cindex File names
2073
2074 @noindent
2075 In the previous section, we have described the default rules used by
2076 GNAT to determine the file name in which a given unit resides. It is
2077 often convenient to follow these default rules, and if you follow them,
2078 the compiler knows without being explicitly told where to find all
2079 the files it needs.
2080
2081 However, in some cases, particularly when a program is imported from
2082 another Ada compiler environment, it may be more convenient for the
2083 programmer to specify which file names contain which units. GNAT allows
2084 arbitrary file names to be used by means of the Source_File_Name pragma.
2085 The form of this pragma is as shown in the following examples:
2086 @cindex Source_File_Name pragma
2087
2088 @smallexample @c ada
2089 @cartouche
2090 pragma Source_File_Name (My_Utilities.Stacks,
2091   Spec_File_Name => "myutilst_a.ada");
2092 pragma Source_File_name (My_Utilities.Stacks,
2093   Body_File_Name => "myutilst.ada");
2094 @end cartouche
2095 @end smallexample
2096
2097 @noindent
2098 As shown in this example, the first argument for the pragma is the unit
2099 name (in this example a child unit). The second argument has the form
2100 of a named association. The identifier
2101 indicates whether the file name is for a spec or a body;
2102 the file name itself is given by a string literal.
2103
2104 The source file name pragma is a configuration pragma, which means that
2105 normally it will be placed in the @file{gnat.adc}
2106 file used to hold configuration
2107 pragmas that apply to a complete compilation environment.
2108 For more details on how the @file{gnat.adc} file is created and used
2109 see @ref{Handling of Configuration Pragmas}.
2110 @cindex @file{gnat.adc}
2111
2112 @ifclear vms
2113 GNAT allows completely arbitrary file names to be specified using the
2114 source file name pragma. However, if the file name specified has an
2115 extension other than @file{.ads} or @file{.adb} it is necessary to use
2116 a special syntax when compiling the file. The name in this case must be
2117 preceded by the special sequence @option{-x} followed by a space and the name
2118 of the language, here @code{ada}, as in:
2119
2120 @smallexample
2121 $ gcc -c -x ada peculiar_file_name.sim
2122 @end smallexample
2123 @end ifclear
2124
2125 @noindent
2126 @command{gnatmake} handles non-standard file names in the usual manner (the
2127 non-standard file name for the main program is simply used as the
2128 argument to gnatmake). Note that if the extension is also non-standard,
2129 then it must be included in the @command{gnatmake} command, it may not
2130 be omitted.
2131
2132 @node Alternative File Naming Schemes
2133 @section Alternative File Naming Schemes
2134 @cindex File naming schemes, alternative
2135 @cindex File names
2136
2137 In the previous section, we described the use of the @code{Source_File_Name}
2138 pragma to allow arbitrary names to be assigned to individual source files.
2139 However, this approach requires one pragma for each file, and especially in
2140 large systems can result in very long @file{gnat.adc} files, and also create
2141 a maintenance problem.
2142
2143 GNAT also provides a facility for specifying systematic file naming schemes
2144 other than the standard default naming scheme previously described. An
2145 alternative scheme for naming is specified by the use of
2146 @code{Source_File_Name} pragmas having the following format:
2147 @cindex Source_File_Name pragma
2148
2149 @smallexample @c ada
2150 pragma Source_File_Name (
2151    Spec_File_Name  => FILE_NAME_PATTERN
2152  @r{[},Casing          => CASING_SPEC@r{]}
2153  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2154
2155 pragma Source_File_Name (
2156    Body_File_Name  => FILE_NAME_PATTERN
2157  @r{[},Casing          => CASING_SPEC@r{]}
2158  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2159
2160 pragma Source_File_Name (
2161    Subunit_File_Name  => FILE_NAME_PATTERN
2162  @r{[},Casing             => CASING_SPEC@r{]}
2163  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2164
2165 FILE_NAME_PATTERN ::= STRING_LITERAL
2166 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2167 @end smallexample
2168
2169 @noindent
2170 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2171 It contains a single asterisk character, and the unit name is substituted
2172 systematically for this asterisk. The optional parameter
2173 @code{Casing} indicates
2174 whether the unit name is to be all upper-case letters, all lower-case letters,
2175 or mixed-case. If no
2176 @code{Casing} parameter is used, then the default is all
2177 ^lower-case^upper-case^.
2178
2179 The optional @code{Dot_Replacement} string is used to replace any periods
2180 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2181 argument is used then separating dots appear unchanged in the resulting
2182 file name.
2183 Although the above syntax indicates that the
2184 @code{Casing} argument must appear
2185 before the @code{Dot_Replacement} argument, but it
2186 is also permissible to write these arguments in the opposite order.
2187
2188 As indicated, it is possible to specify different naming schemes for
2189 bodies, specs, and subunits. Quite often the rule for subunits is the
2190 same as the rule for bodies, in which case, there is no need to give
2191 a separate @code{Subunit_File_Name} rule, and in this case the
2192 @code{Body_File_name} rule is used for subunits as well.
2193
2194 The separate rule for subunits can also be used to implement the rather
2195 unusual case of a compilation environment (e.g.@: a single directory) which
2196 contains a subunit and a child unit with the same unit name. Although
2197 both units cannot appear in the same partition, the Ada Reference Manual
2198 allows (but does not require) the possibility of the two units coexisting
2199 in the same environment.
2200
2201 The file name translation works in the following steps:
2202
2203 @itemize @bullet
2204
2205 @item
2206 If there is a specific @code{Source_File_Name} pragma for the given unit,
2207 then this is always used, and any general pattern rules are ignored.
2208
2209 @item
2210 If there is a pattern type @code{Source_File_Name} pragma that applies to
2211 the unit, then the resulting file name will be used if the file exists. If
2212 more than one pattern matches, the latest one will be tried first, and the
2213 first attempt resulting in a reference to a file that exists will be used.
2214
2215 @item
2216 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2217 for which the corresponding file exists, then the standard GNAT default
2218 naming rules are used.
2219
2220 @end itemize
2221
2222 @noindent
2223 As an example of the use of this mechanism, consider a commonly used scheme
2224 in which file names are all lower case, with separating periods copied
2225 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2226 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2227 two pragmas appear:
2228
2229 @smallexample @c ada
2230 pragma Source_File_Name
2231   (Spec_File_Name => "*.1.ada");
2232 pragma Source_File_Name
2233   (Body_File_Name => "*.2.ada");
2234 @end smallexample
2235
2236 @noindent
2237 The default GNAT scheme is actually implemented by providing the following
2238 default pragmas internally:
2239
2240 @smallexample @c ada
2241 pragma Source_File_Name
2242   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2243 pragma Source_File_Name
2244   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2245 @end smallexample
2246
2247 @noindent
2248 Our final example implements a scheme typically used with one of the
2249 Ada 83 compilers, where the separator character for subunits was ``__''
2250 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2251 by adding @file{.ADA}, and subunits by
2252 adding @file{.SEP}. All file names were
2253 upper case. Child units were not present of course since this was an
2254 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2255 the same double underscore separator for child units.
2256
2257 @smallexample @c ada
2258 pragma Source_File_Name
2259   (Spec_File_Name => "*_.ADA",
2260    Dot_Replacement => "__",
2261    Casing = Uppercase);
2262 pragma Source_File_Name
2263   (Body_File_Name => "*.ADA",
2264    Dot_Replacement => "__",
2265    Casing = Uppercase);
2266 pragma Source_File_Name
2267   (Subunit_File_Name => "*.SEP",
2268    Dot_Replacement => "__",
2269    Casing = Uppercase);
2270 @end smallexample
2271
2272 @node Generating Object Files
2273 @section Generating Object Files
2274
2275 @noindent
2276 An Ada program consists of a set of source files, and the first step in
2277 compiling the program is to generate the corresponding object files.
2278 These are generated by compiling a subset of these source files.
2279 The files you need to compile are the following:
2280
2281 @itemize @bullet
2282 @item
2283 If a package spec has no body, compile the package spec to produce the
2284 object file for the package.
2285
2286 @item
2287 If a package has both a spec and a body, compile the body to produce the
2288 object file for the package. The source file for the package spec need
2289 not be compiled in this case because there is only one object file, which
2290 contains the code for both the spec and body of the package.
2291
2292 @item
2293 For a subprogram, compile the subprogram body to produce the object file
2294 for the subprogram. The spec, if one is present, is as usual in a
2295 separate file, and need not be compiled.
2296
2297 @item
2298 @cindex Subunits
2299 In the case of subunits, only compile the parent unit. A single object
2300 file is generated for the entire subunit tree, which includes all the
2301 subunits.
2302
2303 @item
2304 Compile child units independently of their parent units
2305 (though, of course, the spec of all the ancestor unit must be present in order
2306 to compile a child unit).
2307
2308 @item
2309 @cindex Generics
2310 Compile generic units in the same manner as any other units. The object
2311 files in this case are small dummy files that contain at most the
2312 flag used for elaboration checking. This is because GNAT always handles generic
2313 instantiation by means of macro expansion. However, it is still necessary to
2314 compile generic units, for dependency checking and elaboration purposes.
2315 @end itemize
2316
2317 @noindent
2318 The preceding rules describe the set of files that must be compiled to
2319 generate the object files for a program. Each object file has the same
2320 name as the corresponding source file, except that the extension is
2321 @file{.o} as usual.
2322
2323 You may wish to compile other files for the purpose of checking their
2324 syntactic and semantic correctness. For example, in the case where a
2325 package has a separate spec and body, you would not normally compile the
2326 spec. However, it is convenient in practice to compile the spec to make
2327 sure it is error-free before compiling clients of this spec, because such
2328 compilations will fail if there is an error in the spec.
2329
2330 GNAT provides an option for compiling such files purely for the
2331 purposes of checking correctness; such compilations are not required as
2332 part of the process of building a program. To compile a file in this
2333 checking mode, use the @option{-gnatc} switch.
2334
2335 @node Source Dependencies
2336 @section Source Dependencies
2337
2338 @noindent
2339 A given object file clearly depends on the source file which is compiled
2340 to produce it. Here we are using @dfn{depends} in the sense of a typical
2341 @code{make} utility; in other words, an object file depends on a source
2342 file if changes to the source file require the object file to be
2343 recompiled.
2344 In addition to this basic dependency, a given object may depend on
2345 additional source files as follows:
2346
2347 @itemize @bullet
2348 @item
2349 If a file being compiled @code{with}'s a unit @var{X}, the object file
2350 depends on the file containing the spec of unit @var{X}. This includes
2351 files that are @code{with}'ed implicitly either because they are parents
2352 of @code{with}'ed child units or they are run-time units required by the
2353 language constructs used in a particular unit.
2354
2355 @item
2356 If a file being compiled instantiates a library level generic unit, the
2357 object file depends on both the spec and body files for this generic
2358 unit.
2359
2360 @item
2361 If a file being compiled instantiates a generic unit defined within a
2362 package, the object file depends on the body file for the package as
2363 well as the spec file.
2364
2365 @item
2366 @findex Inline
2367 @cindex @option{-gnatn} switch
2368 If a file being compiled contains a call to a subprogram for which
2369 pragma @code{Inline} applies and inlining is activated with the
2370 @option{-gnatn} switch, the object file depends on the file containing the
2371 body of this subprogram as well as on the file containing the spec. Note
2372 that for inlining to actually occur as a result of the use of this switch,
2373 it is necessary to compile in optimizing mode.
2374
2375 @cindex @option{-gnatN} switch
2376 The use of @option{-gnatN} activates  inlining optimization
2377 that is performed by the front end of the compiler. This inlining does
2378 not require that the code generation be optimized. Like @option{-gnatn},
2379 the use of this switch generates additional dependencies.
2380
2381 When using a gcc-based back end (in practice this means using any version
2382 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2383 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2384 Historically front end inlining was more extensive than the gcc back end
2385 inlining, but that is no longer the case.
2386
2387 @item
2388 If an object file @file{O} depends on the proper body of a subunit through
2389 inlining or instantiation, it depends on the parent unit of the subunit.
2390 This means that any modification of the parent unit or one of its subunits
2391 affects the compilation of @file{O}.
2392
2393 @item
2394 The object file for a parent unit depends on all its subunit body files.
2395
2396 @item
2397 The previous two rules meant that for purposes of computing dependencies and
2398 recompilation, a body and all its subunits are treated as an indivisible whole.
2399
2400 @noindent
2401 These rules are applied transitively: if unit @code{A} @code{with}'s
2402 unit @code{B}, whose elaboration calls an inlined procedure in package
2403 @code{C}, the object file for unit @code{A} will depend on the body of
2404 @code{C}, in file @file{c.adb}.
2405
2406 The set of dependent files described by these rules includes all the
2407 files on which the unit is semantically dependent, as dictated by the
2408 Ada language standard. However, it is a superset of what the
2409 standard describes, because it includes generic, inline, and subunit
2410 dependencies.
2411
2412 An object file must be recreated by recompiling the corresponding source
2413 file if any of the source files on which it depends are modified. For
2414 example, if the @code{make} utility is used to control compilation,
2415 the rule for an Ada object file must mention all the source files on
2416 which the object file depends, according to the above definition.
2417 The determination of the necessary
2418 recompilations is done automatically when one uses @command{gnatmake}.
2419 @end itemize
2420
2421 @node The Ada Library Information Files
2422 @section The Ada Library Information Files
2423 @cindex Ada Library Information files
2424 @cindex @file{ALI} files
2425
2426 @noindent
2427 Each compilation actually generates two output files. The first of these
2428 is the normal object file that has a @file{.o} extension. The second is a
2429 text file containing full dependency information. It has the same
2430 name as the source file, but an @file{.ali} extension.
2431 This file is known as the Ada Library Information (@file{ALI}) file.
2432 The following information is contained in the @file{ALI} file.
2433
2434 @itemize @bullet
2435 @item
2436 Version information (indicates which version of GNAT was used to compile
2437 the unit(s) in question)
2438
2439 @item
2440 Main program information (including priority and time slice settings,
2441 as well as the wide character encoding used during compilation).
2442
2443 @item
2444 List of arguments used in the @command{gcc} command for the compilation
2445
2446 @item
2447 Attributes of the unit, including configuration pragmas used, an indication
2448 of whether the compilation was successful, exception model used etc.
2449
2450 @item
2451 A list of relevant restrictions applying to the unit (used for consistency)
2452 checking.
2453
2454 @item
2455 Categorization information (e.g.@: use of pragma @code{Pure}).
2456
2457 @item
2458 Information on all @code{with}'ed units, including presence of
2459 @code{Elaborate} or @code{Elaborate_All} pragmas.
2460
2461 @item
2462 Information from any @code{Linker_Options} pragmas used in the unit
2463
2464 @item
2465 Information on the use of @code{Body_Version} or @code{Version}
2466 attributes in the unit.
2467
2468 @item
2469 Dependency information. This is a list of files, together with
2470 time stamp and checksum information. These are files on which
2471 the unit depends in the sense that recompilation is required
2472 if any of these units are modified.
2473
2474 @item
2475 Cross-reference data. Contains information on all entities referenced
2476 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2477 provide cross-reference information.
2478
2479 @end itemize
2480
2481 @noindent
2482 For a full detailed description of the format of the @file{ALI} file,
2483 see the source of the body of unit @code{Lib.Writ}, contained in file
2484 @file{lib-writ.adb} in the GNAT compiler sources.
2485
2486 @node Binding an Ada Program
2487 @section Binding an Ada Program
2488
2489 @noindent
2490 When using languages such as C and C++, once the source files have been
2491 compiled the only remaining step in building an executable program
2492 is linking the object modules together. This means that it is possible to
2493 link an inconsistent version of a program, in which two units have
2494 included different versions of the same header.
2495
2496 The rules of Ada do not permit such an inconsistent program to be built.
2497 For example, if two clients have different versions of the same package,
2498 it is illegal to build a program containing these two clients.
2499 These rules are enforced by the GNAT binder, which also determines an
2500 elaboration order consistent with the Ada rules.
2501
2502 The GNAT binder is run after all the object files for a program have
2503 been created. It is given the name of the main program unit, and from
2504 this it determines the set of units required by the program, by reading the
2505 corresponding ALI files. It generates error messages if the program is
2506 inconsistent or if no valid order of elaboration exists.
2507
2508 If no errors are detected, the binder produces a main program, in Ada by
2509 default, that contains calls to the elaboration procedures of those
2510 compilation unit that require them, followed by
2511 a call to the main program. This Ada program is compiled to generate the
2512 object file for the main program. The name of
2513 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2514 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2515 main program unit.
2516
2517 Finally, the linker is used to build the resulting executable program,
2518 using the object from the main program from the bind step as well as the
2519 object files for the Ada units of the program.
2520
2521 @node Mixed Language Programming
2522 @section Mixed Language Programming
2523 @cindex Mixed Language Programming
2524
2525 @noindent
2526 This section describes how to develop a mixed-language program,
2527 specifically one that comprises units in both Ada and C.
2528
2529 @menu
2530 * Interfacing to C::
2531 * Calling Conventions::
2532 @end menu
2533
2534 @node Interfacing to C
2535 @subsection Interfacing to C
2536 @noindent
2537 Interfacing Ada with a foreign language such as C involves using
2538 compiler directives to import and/or export entity definitions in each
2539 language---using @code{extern} statements in C, for instance, and the
2540 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2541 A full treatment of these topics is provided in Appendix B, section 1
2542 of the Ada Reference Manual.
2543
2544 There are two ways to build a program using GNAT that contains some Ada
2545 sources and some foreign language sources, depending on whether or not
2546 the main subprogram is written in Ada.  Here is a source example with
2547 the main subprogram in Ada:
2548
2549 @smallexample
2550 /* file1.c */
2551 #include <stdio.h>
2552
2553 void print_num (int num)
2554 @{
2555   printf ("num is %d.\n", num);
2556   return;
2557 @}
2558
2559 /* file2.c */
2560
2561 /* num_from_Ada is declared in my_main.adb */
2562 extern int num_from_Ada;
2563
2564 int get_num (void)
2565 @{
2566   return num_from_Ada;
2567 @}
2568 @end smallexample
2569
2570 @smallexample @c ada
2571 --  my_main.adb
2572 procedure My_Main is
2573
2574    --  Declare then export an Integer entity called num_from_Ada
2575    My_Num : Integer := 10;
2576    pragma Export (C, My_Num, "num_from_Ada");
2577
2578    --  Declare an Ada function spec for Get_Num, then use
2579    --  C function get_num for the implementation.
2580    function Get_Num return Integer;
2581    pragma Import (C, Get_Num, "get_num");
2582
2583    --  Declare an Ada procedure spec for Print_Num, then use
2584    --  C function print_num for the implementation.
2585    procedure Print_Num (Num : Integer);
2586    pragma Import (C, Print_Num, "print_num");
2587
2588 begin
2589    Print_Num (Get_Num);
2590 end My_Main;
2591 @end smallexample
2592
2593 @enumerate
2594 @item
2595 To build this example, first compile the foreign language files to
2596 generate object files:
2597 @smallexample
2598 ^gcc -c file1.c^gcc -c FILE1.C^
2599 ^gcc -c file2.c^gcc -c FILE2.C^
2600 @end smallexample
2601
2602 @item
2603 Then, compile the Ada units to produce a set of object files and ALI
2604 files:
2605 @smallexample
2606 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2607 @end smallexample
2608
2609 @item
2610 Run the Ada binder on the Ada main program:
2611 @smallexample
2612 gnatbind my_main.ali
2613 @end smallexample
2614
2615 @item
2616 Link the Ada main program, the Ada objects and the other language
2617 objects:
2618 @smallexample
2619 gnatlink my_main.ali file1.o file2.o
2620 @end smallexample
2621 @end enumerate
2622
2623 The last three steps can be grouped in a single command:
2624 @smallexample
2625 gnatmake my_main.adb -largs file1.o file2.o
2626 @end smallexample
2627
2628 @cindex Binder output file
2629 @noindent
2630 If the main program is in a language other than Ada, then you may have
2631 more than one entry point into the Ada subsystem. You must use a special
2632 binder option to generate callable routines that initialize and
2633 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2634 Calls to the initialization and finalization routines must be inserted
2635 in the main program, or some other appropriate point in the code. The
2636 call to initialize the Ada units must occur before the first Ada
2637 subprogram is called, and the call to finalize the Ada units must occur
2638 after the last Ada subprogram returns. The binder will place the
2639 initialization and finalization subprograms into the
2640 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2641 sources.  To illustrate, we have the following example:
2642
2643 @smallexample
2644 /* main.c */
2645 extern void adainit (void);
2646 extern void adafinal (void);
2647 extern int add (int, int);
2648 extern int sub (int, int);
2649
2650 int main (int argc, char *argv[])
2651 @{
2652   int a = 21, b = 7;
2653
2654   adainit();
2655
2656   /* Should print "21 + 7 = 28" */
2657   printf ("%d + %d = %d\n", a, b, add (a, b));
2658   /* Should print "21 - 7 = 14" */
2659   printf ("%d - %d = %d\n", a, b, sub (a, b));
2660
2661   adafinal();
2662 @}
2663 @end smallexample
2664
2665 @smallexample @c ada
2666 --  unit1.ads
2667 package Unit1 is
2668    function Add (A, B : Integer) return Integer;
2669    pragma Export (C, Add, "add");
2670 end Unit1;
2671
2672 --  unit1.adb
2673 package body Unit1 is
2674    function Add (A, B : Integer) return Integer is
2675    begin
2676       return A + B;
2677    end Add;
2678 end Unit1;
2679
2680 --  unit2.ads
2681 package Unit2 is
2682    function Sub (A, B : Integer) return Integer;
2683    pragma Export (C, Sub, "sub");
2684 end Unit2;
2685
2686 --  unit2.adb
2687 package body Unit2 is
2688    function Sub (A, B : Integer) return Integer is
2689    begin
2690       return A - B;
2691    end Sub;
2692 end Unit2;
2693 @end smallexample
2694
2695 @enumerate
2696 @item
2697 The build procedure for this application is similar to the last
2698 example's.  First, compile the foreign language files to generate object
2699 files:
2700 @smallexample
2701 ^gcc -c main.c^gcc -c main.c^
2702 @end smallexample
2703
2704 @item
2705 Next, compile the Ada units to produce a set of object files and ALI
2706 files:
2707 @smallexample
2708 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2709 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2710 @end smallexample
2711
2712 @item
2713 Run the Ada binder on every generated ALI file.  Make sure to use the
2714 @option{-n} option to specify a foreign main program:
2715 @smallexample
2716 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2717 @end smallexample
2718
2719 @item
2720 Link the Ada main program, the Ada objects and the foreign language
2721 objects. You need only list the last ALI file here:
2722 @smallexample
2723 gnatlink unit2.ali main.o -o exec_file
2724 @end smallexample
2725
2726 This procedure yields a binary executable called @file{exec_file}.
2727 @end enumerate
2728
2729 @noindent
2730 Depending on the circumstances (for example when your non-Ada main object
2731 does not provide symbol @code{main}), you may also need to instruct the
2732 GNAT linker not to include the standard startup objects by passing the
2733 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2734
2735 @node Calling Conventions
2736 @subsection Calling Conventions
2737 @cindex Foreign Languages
2738 @cindex Calling Conventions
2739 GNAT follows standard calling sequence conventions and will thus interface
2740 to any other language that also follows these conventions. The following
2741 Convention identifiers are recognized by GNAT:
2742
2743 @table @code
2744 @cindex Interfacing to Ada
2745 @cindex Other Ada compilers
2746 @cindex Convention Ada
2747 @item Ada
2748 This indicates that the standard Ada calling sequence will be
2749 used and all Ada data items may be passed without any limitations in the
2750 case where GNAT is used to generate both the caller and callee. It is also
2751 possible to mix GNAT generated code and code generated by another Ada
2752 compiler. In this case, the data types should be restricted to simple
2753 cases, including primitive types. Whether complex data types can be passed
2754 depends on the situation. Probably it is safe to pass simple arrays, such
2755 as arrays of integers or floats. Records may or may not work, depending
2756 on whether both compilers lay them out identically. Complex structures
2757 involving variant records, access parameters, tasks, or protected types,
2758 are unlikely to be able to be passed.
2759
2760 Note that in the case of GNAT running
2761 on a platform that supports HP Ada 83, a higher degree of compatibility
2762 can be guaranteed, and in particular records are layed out in an identical
2763 manner in the two compilers. Note also that if output from two different
2764 compilers is mixed, the program is responsible for dealing with elaboration
2765 issues. Probably the safest approach is to write the main program in the
2766 version of Ada other than GNAT, so that it takes care of its own elaboration
2767 requirements, and then call the GNAT-generated adainit procedure to ensure
2768 elaboration of the GNAT components. Consult the documentation of the other
2769 Ada compiler for further details on elaboration.
2770
2771 However, it is not possible to mix the tasking run time of GNAT and
2772 HP Ada 83, All the tasking operations must either be entirely within
2773 GNAT compiled sections of the program, or entirely within HP Ada 83
2774 compiled sections of the program.
2775
2776 @cindex Interfacing to Assembly
2777 @cindex Convention Assembler
2778 @item Assembler
2779 Specifies assembler as the convention. In practice this has the
2780 same effect as convention Ada (but is not equivalent in the sense of being
2781 considered the same convention).
2782
2783 @cindex Convention Asm
2784 @findex Asm
2785 @item Asm
2786 Equivalent to Assembler.
2787
2788 @cindex Interfacing to COBOL
2789 @cindex Convention COBOL
2790 @findex COBOL
2791 @item COBOL
2792 Data will be passed according to the conventions described
2793 in section B.4 of the Ada Reference Manual.
2794
2795 @findex C
2796 @cindex Interfacing to C
2797 @cindex Convention C
2798 @item C
2799 Data will be passed according to the conventions described
2800 in section B.3 of the Ada Reference Manual.
2801
2802 A note on interfacing to a C ``varargs'' function:
2803 @findex C varargs function
2804 @cindex Interfacing to C varargs function
2805 @cindex varargs function interfaces
2806
2807 @itemize @bullet
2808 @item
2809 In C, @code{varargs} allows a function to take a variable number of
2810 arguments. There is no direct equivalent in this to Ada. One
2811 approach that can be used is to create a C wrapper for each
2812 different profile and then interface to this C wrapper. For
2813 example, to print an @code{int} value using @code{printf},
2814 create a C function @code{printfi} that takes two arguments, a
2815 pointer to a string and an int, and calls @code{printf}.
2816 Then in the Ada program, use pragma @code{Import} to
2817 interface to @code{printfi}.
2818
2819 @item
2820 It may work on some platforms to directly interface to
2821 a @code{varargs} function by providing a specific Ada profile
2822 for a particular call. However, this does not work on
2823 all platforms, since there is no guarantee that the
2824 calling sequence for a two argument normal C function
2825 is the same as for calling a @code{varargs} C function with
2826 the same two arguments.
2827 @end itemize
2828
2829 @cindex Convention Default
2830 @findex Default
2831 @item Default
2832 Equivalent to C.
2833
2834 @cindex Convention External
2835 @findex External
2836 @item External
2837 Equivalent to C.
2838
2839 @ifclear vms
2840 @findex C++
2841 @cindex Interfacing to C++
2842 @cindex Convention C++
2843 @item C_Plus_Plus (or CPP)
2844 This stands for C++. For most purposes this is identical to C.
2845 See the separate description of the specialized GNAT pragmas relating to
2846 C++ interfacing for further details.
2847 @end ifclear
2848
2849 @findex Fortran
2850 @cindex Interfacing to Fortran
2851 @cindex Convention Fortran
2852 @item Fortran
2853 Data will be passed according to the conventions described
2854 in section B.5 of the Ada Reference Manual.
2855
2856 @item Intrinsic
2857 This applies to an intrinsic operation, as defined in the Ada
2858 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2859 this means that the body of the subprogram is provided by the compiler itself,
2860 usually by means of an efficient code sequence, and that the user does not
2861 supply an explicit body for it. In an application program, the pragma may
2862 be applied to the following sets of names:
2863
2864 @itemize @bullet
2865 @item
2866 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2867 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2868 two formal parameters. The
2869 first one must be a signed integer type or a modular type with a binary
2870 modulus, and the second parameter must be of type Natural.
2871 The return type must be the same as the type of the first argument. The size
2872 of this type can only be 8, 16, 32, or 64.
2873
2874 @item
2875 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2876 The corresponding operator declaration must have parameters and result type
2877 that have the same root numeric type (for example, all three are long_float
2878 types). This simplifies the definition of operations that use type checking
2879 to perform dimensional checks:
2880
2881 @smallexample @c ada
2882 type Distance is new Long_Float;
2883 type Time     is new Long_Float;
2884 type Velocity is new Long_Float;
2885 function "/" (D : Distance; T : Time)
2886   return Velocity;
2887 pragma Import (Intrinsic, "/");
2888 @end smallexample
2889
2890 @noindent
2891 This common idiom is often programmed with a generic definition and an
2892 explicit body. The pragma makes it simpler to introduce such declarations.
2893 It incurs no overhead in compilation time or code size, because it is
2894 implemented as a single machine instruction.
2895
2896 @item
2897 General subprogram entities, to bind an Ada subprogram declaration to
2898 a compiler builtin by name with back-ends where such interfaces are
2899 available. A typical example is the set of ``__builtin'' functions
2900 exposed by the GCC back-end, as in the following example:
2901
2902 @smallexample @c ada
2903    function builtin_sqrt (F : Float) return Float;
2904    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2905 @end smallexample
2906
2907 Most of the GCC builtins are accessible this way, and as for other
2908 import conventions (e.g. C), it is the user's responsibility to ensure
2909 that the Ada subprogram profile matches the underlying builtin
2910 expectations.
2911 @end itemize
2912
2913 @noindent
2914
2915 @ifset unw
2916 @findex Stdcall
2917 @cindex Convention Stdcall
2918 @item Stdcall
2919 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2920 and specifies that the @code{Stdcall} calling sequence will be used,
2921 as defined by the NT API. Nevertheless, to ease building
2922 cross-platform bindings this convention will be handled as a @code{C} calling
2923 convention on non-Windows platforms.
2924
2925 @findex DLL
2926 @cindex Convention DLL
2927 @item DLL
2928 This is equivalent to @code{Stdcall}.
2929
2930 @findex Win32
2931 @cindex Convention Win32
2932 @item Win32
2933 This is equivalent to @code{Stdcall}.
2934 @end ifset
2935
2936 @findex Stubbed
2937 @cindex Convention Stubbed
2938 @item Stubbed
2939 This is a special convention that indicates that the compiler
2940 should provide a stub body that raises @code{Program_Error}.
2941 @end table
2942
2943 @noindent
2944 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2945 that can be used to parametrize conventions and allow additional synonyms
2946 to be specified. For example if you have legacy code in which the convention
2947 identifier Fortran77 was used for Fortran, you can use the configuration
2948 pragma:
2949
2950 @smallexample @c ada
2951 pragma Convention_Identifier (Fortran77, Fortran);
2952 @end smallexample
2953
2954 @noindent
2955 And from now on the identifier Fortran77 may be used as a convention
2956 identifier (for example in an @code{Import} pragma) with the same
2957 meaning as Fortran.
2958
2959 @ifclear vms
2960 @node Building Mixed Ada & C++ Programs
2961 @section Building Mixed Ada and C++ Programs
2962
2963 @noindent
2964 A programmer inexperienced with mixed-language development may find that
2965 building an application containing both Ada and C++ code can be a
2966 challenge.  This section gives a few
2967 hints that should make this task easier. The first section addresses
2968 the differences between interfacing with C and interfacing with C++.
2969 The second section
2970 looks into the delicate problem of linking the complete application from
2971 its Ada and C++ parts. The last section gives some hints on how the GNAT
2972 run-time library can be adapted in order to allow inter-language dispatching
2973 with a new C++ compiler.
2974
2975 @menu
2976 * Interfacing to C++::
2977 * Linking a Mixed C++ & Ada Program::
2978 * A Simple Example::
2979 * Interfacing with C++ constructors::
2980 * Interfacing with C++ at the Class Level::
2981 @end menu
2982
2983 @node Interfacing to C++
2984 @subsection Interfacing to C++
2985
2986 @noindent
2987 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2988 generating code that is compatible with the G++ Application Binary
2989 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2990
2991 @noindent
2992 Interfacing can be done at 3 levels: simple data, subprograms, and
2993 classes. In the first two cases, GNAT offers a specific @code{Convention
2994 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2995 Usually, C++ mangles the names of subprograms. To generate proper mangled
2996 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2997 This problem can also be addressed manually in two ways:
2998
2999 @itemize @bullet
3000 @item
3001 by modifying the C++ code in order to force a C convention using
3002 the @code{extern "C"} syntax.
3003
3004 @item
3005 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
3006 Link_Name argument of the pragma import.
3007 @end itemize
3008
3009 @noindent
3010 Interfacing at the class level can be achieved by using the GNAT specific
3011 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3012 gnat_rm, GNAT Reference Manual}, for additional information.
3013
3014 @node Linking a Mixed C++ & Ada Program
3015 @subsection Linking a Mixed C++ & Ada Program
3016
3017 @noindent
3018 Usually the linker of the C++ development system must be used to link
3019 mixed applications because most C++ systems will resolve elaboration
3020 issues (such as calling constructors on global class instances)
3021 transparently during the link phase. GNAT has been adapted to ease the
3022 use of a foreign linker for the last phase. Three cases can be
3023 considered:
3024 @enumerate
3025
3026 @item
3027 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3028 The C++ linker can simply be called by using the C++ specific driver
3029 called @code{g++}.
3030
3031 Note that if the C++ code uses inline functions, you will need to
3032 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3033 order to provide an existing function implementation that the Ada code can
3034 link with.
3035
3036 @smallexample
3037 $ g++ -c -fkeep-inline-functions file1.C
3038 $ g++ -c -fkeep-inline-functions file2.C
3039 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3040 @end smallexample
3041
3042 @item
3043 Using GNAT and G++ from two different GCC installations: If both
3044 compilers are on the @env{PATH}, the previous method may be used. It is
3045 important to note that environment variables such as
3046 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3047 @env{GCC_ROOT} will affect both compilers
3048 at the same time and may make one of the two compilers operate
3049 improperly if set during invocation of the wrong compiler.  It is also
3050 very important that the linker uses the proper @file{libgcc.a} GCC
3051 library -- that is, the one from the C++ compiler installation. The
3052 implicit link command as suggested in the @command{gnatmake} command
3053 from the former example can be replaced by an explicit link command with
3054 the full-verbosity option in order to verify which library is used:
3055 @smallexample
3056 $ gnatbind ada_unit
3057 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3058 @end smallexample
3059 If there is a problem due to interfering environment variables, it can
3060 be worked around by using an intermediate script. The following example
3061 shows the proper script to use when GNAT has not been installed at its
3062 default location and g++ has been installed at its default location:
3063
3064 @smallexample
3065 $ cat ./my_script
3066 #!/bin/sh
3067 unset BINUTILS_ROOT
3068 unset GCC_ROOT
3069 c++ $*
3070 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3071 @end smallexample
3072
3073 @item
3074 Using a non-GNU C++ compiler: The commands previously described can be
3075 used to insure that the C++ linker is used. Nonetheless, you need to add
3076 a few more parameters to the link command line, depending on the exception
3077 mechanism used.
3078
3079 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3080 to the libgcc libraries are required:
3081
3082 @smallexample
3083 $ cat ./my_script
3084 #!/bin/sh
3085 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3086 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3087 @end smallexample
3088
3089 Where CC is the name of the non-GNU C++ compiler.
3090
3091 If the @code{zero cost} exception mechanism is used, and the platform
3092 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3093 paths to more objects are required:
3094
3095 @smallexample
3096 $ cat ./my_script
3097 #!/bin/sh
3098 CC `gcc -print-file-name=crtbegin.o` $* \
3099 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3100 `gcc -print-file-name=crtend.o`
3101 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3102 @end smallexample
3103
3104 If the @code{zero cost} exception mechanism is used, and the platform
3105 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3106 Tru64 or AIX), the simple approach described above will not work and
3107 a pre-linking phase using GNAT will be necessary.
3108
3109 @end enumerate
3110
3111 Another alternative is to use the @command{gprbuild} multi-language builder
3112 which has a large knowledge base and knows how to link Ada and C++ code
3113 together automatically in most cases.
3114
3115 @node A Simple Example
3116 @subsection  A Simple Example
3117 @noindent
3118 The following example, provided as part of the GNAT examples, shows how
3119 to achieve procedural interfacing between Ada and C++ in both
3120 directions. The C++ class A has two methods. The first method is exported
3121 to Ada by the means of an extern C wrapper function. The second method
3122 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3123 a limited record with a layout comparable to the C++ class. The Ada
3124 subprogram, in turn, calls the C++ method. So, starting from the C++
3125 main program, the process passes back and forth between the two
3126 languages.
3127
3128 @noindent
3129 Here are the compilation commands:
3130 @smallexample
3131 $ gnatmake -c simple_cpp_interface
3132 $ g++ -c cpp_main.C
3133 $ g++ -c ex7.C
3134 $ gnatbind -n simple_cpp_interface
3135 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3136       -lstdc++ ex7.o cpp_main.o
3137 @end smallexample
3138
3139 @noindent
3140 Here are the corresponding sources:
3141 @smallexample
3142
3143 //cpp_main.C
3144
3145 #include "ex7.h"
3146
3147 extern "C" @{
3148   void adainit (void);
3149   void adafinal (void);
3150   void method1 (A *t);
3151 @}
3152
3153 void method1 (A *t)
3154 @{
3155   t->method1 ();
3156 @}
3157
3158 int main ()
3159 @{
3160   A obj;
3161   adainit ();
3162   obj.method2 (3030);
3163   adafinal ();
3164 @}
3165
3166 //ex7.h
3167
3168 class Origin @{
3169  public:
3170   int o_value;
3171 @};
3172 class A : public Origin @{
3173  public:
3174   void method1 (void);
3175   void method2 (int v);
3176   A();
3177   int   a_value;
3178 @};
3179
3180 //ex7.C
3181
3182 #include "ex7.h"
3183 #include <stdio.h>
3184
3185 extern "C" @{ void ada_method2 (A *t, int v);@}
3186
3187 void A::method1 (void)
3188 @{
3189   a_value = 2020;
3190   printf ("in A::method1, a_value = %d \n",a_value);
3191
3192 @}
3193
3194 void A::method2 (int v)
3195 @{
3196    ada_method2 (this, v);
3197    printf ("in A::method2, a_value = %d \n",a_value);
3198
3199 @}
3200
3201 A::A(void)
3202 @{
3203    a_value = 1010;
3204   printf ("in A::A, a_value = %d \n",a_value);
3205 @}
3206 @end smallexample
3207
3208 @smallexample @c ada
3209 -- Ada sources
3210 package body Simple_Cpp_Interface is
3211
3212    procedure Ada_Method2 (This : in out A; V : Integer) is
3213    begin
3214       Method1 (This);
3215       This.A_Value := V;
3216    end Ada_Method2;
3217
3218 end Simple_Cpp_Interface;
3219
3220 with System;
3221 package Simple_Cpp_Interface is
3222    type A is limited
3223       record
3224          Vptr    : System.Address;
3225          O_Value : Integer;
3226          A_Value : Integer;
3227       end record;
3228    pragma Convention (C, A);
3229
3230    procedure Method1 (This : in out A);
3231    pragma Import (C, Method1);
3232
3233    procedure Ada_Method2 (This : in out A; V : Integer);
3234    pragma Export (C, Ada_Method2);
3235
3236 end Simple_Cpp_Interface;
3237 @end smallexample
3238
3239 @node Interfacing with C++ constructors
3240 @subsection Interfacing with C++ constructors
3241 @noindent
3242
3243 In order to interface with C++ constructors GNAT provides the
3244 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3245 gnat_rm, GNAT Reference Manual}, for additional information).
3246 In this section we present some common uses of C++ constructors
3247 in mixed-languages programs in GNAT.
3248
3249 Let us assume that we need to interface with the following
3250 C++ class:
3251
3252 @smallexample
3253 @b{class} Root @{
3254 @b{public}:
3255   int  a_value;
3256   int  b_value;
3257   @b{virtual} int Get_Value ();
3258   Root();              // Default constructor
3259   Root(int v);         // 1st non-default constructor
3260   Root(int v, int w);  // 2nd non-default constructor
3261 @};
3262 @end smallexample
3263
3264 For this purpose we can write the following package spec (further
3265 information on how to build this spec is available in
3266 @ref{Interfacing with C++ at the Class Level} and
3267 @ref{Generating Ada Bindings for C and C++ headers}).
3268
3269 @smallexample @c ada
3270 with Interfaces.C; use Interfaces.C;
3271 package Pkg_Root is
3272   type Root is tagged limited record
3273      A_Value : int;
3274      B_Value : int;
3275   end record;
3276   pragma Import (CPP, Root);
3277
3278   function Get_Value (Obj : Root) return int;
3279   pragma Import (CPP, Get_Value);
3280
3281   function Constructor return Root;
3282   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3283
3284   function Constructor (v : Integer) return Root;
3285   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3286
3287   function Constructor (v, w : Integer) return Root;
3288   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3289 end Pkg_Root;
3290 @end smallexample
3291
3292 On the Ada side the constructor is represented by a function (whose
3293 name is arbitrary) that returns the classwide type corresponding to
3294 the imported C++ class. Although the constructor is described as a
3295 function, it is typically a procedure with an extra implicit argument
3296 (the object being initialized) at the implementation level. GNAT
3297 issues the appropriate call, whatever it is, to get the object
3298 properly initialized.
3299
3300 Constructors can only appear in the following contexts:
3301
3302 @itemize @bullet
3303 @item
3304 On the right side of an initialization of an object of type @var{T}.
3305 @item
3306 On the right side of an initialization of a record component of type @var{T}.
3307 @item
3308 In an Ada 2005 limited aggregate.
3309 @item
3310 In an Ada 2005 nested limited aggregate.
3311 @item
3312 In an Ada 2005 limited aggregate that initializes an object built in
3313 place by an extended return statement.
3314 @end itemize
3315
3316 @noindent
3317 In a declaration of an object whose type is a class imported from C++,
3318 either the default C++ constructor is implicitly called by GNAT, or
3319 else the required C++ constructor must be explicitly called in the
3320 expression that initializes the object. For example:
3321
3322 @smallexample @c ada
3323   Obj1 : Root;
3324   Obj2 : Root := Constructor;
3325   Obj3 : Root := Constructor (v => 10);
3326   Obj4 : Root := Constructor (30, 40);
3327 @end smallexample
3328
3329 The first two declarations are equivalent: in both cases the default C++
3330 constructor is invoked (in the former case the call to the constructor is
3331 implicit, and in the latter case the call is explicit in the object
3332 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3333 that takes an integer argument, and @code{Obj4} is initialized by the
3334 non-default C++ constructor that takes two integers.
3335
3336 Let us derive the imported C++ class in the Ada side. For example:
3337
3338 @smallexample @c ada
3339   type DT is new Root with record
3340      C_Value : Natural := 2009;
3341   end record;
3342 @end smallexample
3343
3344 In this case the components DT inherited from the C++ side must be
3345 initialized by a C++ constructor, and the additional Ada components
3346 of type DT are initialized by GNAT. The initialization of such an
3347 object is done either by default, or by means of a function returning
3348 an aggregate of type DT, or by means of an extension aggregate.
3349
3350 @smallexample @c ada
3351   Obj5 : DT;
3352   Obj6 : DT := Function_Returning_DT (50);
3353   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3354 @end smallexample
3355
3356 The declaration of @code{Obj5} invokes the default constructors: the
3357 C++ default constructor of the parent type takes care of the initialization
3358 of the components inherited from Root, and GNAT takes care of the default
3359 initialization of the additional Ada components of type DT (that is,
3360 @code{C_Value} is initialized to value 2009). The order of invocation of
3361 the constructors is consistent with the order of elaboration required by
3362 Ada and C++. That is, the constructor of the parent type is always called
3363 before the constructor of the derived type.
3364
3365 Let us now consider a record that has components whose type is imported
3366 from C++. For example:
3367
3368 @smallexample @c ada
3369   type Rec1 is limited record
3370      Data1 : Root := Constructor (10);
3371      Value : Natural := 1000;
3372   end record;
3373
3374   type Rec2 (D : Integer := 20) is limited record
3375      Rec   : Rec1;
3376      Data2 : Root := Constructor (D, 30);
3377   end record;
3378 @end smallexample
3379
3380 The initialization of an object of type @code{Rec2} will call the
3381 non-default C++ constructors specified for the imported components.
3382 For example:
3383
3384 @smallexample @c ada
3385   Obj8 : Rec2 (40);
3386 @end smallexample
3387
3388 Using Ada 2005 we can use limited aggregates to initialize an object
3389 invoking C++ constructors that differ from those specified in the type
3390 declarations. For example:
3391
3392 @smallexample @c ada
3393   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3394                           others => <>),
3395                   others => <>);
3396 @end smallexample
3397
3398 The above declaration uses an Ada 2005 limited aggregate to
3399 initialize @code{Obj9}, and the C++ constructor that has two integer
3400 arguments is invoked to initialize the @code{Data1} component instead
3401 of the constructor specified in the declaration of type @code{Rec1}. In
3402 Ada 2005 the box in the aggregate indicates that unspecified components
3403 are initialized using the expression (if any) available in the component
3404 declaration. That is, in this case discriminant @code{D} is initialized
3405 to value @code{20}, @code{Value} is initialized to value 1000, and the
3406 non-default C++ constructor that handles two integers takes care of
3407 initializing component @code{Data2} with values @code{20,30}.
3408
3409 In Ada 2005 we can use the extended return statement to build the Ada
3410 equivalent to C++ non-default constructors. For example:
3411
3412 @smallexample @c ada
3413   function Constructor (V : Integer) return Rec2 is
3414   begin
3415      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3416                                    others => <>),
3417                            others => <>) do
3418         --  Further actions required for construction of
3419         --  objects of type Rec2
3420         ...
3421      end record;
3422   end Constructor;
3423 @end smallexample
3424
3425 In this example the extended return statement construct is used to
3426 build in place the returned object whose components are initialized
3427 by means of a limited aggregate. Any further action associated with
3428 the constructor can be placed inside the construct.
3429
3430 @node Interfacing with C++ at the Class Level
3431 @subsection Interfacing with C++ at the Class Level
3432 @noindent
3433 In this section we demonstrate the GNAT features for interfacing with
3434 C++ by means of an example making use of Ada 2005 abstract interface
3435 types. This example consists of a classification of animals; classes
3436 have been used to model our main classification of animals, and
3437 interfaces provide support for the management of secondary
3438 classifications. We first demonstrate a case in which the types and
3439 constructors are defined on the C++ side and imported from the Ada
3440 side, and latter the reverse case.
3441
3442 The root of our derivation will be the @code{Animal} class, with a
3443 single private attribute (the @code{Age} of the animal) and two public
3444 primitives to set and get the value of this attribute.
3445
3446 @smallexample
3447 @b{class} Animal @{
3448  @b{public}:
3449    @b{virtual} void Set_Age (int New_Age);
3450    @b{virtual} int Age ();
3451  @b{private}:
3452    int Age_Count;
3453 @};
3454 @end smallexample
3455
3456 Abstract interface types are defined in C++ by means of classes with pure
3457 virtual functions and no data members. In our example we will use two
3458 interfaces that provide support for the common management of @code{Carnivore}
3459 and @code{Domestic} animals:
3460
3461 @smallexample
3462 @b{class} Carnivore @{
3463 @b{public}:
3464    @b{virtual} int Number_Of_Teeth () = 0;
3465 @};
3466
3467 @b{class} Domestic @{
3468 @b{public}:
3469    @b{virtual void} Set_Owner (char* Name) = 0;
3470 @};
3471 @end smallexample
3472
3473 Using these declarations, we can now say that a @code{Dog} is an animal that is
3474 both Carnivore and Domestic, that is:
3475
3476 @smallexample
3477 @b{class} Dog : Animal, Carnivore, Domestic @{
3478  @b{public}:
3479    @b{virtual} int  Number_Of_Teeth ();
3480    @b{virtual} void Set_Owner (char* Name);
3481
3482    Dog(); // Constructor
3483  @b{private}:
3484    int  Tooth_Count;
3485    char *Owner;
3486 @};
3487 @end smallexample
3488
3489 In the following examples we will assume that the previous declarations are
3490 located in a file named @code{animals.h}. The following package demonstrates
3491 how to import these C++ declarations from the Ada side:
3492
3493 @smallexample @c ada
3494 with Interfaces.C.Strings; use Interfaces.C.Strings;
3495 package Animals is
3496   type Carnivore is interface;
3497   pragma Convention (C_Plus_Plus, Carnivore);
3498   function Number_Of_Teeth (X : Carnivore)
3499      return Natural is abstract;
3500
3501   type Domestic is interface;
3502   pragma Convention (C_Plus_Plus, Set_Owner);
3503   procedure Set_Owner
3504     (X    : in out Domestic;
3505      Name : Chars_Ptr) is abstract;
3506
3507   type Animal is tagged record
3508     Age : Natural := 0;
3509   end record;
3510   pragma Import (C_Plus_Plus, Animal);
3511
3512   procedure Set_Age (X : in out Animal; Age : Integer);
3513   pragma Import (C_Plus_Plus, Set_Age);
3514
3515   function Age (X : Animal) return Integer;
3516   pragma Import (C_Plus_Plus, Age);
3517
3518   type Dog is new Animal and Carnivore and Domestic with record
3519     Tooth_Count : Natural;
3520     Owner       : String (1 .. 30);
3521   end record;
3522   pragma Import (C_Plus_Plus, Dog);
3523
3524   function Number_Of_Teeth (A : Dog) return Integer;
3525   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3526
3527   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3528   pragma Import (C_Plus_Plus, Set_Owner);
3529
3530   function New_Dog return Dog;
3531   pragma CPP_Constructor (New_Dog);
3532   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3533 end Animals;
3534 @end smallexample
3535
3536 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3537 interfacing with these C++ classes is easy. The only requirement is that all
3538 the primitives and components must be declared exactly in the same order in
3539 the two languages.
3540
3541 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3542 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3543 the arguments to the called primitives will be the same as for C++. For the
3544 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3545 to indicate that they have been defined on the C++ side; this is required
3546 because the dispatch table associated with these tagged types will be built
3547 in the C++ side and therefore will not contain the predefined Ada primitives
3548 which Ada would otherwise expect.
3549
3550 As the reader can see there is no need to indicate the C++ mangled names
3551 associated with each subprogram because it is assumed that all the calls to
3552 these primitives will be dispatching calls. The only exception is the
3553 constructor, which must be registered with the compiler by means of
3554 @code{pragma CPP_Constructor} and needs to provide its associated C++
3555 mangled name because the Ada compiler generates direct calls to it.
3556
3557 With the above packages we can now declare objects of type Dog on the Ada side
3558 and dispatch calls to the corresponding subprograms on the C++ side. We can
3559 also extend the tagged type Dog with further fields and primitives, and
3560 override some of its C++ primitives on the Ada side. For example, here we have
3561 a type derivation defined on the Ada side that inherits all the dispatching
3562 primitives of the ancestor from the C++ side.
3563
3564 @smallexample
3565 @b{with} Animals; @b{use} Animals;
3566 @b{package} Vaccinated_Animals @b{is}
3567   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3568   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3569 @b{end} Vaccinated_Animals;
3570 @end smallexample
3571
3572 It is important to note that, because of the ABI compatibility, the programmer
3573 does not need to add any further information to indicate either the object
3574 layout or the dispatch table entry associated with each dispatching operation.
3575
3576 Now let us define all the types and constructors on the Ada side and export
3577 them to C++, using the same hierarchy of our previous example:
3578
3579 @smallexample @c ada
3580 with Interfaces.C.Strings;
3581 use Interfaces.C.Strings;
3582 package Animals is
3583   type Carnivore is interface;
3584   pragma Convention (C_Plus_Plus, Carnivore);
3585   function Number_Of_Teeth (X : Carnivore)
3586      return Natural is abstract;
3587
3588   type Domestic is interface;
3589   pragma Convention (C_Plus_Plus, Set_Owner);
3590   procedure Set_Owner
3591     (X    : in out Domestic;
3592      Name : Chars_Ptr) is abstract;
3593
3594   type Animal is tagged record
3595     Age : Natural := 0;
3596   end record;
3597   pragma Convention (C_Plus_Plus, Animal);
3598
3599   procedure Set_Age (X : in out Animal; Age : Integer);
3600   pragma Export (C_Plus_Plus, Set_Age);
3601
3602   function Age (X : Animal) return Integer;
3603   pragma Export (C_Plus_Plus, Age);
3604
3605   type Dog is new Animal and Carnivore and Domestic with record
3606     Tooth_Count : Natural;
3607     Owner       : String (1 .. 30);
3608   end record;
3609   pragma Convention (C_Plus_Plus, Dog);
3610
3611   function Number_Of_Teeth (A : Dog) return Integer;
3612   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3613
3614   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3615   pragma Export (C_Plus_Plus, Set_Owner);
3616
3617   function New_Dog return Dog'Class;
3618   pragma Export (C_Plus_Plus, New_Dog);
3619 end Animals;
3620 @end smallexample
3621
3622 Compared with our previous example the only difference is the use of
3623 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3624 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3625 nothing else to be done; as explained above, the only requirement is that all
3626 the primitives and components are declared in exactly the same order.
3627
3628 For completeness, let us see a brief C++ main program that uses the
3629 declarations available in @code{animals.h} (presented in our first example) to
3630 import and use the declarations from the Ada side, properly initializing and
3631 finalizing the Ada run-time system along the way:
3632
3633 @smallexample
3634 @b{#include} "animals.h"
3635 @b{#include} <iostream>
3636 @b{using namespace} std;
3637
3638 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3639 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3640 void Check_Animal (Animal *obj)       @{@dots{}@}
3641 void Check_Dog (Dog *obj)             @{@dots{}@}
3642
3643 @b{extern} "C" @{
3644   void adainit (void);
3645   void adafinal (void);
3646   Dog* new_dog ();
3647 @}
3648
3649 void test ()
3650 @{
3651   Dog *obj = new_dog();  // Ada constructor
3652   Check_Carnivore (obj); // Check secondary DT
3653   Check_Domestic (obj);  // Check secondary DT
3654   Check_Animal (obj);    // Check primary DT
3655   Check_Dog (obj);       // Check primary DT
3656 @}
3657
3658 int main ()
3659 @{
3660   adainit ();  test();  adafinal ();
3661   return 0;
3662 @}
3663 @end smallexample
3664
3665 @node Comparison between GNAT and C/C++ Compilation Models
3666 @section Comparison between GNAT and C/C++ Compilation Models
3667
3668 @noindent
3669 The GNAT model of compilation is close to the C and C++ models. You can
3670 think of Ada specs as corresponding to header files in C. As in C, you
3671 don't need to compile specs; they are compiled when they are used. The
3672 Ada @code{with} is similar in effect to the @code{#include} of a C
3673 header.
3674
3675 One notable difference is that, in Ada, you may compile specs separately
3676 to check them for semantic and syntactic accuracy. This is not always
3677 possible with C headers because they are fragments of programs that have
3678 less specific syntactic or semantic rules.
3679
3680 The other major difference is the requirement for running the binder,
3681 which performs two important functions. First, it checks for
3682 consistency. In C or C++, the only defense against assembling
3683 inconsistent programs lies outside the compiler, in a makefile, for
3684 example. The binder satisfies the Ada requirement that it be impossible
3685 to construct an inconsistent program when the compiler is used in normal
3686 mode.
3687
3688 @cindex Elaboration order control
3689 The other important function of the binder is to deal with elaboration
3690 issues. There are also elaboration issues in C++ that are handled
3691 automatically. This automatic handling has the advantage of being
3692 simpler to use, but the C++ programmer has no control over elaboration.
3693 Where @code{gnatbind} might complain there was no valid order of
3694 elaboration, a C++ compiler would simply construct a program that
3695 malfunctioned at run time.
3696 @end ifclear
3697
3698 @node Comparison between GNAT and Conventional Ada Library Models
3699 @section Comparison between GNAT and Conventional Ada Library Models
3700
3701 @noindent
3702 This section is intended for Ada programmers who have
3703 used an Ada compiler implementing the traditional Ada library
3704 model, as described in the Ada Reference Manual.
3705
3706 @cindex GNAT library
3707 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3708 source files themselves acts as the library. Compiling Ada programs does
3709 not generate any centralized information, but rather an object file and
3710 a ALI file, which are of interest only to the binder and linker.
3711 In a traditional system, the compiler reads information not only from
3712 the source file being compiled, but also from the centralized library.
3713 This means that the effect of a compilation depends on what has been
3714 previously compiled. In particular:
3715
3716 @itemize @bullet
3717 @item
3718 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3719 to the version of the unit most recently compiled into the library.
3720
3721 @item
3722 Inlining is effective only if the necessary body has already been
3723 compiled into the library.
3724
3725 @item
3726 Compiling a unit may obsolete other units in the library.
3727 @end itemize
3728
3729 @noindent
3730 In GNAT, compiling one unit never affects the compilation of any other
3731 units because the compiler reads only source files. Only changes to source
3732 files can affect the results of a compilation. In particular:
3733
3734 @itemize @bullet
3735 @item
3736 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3737 to the source version of the unit that is currently accessible to the
3738 compiler.
3739
3740 @item
3741 @cindex Inlining
3742 Inlining requires the appropriate source files for the package or
3743 subprogram bodies to be available to the compiler. Inlining is always
3744 effective, independent of the order in which units are complied.
3745
3746 @item
3747 Compiling a unit never affects any other compilations. The editing of
3748 sources may cause previous compilations to be out of date if they
3749 depended on the source file being modified.
3750 @end itemize
3751
3752 @noindent
3753 The most important result of these differences is that order of compilation
3754 is never significant in GNAT. There is no situation in which one is
3755 required to do one compilation before another. What shows up as order of
3756 compilation requirements in the traditional Ada library becomes, in
3757 GNAT, simple source dependencies; in other words, there is only a set
3758 of rules saying what source files must be present when a file is
3759 compiled.
3760
3761 @ifset vms
3762 @node Placement of temporary files
3763 @section Placement of temporary files
3764 @cindex Temporary files (user control over placement)
3765
3766 @noindent
3767 GNAT creates temporary files in the directory designated by the environment
3768 variable @env{TMPDIR}.
3769 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3770 for detailed information on how environment variables are resolved.
3771 For most users the easiest way to make use of this feature is to simply
3772 define @env{TMPDIR} as a job level logical name).
3773 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3774 for compiler temporary files, then you can include something like the
3775 following command in your @file{LOGIN.COM} file:
3776
3777 @smallexample
3778 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3779 @end smallexample
3780
3781 @noindent
3782 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3783 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3784 designated by @env{TEMP}.
3785 If none of these environment variables are defined then GNAT uses the
3786 directory designated by the logical name @code{SYS$SCRATCH:}
3787 (by default the user's home directory). If all else fails
3788 GNAT uses the current directory for temporary files.
3789 @end ifset
3790
3791 @c *************************
3792 @node Compiling Using gcc
3793 @chapter Compiling Using @command{gcc}
3794
3795 @noindent
3796 This chapter discusses how to compile Ada programs using the @command{gcc}
3797 command. It also describes the set of switches
3798 that can be used to control the behavior of the compiler.
3799 @menu
3800 * Compiling Programs::
3801 * Switches for gcc::
3802 * Search Paths and the Run-Time Library (RTL)::
3803 * Order of Compilation Issues::
3804 * Examples::
3805 @end menu
3806
3807 @node Compiling Programs
3808 @section Compiling Programs
3809
3810 @noindent
3811 The first step in creating an executable program is to compile the units
3812 of the program using the @command{gcc} command. You must compile the
3813 following files:
3814
3815 @itemize @bullet
3816 @item
3817 the body file (@file{.adb}) for a library level subprogram or generic
3818 subprogram
3819
3820 @item
3821 the spec file (@file{.ads}) for a library level package or generic
3822 package that has no body
3823
3824 @item
3825 the body file (@file{.adb}) for a library level package
3826 or generic package that has a body
3827
3828 @end itemize
3829
3830 @noindent
3831 You need @emph{not} compile the following files
3832
3833 @itemize @bullet
3834
3835 @item
3836 the spec of a library unit which has a body
3837
3838 @item
3839 subunits
3840 @end itemize
3841
3842 @noindent
3843 because they are compiled as part of compiling related units. GNAT
3844 package specs
3845 when the corresponding body is compiled, and subunits when the parent is
3846 compiled.
3847
3848 @cindex cannot generate code
3849 If you attempt to compile any of these files, you will get one of the
3850 following error messages (where @var{fff} is the name of the file you compiled):
3851
3852 @smallexample
3853 cannot generate code for file @var{fff} (package spec)
3854 to check package spec, use -gnatc
3855
3856 cannot generate code for file @var{fff} (missing subunits)
3857 to check parent unit, use -gnatc
3858
3859 cannot generate code for file @var{fff} (subprogram spec)
3860 to check subprogram spec, use -gnatc
3861
3862 cannot generate code for file @var{fff} (subunit)
3863 to check subunit, use -gnatc
3864 @end smallexample
3865
3866 @noindent
3867 As indicated by the above error messages, if you want to submit
3868 one of these files to the compiler to check for correct semantics
3869 without generating code, then use the @option{-gnatc} switch.
3870
3871 The basic command for compiling a file containing an Ada unit is
3872
3873 @smallexample
3874 $ gcc -c @ovar{switches} @file{file name}
3875 @end smallexample
3876
3877 @noindent
3878 where @var{file name} is the name of the Ada file (usually
3879 having an extension
3880 @file{.ads} for a spec or @file{.adb} for a body).
3881 @ifclear vms
3882 You specify the
3883 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3884 @end ifclear
3885 The result of a successful compilation is an object file, which has the
3886 same name as the source file but an extension of @file{.o} and an Ada
3887 Library Information (ALI) file, which also has the same name as the
3888 source file, but with @file{.ali} as the extension. GNAT creates these
3889 two output files in the current directory, but you may specify a source
3890 file in any directory using an absolute or relative path specification
3891 containing the directory information.
3892
3893 @findex gnat1
3894 @command{gcc} is actually a driver program that looks at the extensions of
3895 the file arguments and loads the appropriate compiler. For example, the
3896 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3897 These programs are in directories known to the driver program (in some
3898 configurations via environment variables you set), but need not be in
3899 your path. The @command{gcc} driver also calls the assembler and any other
3900 utilities needed to complete the generation of the required object
3901 files.
3902
3903 It is possible to supply several file names on the same @command{gcc}
3904 command. This causes @command{gcc} to call the appropriate compiler for
3905 each file. For example, the following command lists three separate
3906 files to be compiled:
3907
3908 @smallexample
3909 $ gcc -c x.adb y.adb z.c
3910 @end smallexample
3911
3912 @noindent
3913 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3914 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3915 The compiler generates three object files @file{x.o}, @file{y.o} and
3916 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3917 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3918 @ifclear vms
3919 except for
3920 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3921 @end ifclear
3922
3923 @node Switches for gcc
3924 @section Switches for @command{gcc}
3925
3926 @noindent
3927 The @command{gcc} command accepts switches that control the
3928 compilation process. These switches are fully described in this section.
3929 First we briefly list all the switches, in alphabetical order, then we
3930 describe the switches in more detail in functionally grouped sections.
3931
3932 More switches exist for GCC than those documented here, especially
3933 for specific targets. However, their use is not recommended as
3934 they may change code generation in ways that are incompatible with
3935 the Ada run-time library, or can cause inconsistencies between
3936 compilation units.
3937
3938 @menu
3939 * Output and Error Message Control::
3940 * Warning Message Control::
3941 * Debugging and Assertion Control::
3942 * Validity Checking::
3943 * Style Checking::
3944 * Run-Time Checks::
3945 * Using gcc for Syntax Checking::
3946 * Using gcc for Semantic Checking::
3947 * Compiling Different Versions of Ada::
3948 * Character Set Control::
3949 * File Naming Control::
3950 * Subprogram Inlining Control::
3951 * Auxiliary Output Control::
3952 * Debugging Control::
3953 * Exception Handling Control::
3954 * Units to Sources Mapping Files::
3955 * Integrated Preprocessing::
3956 * Code Generation Control::
3957 @ifset vms
3958 * Return Codes::
3959 @end ifset
3960 @end menu
3961
3962 @table @option
3963 @c !sort!
3964 @ifclear vms
3965 @cindex @option{-b} (@command{gcc})
3966 @item -b @var{target}
3967 Compile your program to run on @var{target}, which is the name of a
3968 system configuration. You must have a GNAT cross-compiler built if
3969 @var{target} is not the same as your host system.
3970
3971 @item -B@var{dir}
3972 @cindex @option{-B} (@command{gcc})
3973 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3974 from @var{dir} instead of the default location. Only use this switch
3975 when multiple versions of the GNAT compiler are available.
3976 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3977 GNU Compiler Collection (GCC)}, for further details. You would normally
3978 use the @option{-b} or @option{-V} switch instead.
3979
3980 @item -c
3981 @cindex @option{-c} (@command{gcc})
3982 Compile. Always use this switch when compiling Ada programs.
3983
3984 Note: for some other languages when using @command{gcc}, notably in
3985 the case of C and C++, it is possible to use
3986 use @command{gcc} without a @option{-c} switch to
3987 compile and link in one step. In the case of GNAT, you
3988 cannot use this approach, because the binder must be run
3989 and @command{gcc} cannot be used to run the GNAT binder.
3990 @end ifclear
3991
3992 @item -fno-inline
3993 @cindex @option{-fno-inline} (@command{gcc})
3994 Suppresses all back-end inlining, even if other optimization or inlining
3995 switches are set.
3996 This includes suppression of inlining that results
3997 from the use of the pragma @code{Inline_Always}.
3998 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3999 are ignored, and @option{-gnatn} and @option{-gnatN} have no
4000 effect if this switch is present.
4001
4002 @item -fno-inline-functions
4003 @cindex @option{-fno-inline-functions} (@command{gcc})
4004 Suppresses automatic inlining of simple subprograms, which is enabled
4005 if @option{-O3} is used.
4006
4007 @item -fno-inline-small-functions
4008 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4009 Suppresses automatic inlining of small subprograms, which is enabled
4010 if @option{-O2} is used.
4011
4012 @item -fno-inline-functions-called-once
4013 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4014 Suppresses inlining of subprograms local to the unit and called once
4015 from within it, which is enabled if @option{-O1} is used.
4016
4017 @item -fno-ivopts
4018 @cindex @option{-fno-ivopts} (@command{gcc})
4019 Suppresses high-level loop induction variable optimizations, which are
4020 enabled if @option{-O1} is used. These optimizations are generally
4021 profitable but, for some specific cases of loops with numerous uses
4022 of the iteration variable that follow a common pattern, they may end
4023 up destroying the regularity that could be exploited at a lower level
4024 and thus producing inferior code.
4025
4026 @item -fno-strict-aliasing
4027 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4028 Causes the compiler to avoid assumptions regarding non-aliasing
4029 of objects of different types. See
4030 @ref{Optimization and Strict Aliasing} for details.
4031
4032 @item -fstack-check
4033 @cindex @option{-fstack-check} (@command{gcc})
4034 Activates stack checking.
4035 See @ref{Stack Overflow Checking} for details.
4036
4037 @item -fstack-usage
4038 @cindex @option{-fstack-usage} (@command{gcc})
4039 Makes the compiler output stack usage information for the program, on a
4040 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4041
4042 @item -fcallgraph-info@r{[}=su@r{]}
4043 @cindex @option{-fcallgraph-info} (@command{gcc})
4044 Makes the compiler output callgraph information for the program, on a
4045 per-file basis.  The information is generated in the VCG format.  It can
4046 be decorated with stack-usage per-node information.
4047
4048 @item ^-g^/DEBUG^
4049 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4050 Generate debugging information. This information is stored in the object
4051 file and copied from there to the final executable file by the linker,
4052 where it can be read by the debugger. You must use the
4053 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4054
4055 @item -gnat83
4056 @cindex @option{-gnat83} (@command{gcc})
4057 Enforce Ada 83 restrictions.
4058
4059 @item -gnat95
4060 @cindex @option{-gnat95} (@command{gcc})
4061 Enforce Ada 95 restrictions.
4062
4063 @item -gnat05
4064 @cindex @option{-gnat05} (@command{gcc})
4065 Allow full Ada 2005 features.
4066
4067 @item -gnata
4068 @cindex @option{-gnata} (@command{gcc})
4069 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4070 activated. Note that these pragmas can also be controlled using the
4071 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4072 It also activates pragmas @code{Check}, @code{Precondition}, and
4073 @code{Postcondition}. Note that these pragmas can also be controlled
4074 using the configuration pragma @code{Check_Policy}.
4075
4076 @item -gnatA
4077 @cindex @option{-gnatA} (@command{gcc})
4078 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4079 it will be ignored.
4080
4081 @item -gnatb
4082 @cindex @option{-gnatb} (@command{gcc})
4083 Generate brief messages to @file{stderr} even if verbose mode set.
4084
4085 @item -gnatB
4086 @cindex @option{-gnatB} (@command{gcc})
4087 Assume no invalid (bad) values except for 'Valid attribute use.
4088
4089 @item -gnatc
4090 @cindex @option{-gnatc} (@command{gcc})
4091 Check syntax and semantics only (no code generation attempted).
4092
4093 @item -gnatd
4094 @cindex @option{-gnatd} (@command{gcc})
4095 Specify debug options for the compiler. The string of characters after
4096 the @option{-gnatd} specify the specific debug options. The possible
4097 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4098 compiler source file @file{debug.adb} for details of the implemented
4099 debug options. Certain debug options are relevant to applications
4100 programmers, and these are documented at appropriate points in this
4101 users guide.
4102
4103 @ifclear vms
4104 @item -gnatD
4105 @cindex @option{-gnatD[nn]} (@command{gcc})
4106 @end ifclear
4107 @ifset vms
4108 @item /XDEBUG /LXDEBUG=nnn
4109 @end ifset
4110 Create expanded source files for source level debugging. This switch
4111 also suppress generation of cross-reference information
4112 (see @option{-gnatx}).
4113
4114 @item -gnatec=@var{path}
4115 @cindex @option{-gnatec} (@command{gcc})
4116 Specify a configuration pragma file
4117 @ifclear vms
4118 (the equal sign is optional)
4119 @end ifclear
4120 (@pxref{The Configuration Pragmas Files}).
4121
4122 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4123 @cindex @option{-gnateD} (@command{gcc})
4124 Defines a symbol, associated with @var{value}, for preprocessing.
4125 (@pxref{Integrated Preprocessing}).
4126
4127 @item -gnatef
4128 @cindex @option{-gnatef} (@command{gcc})
4129 Display full source path name in brief error messages.
4130
4131 @item -gnateG
4132 @cindex @option{-gnateG} (@command{gcc})
4133 Save result of preprocessing in a text file.
4134
4135 @item -gnatem=@var{path}
4136 @cindex @option{-gnatem} (@command{gcc})
4137 Specify a mapping file
4138 @ifclear vms
4139 (the equal sign is optional)
4140 @end ifclear
4141 (@pxref{Units to Sources Mapping Files}).
4142
4143 @item -gnatep=@var{file}
4144 @cindex @option{-gnatep} (@command{gcc})
4145 Specify a preprocessing data file
4146 @ifclear vms
4147 (the equal sign is optional)
4148 @end ifclear
4149 (@pxref{Integrated Preprocessing}).
4150
4151 @item -gnatE
4152 @cindex @option{-gnatE} (@command{gcc})
4153 Full dynamic elaboration checks.
4154
4155 @item -gnatf
4156 @cindex @option{-gnatf} (@command{gcc})
4157 Full errors. Multiple errors per line, all undefined references, do not
4158 attempt to suppress cascaded errors.
4159
4160 @item -gnatF
4161 @cindex @option{-gnatF} (@command{gcc})
4162 Externals names are folded to all uppercase.
4163
4164 @item ^-gnatg^/GNAT_INTERNAL^
4165 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4166 Internal GNAT implementation mode. This should not be used for
4167 applications programs, it is intended only for use by the compiler
4168 and its run-time library. For documentation, see the GNAT sources.
4169 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4170 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4171 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4172 so that all standard warnings and all standard style options are turned on.
4173 All warnings and style error messages are treated as errors.
4174
4175 @ifclear vms
4176 @item -gnatG=nn
4177 @cindex @option{-gnatG[nn]} (@command{gcc})
4178 @end ifclear
4179 @ifset vms
4180 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4181 @end ifset
4182 List generated expanded code in source form.
4183
4184 @item ^-gnath^/HELP^
4185 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4186 Output usage information. The output is written to @file{stdout}.
4187
4188 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4189 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4190 Identifier character set
4191 @ifclear vms
4192 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4193 @end ifclear
4194 For details of the possible selections for @var{c},
4195 see @ref{Character Set Control}.
4196
4197 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4198 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4199 Ignore representation clauses. When this switch is used,
4200 representation clauses are treated as comments. This is useful
4201 when initially porting code where you want to ignore rep clause
4202 problems, and also for compiling foreign code (particularly
4203 for use with ASIS). The representation clauses that are ignored
4204 are: enumeration_representation_clause, record_representation_clause,
4205 and attribute_definition_clause for the following attributes:
4206 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4207 Object_Size, Size, Small, Stream_Size, and Value_Size.
4208 Note that this option should be used only for compiling -- the
4209 code is likely to malfunction at run time.
4210
4211 @item -gnatjnn
4212 @cindex @option{-gnatjnn} (@command{gcc})
4213 Reformat error messages to fit on nn character lines
4214
4215 @item -gnatk=@var{n}
4216 @cindex @option{-gnatk} (@command{gcc})
4217 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4218
4219 @item -gnatl
4220 @cindex @option{-gnatl} (@command{gcc})
4221 Output full source listing with embedded error messages.
4222
4223 @item -gnatL
4224 @cindex @option{-gnatL} (@command{gcc})
4225 Used in conjunction with -gnatG or -gnatD to intersperse original
4226 source lines (as comment lines with line numbers) in the expanded
4227 source output.
4228
4229 @item -gnatm=@var{n}
4230 @cindex @option{-gnatm} (@command{gcc})
4231 Limit number of detected error or warning messages to @var{n}
4232 where @var{n} is in the range 1..999999. The default setting if
4233 no switch is given is 9999. If the number of warnings reaches this
4234 limit, then a message is output and further warnings are suppressed,
4235 but the compilation is continued. If the number of error messages
4236 reaches this limit, then a message is output and the compilation
4237 is abandoned. The equal sign here is optional. A value of zero
4238 means that no limit applies.
4239
4240 @item -gnatn
4241 @cindex @option{-gnatn} (@command{gcc})
4242 Activate inlining for subprograms for which
4243 pragma @code{inline} is specified. This inlining is performed
4244 by the GCC back-end.
4245
4246 @item -gnatN
4247 @cindex @option{-gnatN} (@command{gcc})
4248 Activate front end inlining for subprograms for which
4249 pragma @code{Inline} is specified. This inlining is performed
4250 by the front end and will be visible in the
4251 @option{-gnatG} output.
4252
4253 When using a gcc-based back end (in practice this means using any version
4254 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4255 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4256 Historically front end inlining was more extensive than the gcc back end
4257 inlining, but that is no longer the case.
4258
4259 @item -gnato
4260 @cindex @option{-gnato} (@command{gcc})
4261 Enable numeric overflow checking (which is not normally enabled by
4262 default). Note that division by zero is a separate check that is not
4263 controlled by this switch (division by zero checking is on by default).
4264
4265 @item -gnatp
4266 @cindex @option{-gnatp} (@command{gcc})
4267 Suppress all checks. See @ref{Run-Time Checks} for details.
4268
4269 @item -gnatP
4270 @cindex @option{-gnatP} (@command{gcc})
4271 Enable polling. This is required on some systems (notably Windows NT) to
4272 obtain asynchronous abort and asynchronous transfer of control capability.
4273 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4274 details.
4275
4276 @item -gnatq
4277 @cindex @option{-gnatq} (@command{gcc})
4278 Don't quit. Try semantics, even if parse errors.
4279
4280 @item -gnatQ
4281 @cindex @option{-gnatQ} (@command{gcc})
4282 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4283
4284 @item -gnatr
4285 @cindex @option{-gnatr} (@command{gcc})
4286 Treat pragma Restrictions as Restriction_Warnings.
4287
4288 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4289 @cindex @option{-gnatR} (@command{gcc})
4290 Output representation information for declared types and objects.
4291
4292 @item -gnats
4293 @cindex @option{-gnats} (@command{gcc})
4294 Syntax check only.
4295
4296 @item -gnatS
4297 @cindex @option{-gnatS} (@command{gcc})
4298 Print package Standard.
4299
4300 @item -gnatt
4301 @cindex @option{-gnatt} (@command{gcc})
4302 Generate tree output file.
4303
4304 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4305 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4306 All compiler tables start at @var{nnn} times usual starting size.
4307
4308 @item -gnatu
4309 @cindex @option{-gnatu} (@command{gcc})
4310 List units for this compilation.
4311
4312 @item -gnatU
4313 @cindex @option{-gnatU} (@command{gcc})
4314 Tag all error messages with the unique string ``error:''
4315
4316 @item -gnatv
4317 @cindex @option{-gnatv} (@command{gcc})
4318 Verbose mode. Full error output with source lines to @file{stdout}.
4319
4320 @item -gnatV
4321 @cindex @option{-gnatV} (@command{gcc})
4322 Control level of validity checking. See separate section describing
4323 this feature.
4324
4325 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4326 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4327 Warning mode where
4328 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4329 the exact warnings that
4330 are enabled or disabled (@pxref{Warning Message Control}).
4331
4332 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4333 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4334 Wide character encoding method
4335 @ifclear vms
4336 (@var{e}=n/h/u/s/e/8).
4337 @end ifclear
4338 @ifset vms
4339 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4340 @end ifset
4341
4342 @item -gnatx
4343 @cindex @option{-gnatx} (@command{gcc})
4344 Suppress generation of cross-reference information.
4345
4346 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4347 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4348 Enable built-in style checks (@pxref{Style Checking}).
4349
4350 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4351 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4352 Distribution stub generation and compilation
4353 @ifclear vms
4354 (@var{m}=r/c for receiver/caller stubs).
4355 @end ifclear
4356 @ifset vms
4357 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4358 to be generated and compiled).
4359 @end ifset
4360
4361 @item ^-I^/SEARCH=^@var{dir}
4362 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4363 @cindex RTL
4364 Direct GNAT to search the @var{dir} directory for source files needed by
4365 the current compilation
4366 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4367
4368 @item ^-I-^/NOCURRENT_DIRECTORY^
4369 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4370 @cindex RTL
4371 Except for the source file named in the command line, do not look for source
4372 files in the directory containing the source file named in the command line
4373 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4374
4375 @ifclear vms
4376 @item -mbig-switch
4377 @cindex @option{-mbig-switch} (@command{gcc})
4378 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4379 This standard gcc switch causes the compiler to use larger offsets in its
4380 jump table representation for @code{case} statements.
4381 This may result in less efficient code, but is sometimes necessary
4382 (for example on HP-UX targets)
4383 @cindex HP-UX and @option{-mbig-switch} option
4384 in order to compile large and/or nested @code{case} statements.
4385
4386 @item -o @var{file}
4387 @cindex @option{-o} (@command{gcc})
4388 This switch is used in @command{gcc} to redirect the generated object file
4389 and its associated ALI file. Beware of this switch with GNAT, because it may
4390 cause the object file and ALI file to have different names which in turn
4391 may confuse the binder and the linker.
4392 @end ifclear
4393
4394 @item -nostdinc
4395 @cindex @option{-nostdinc} (@command{gcc})
4396 Inhibit the search of the default location for the GNAT Run Time
4397 Library (RTL) source files.
4398
4399 @item -nostdlib
4400 @cindex @option{-nostdlib} (@command{gcc})
4401 Inhibit the search of the default location for the GNAT Run Time
4402 Library (RTL) ALI files.
4403
4404 @ifclear vms
4405 @item -O@ovar{n}
4406 @cindex @option{-O} (@command{gcc})
4407 @var{n} controls the optimization level.
4408
4409 @table @asis
4410 @item n = 0
4411 No optimization, the default setting if no @option{-O} appears
4412
4413 @item n = 1
4414 Normal optimization, the default if you specify @option{-O} without
4415 an operand. A good compromise between code quality and compilation
4416 time.
4417
4418 @item n = 2
4419 Extensive optimization, may improve execution time, possibly at the cost of
4420 substantially increased compilation time.
4421
4422 @item n = 3
4423 Same as @option{-O2}, and also includes inline expansion for small subprograms
4424 in the same unit.
4425
4426 @item n = s
4427 Optimize space usage
4428 @end table
4429
4430 @noindent
4431 See also @ref{Optimization Levels}.
4432 @end ifclear
4433
4434 @ifset vms
4435 @item  /NOOPTIMIZE
4436 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4437 Equivalent to @option{/OPTIMIZE=NONE}.
4438 This is the default behavior in the absence of an @option{/OPTIMIZE}
4439 qualifier.
4440
4441 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4442 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4443 Selects the level of optimization for your program. The supported
4444 keywords are as follows:
4445 @table @code
4446 @item   ALL
4447 Perform most optimizations, including those that
4448 are expensive.
4449 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4450 without keyword options.
4451
4452 @item   NONE
4453 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4454
4455 @item SOME
4456 Perform some optimizations, but omit ones that are costly.
4457
4458 @item   DEVELOPMENT
4459 Same as @code{SOME}.
4460
4461 @item INLINING
4462 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4463 automatic inlining of small subprograms within a unit
4464
4465 @item   UNROLL_LOOPS
4466 Try to unroll loops. This keyword may be specified together with
4467 any keyword above other than @code{NONE}. Loop unrolling
4468 usually, but not always, improves the performance of programs.
4469
4470 @item SPACE
4471 Optimize space usage
4472 @end table
4473
4474 @noindent
4475 See also @ref{Optimization Levels}.
4476 @end ifset
4477
4478 @ifclear vms
4479 @item -pass-exit-codes
4480 @cindex @option{-pass-exit-codes} (@command{gcc})
4481 Catch exit codes from the compiler and use the most meaningful as
4482 exit status.
4483 @end ifclear
4484
4485 @item --RTS=@var{rts-path}
4486 @cindex @option{--RTS} (@command{gcc})
4487 Specifies the default location of the runtime library. Same meaning as the
4488 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4489
4490 @item ^-S^/ASM^
4491 @cindex @option{^-S^/ASM^} (@command{gcc})
4492 ^Used in place of @option{-c} to^Used to^
4493 cause the assembler source file to be
4494 generated, using @file{^.s^.S^} as the extension,
4495 instead of the object file.
4496 This may be useful if you need to examine the generated assembly code.
4497
4498 @item ^-fverbose-asm^/VERBOSE_ASM^
4499 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4500 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4501 to cause the generated assembly code file to be annotated with variable
4502 names, making it significantly easier to follow.
4503
4504 @item ^-v^/VERBOSE^
4505 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4506 Show commands generated by the @command{gcc} driver. Normally used only for
4507 debugging purposes or if you need to be sure what version of the
4508 compiler you are executing.
4509
4510 @ifclear vms
4511 @item -V @var{ver}
4512 @cindex @option{-V} (@command{gcc})
4513 Execute @var{ver} version of the compiler. This is the @command{gcc}
4514 version, not the GNAT version.
4515 @end ifclear
4516
4517 @item ^-w^/NO_BACK_END_WARNINGS^
4518 @cindex @option{-w} (@command{gcc})
4519 Turn off warnings generated by the back end of the compiler. Use of
4520 this switch also causes the default for front end warnings to be set
4521 to suppress (as though @option{-gnatws} had appeared at the start of
4522 the options).
4523
4524 @end table
4525
4526 @ifclear vms
4527 @c Combining qualifiers does not work on VMS
4528 You may combine a sequence of GNAT switches into a single switch. For
4529 example, the combined switch
4530
4531 @cindex Combining GNAT switches
4532 @smallexample
4533 -gnatofi3
4534 @end smallexample
4535
4536 @noindent
4537 is equivalent to specifying the following sequence of switches:
4538
4539 @smallexample
4540 -gnato -gnatf -gnati3
4541 @end smallexample
4542 @end ifclear
4543
4544 @noindent
4545 The following restrictions apply to the combination of switches
4546 in this manner:
4547
4548 @itemize @bullet
4549 @item
4550 The switch @option{-gnatc} if combined with other switches must come
4551 first in the string.
4552
4553 @item
4554 The switch @option{-gnats} if combined with other switches must come
4555 first in the string.
4556
4557 @item
4558 The switches
4559 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4560 may not be combined with any other switches.
4561
4562 @ifclear vms
4563 @item
4564 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4565 switch), then all further characters in the switch are interpreted
4566 as style modifiers (see description of @option{-gnaty}).
4567
4568 @item
4569 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4570 switch), then all further characters in the switch are interpreted
4571 as debug flags (see description of @option{-gnatd}).
4572
4573 @item
4574 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4575 switch), then all further characters in the switch are interpreted
4576 as warning mode modifiers (see description of @option{-gnatw}).
4577
4578 @item
4579 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4580 switch), then all further characters in the switch are interpreted
4581 as validity checking options (see description of @option{-gnatV}).
4582 @end ifclear
4583 @end itemize
4584
4585 @node Output and Error Message Control
4586 @subsection Output and Error Message Control
4587 @findex stderr
4588
4589 @noindent
4590 The standard default format for error messages is called ``brief format''.
4591 Brief format messages are written to @file{stderr} (the standard error
4592 file) and have the following form:
4593
4594 @smallexample
4595 e.adb:3:04: Incorrect spelling of keyword "function"
4596 e.adb:4:20: ";" should be "is"
4597 @end smallexample
4598
4599 @noindent
4600 The first integer after the file name is the line number in the file,
4601 and the second integer is the column number within the line.
4602 @ifclear vms
4603 @code{GPS} can parse the error messages
4604 and point to the referenced character.
4605 @end ifclear
4606 The following switches provide control over the error message
4607 format:
4608
4609 @table @option
4610 @c !sort!
4611 @item -gnatv
4612 @cindex @option{-gnatv} (@command{gcc})
4613 @findex stdout
4614 @ifclear vms
4615 The v stands for verbose.
4616 @end ifclear
4617 The effect of this setting is to write long-format error
4618 messages to @file{stdout} (the standard output file.
4619 The same program compiled with the
4620 @option{-gnatv} switch would generate:
4621
4622 @smallexample
4623 @cartouche
4624 3. funcion X (Q : Integer)
4625    |
4626 >>> Incorrect spelling of keyword "function"
4627 4. return Integer;
4628                  |
4629 >>> ";" should be "is"
4630 @end cartouche
4631 @end smallexample
4632
4633 @noindent
4634 The vertical bar indicates the location of the error, and the @samp{>>>}
4635 prefix can be used to search for error messages. When this switch is
4636 used the only source lines output are those with errors.
4637
4638 @item -gnatl
4639 @cindex @option{-gnatl} (@command{gcc})
4640 @ifclear vms
4641 The @code{l} stands for list.
4642 @end ifclear
4643 This switch causes a full listing of
4644 the file to be generated. In the case where a body is
4645 compiled, the corresponding spec is also listed, along
4646 with any subunits. Typical output from compiling a package
4647 body @file{p.adb} might look like:
4648
4649 @smallexample @c ada
4650 @cartouche
4651  Compiling: p.adb
4652
4653      1. package body p is
4654      2.    procedure a;
4655      3.    procedure a is separate;
4656      4. begin
4657      5.    null
4658                |
4659         >>> missing ";"
4660
4661      6. end;
4662
4663 Compiling: p.ads
4664
4665      1. package p is
4666      2.    pragma Elaborate_Body
4667                                 |
4668         >>> missing ";"
4669
4670      3. end p;
4671
4672 Compiling: p-a.adb
4673
4674      1. separate p
4675                 |
4676         >>> missing "("
4677
4678      2. procedure a is
4679      3. begin
4680      4.    null
4681                |
4682         >>> missing ";"
4683
4684      5. end;
4685 @end cartouche
4686 @end smallexample
4687
4688 @noindent
4689 @findex stderr
4690 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4691 standard output is redirected, a brief summary is written to
4692 @file{stderr} (standard error) giving the number of error messages and
4693 warning messages generated.
4694
4695 @item -^gnatl^OUTPUT_FILE^=file
4696 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4697 This has the same effect as @option{-gnatl} except that the output is
4698 written to a file instead of to standard output. If the given name
4699 @file{fname} does not start with a period, then it is the full name
4700 of the file to be written. If @file{fname} is an extension, it is
4701 appended to the name of the file being compiled. For example, if
4702 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4703 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4704
4705 @item -gnatU
4706 @cindex @option{-gnatU} (@command{gcc})
4707 This switch forces all error messages to be preceded by the unique
4708 string ``error:''. This means that error messages take a few more
4709 characters in space, but allows easy searching for and identification
4710 of error messages.
4711
4712 @item -gnatb
4713 @cindex @option{-gnatb} (@command{gcc})
4714 @ifclear vms
4715 The @code{b} stands for brief.
4716 @end ifclear
4717 This switch causes GNAT to generate the
4718 brief format error messages to @file{stderr} (the standard error
4719 file) as well as the verbose
4720 format message or full listing (which as usual is written to
4721 @file{stdout} (the standard output file).
4722
4723 @item -gnatm=@var{n}
4724 @cindex @option{-gnatm} (@command{gcc})
4725 @ifclear vms
4726 The @code{m} stands for maximum.
4727 @end ifclear
4728 @var{n} is a decimal integer in the
4729 range of 1 to 999999 and limits the number of error or warning
4730 messages to be generated. For example, using
4731 @option{-gnatm2} might yield
4732
4733 @smallexample
4734 e.adb:3:04: Incorrect spelling of keyword "function"
4735 e.adb:5:35: missing ".."
4736 fatal error: maximum number of errors detected
4737 compilation abandoned
4738 @end smallexample
4739
4740 @noindent
4741 The default setting if
4742 no switch is given is 9999. If the number of warnings reaches this
4743 limit, then a message is output and further warnings are suppressed,
4744 but the compilation is continued. If the number of error messages
4745 reaches this limit, then a message is output and the compilation
4746 is abandoned. A value of zero means that no limit applies.
4747
4748 @noindent
4749 Note that the equal sign is optional, so the switches
4750 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4751
4752 @item -gnatf
4753 @cindex @option{-gnatf} (@command{gcc})
4754 @cindex Error messages, suppressing
4755 @ifclear vms
4756 The @code{f} stands for full.
4757 @end ifclear
4758 Normally, the compiler suppresses error messages that are likely to be
4759 redundant. This switch causes all error
4760 messages to be generated. In particular, in the case of
4761 references to undefined variables. If a given variable is referenced
4762 several times, the normal format of messages is
4763 @smallexample
4764 e.adb:7:07: "V" is undefined (more references follow)
4765 @end smallexample
4766
4767 @noindent
4768 where the parenthetical comment warns that there are additional
4769 references to the variable @code{V}. Compiling the same program with the
4770 @option{-gnatf} switch yields
4771
4772 @smallexample
4773 e.adb:7:07: "V" is undefined
4774 e.adb:8:07: "V" is undefined
4775 e.adb:8:12: "V" is undefined
4776 e.adb:8:16: "V" is undefined
4777 e.adb:9:07: "V" is undefined
4778 e.adb:9:12: "V" is undefined
4779 @end smallexample
4780
4781 @noindent
4782 The @option{-gnatf} switch also generates additional information for
4783 some error messages.  Some examples are:
4784
4785 @itemize @bullet
4786 @item
4787 Full details on entities not available in high integrity mode
4788 @item
4789 Details on possibly non-portable unchecked conversion
4790 @item
4791 List possible interpretations for ambiguous calls
4792 @item
4793 Additional details on incorrect parameters
4794 @end itemize
4795
4796 @item -gnatjnn
4797 @cindex @option{-gnatjnn} (@command{gcc})
4798 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4799 with continuation lines are treated as though the continuation lines were
4800 separate messages (and so a warning with two continuation lines counts as
4801 three warnings, and is listed as three separate messages).
4802
4803 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4804 messages are output in a different manner. A message and all its continuation
4805 lines are treated as a unit, and count as only one warning or message in the
4806 statistics totals. Furthermore, the message is reformatted so that no line
4807 is longer than nn characters.
4808
4809 @item -gnatq
4810 @cindex @option{-gnatq} (@command{gcc})
4811 @ifclear vms
4812 The @code{q} stands for quit (really ``don't quit'').
4813 @end ifclear
4814 In normal operation mode, the compiler first parses the program and
4815 determines if there are any syntax errors. If there are, appropriate
4816 error messages are generated and compilation is immediately terminated.
4817 This switch tells
4818 GNAT to continue with semantic analysis even if syntax errors have been
4819 found. This may enable the detection of more errors in a single run. On
4820 the other hand, the semantic analyzer is more likely to encounter some
4821 internal fatal error when given a syntactically invalid tree.
4822
4823 @item -gnatQ
4824 @cindex @option{-gnatQ} (@command{gcc})
4825 In normal operation mode, the @file{ALI} file is not generated if any
4826 illegalities are detected in the program. The use of @option{-gnatQ} forces
4827 generation of the @file{ALI} file. This file is marked as being in
4828 error, so it cannot be used for binding purposes, but it does contain
4829 reasonably complete cross-reference information, and thus may be useful
4830 for use by tools (e.g., semantic browsing tools or integrated development
4831 environments) that are driven from the @file{ALI} file. This switch
4832 implies @option{-gnatq}, since the semantic phase must be run to get a
4833 meaningful ALI file.
4834
4835 In addition, if @option{-gnatt} is also specified, then the tree file is
4836 generated even if there are illegalities. It may be useful in this case
4837 to also specify @option{-gnatq} to ensure that full semantic processing
4838 occurs. The resulting tree file can be processed by ASIS, for the purpose
4839 of providing partial information about illegal units, but if the error
4840 causes the tree to be badly malformed, then ASIS may crash during the
4841 analysis.
4842
4843 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4844 being in error, @command{gnatmake} will attempt to recompile the source when it
4845 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4846
4847 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4848 since ALI files are never generated if @option{-gnats} is set.
4849
4850 @end table
4851
4852 @node Warning Message Control
4853 @subsection Warning Message Control
4854 @cindex Warning messages
4855 @noindent
4856 In addition to error messages, which correspond to illegalities as defined
4857 in the Ada Reference Manual, the compiler detects two kinds of warning
4858 situations.
4859
4860 First, the compiler considers some constructs suspicious and generates a
4861 warning message to alert you to a possible error. Second, if the
4862 compiler detects a situation that is sure to raise an exception at
4863 run time, it generates a warning message. The following shows an example
4864 of warning messages:
4865 @smallexample
4866 e.adb:4:24: warning: creation of object may raise Storage_Error
4867 e.adb:10:17: warning: static value out of range
4868 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4869 @end smallexample
4870
4871 @noindent
4872 GNAT considers a large number of situations as appropriate
4873 for the generation of warning messages. As always, warnings are not
4874 definite indications of errors. For example, if you do an out-of-range
4875 assignment with the deliberate intention of raising a
4876 @code{Constraint_Error} exception, then the warning that may be
4877 issued does not indicate an error. Some of the situations for which GNAT
4878 issues warnings (at least some of the time) are given in the following
4879 list. This list is not complete, and new warnings are often added to
4880 subsequent versions of GNAT. The list is intended to give a general idea
4881 of the kinds of warnings that are generated.
4882
4883 @itemize @bullet
4884 @item
4885 Possible infinitely recursive calls
4886
4887 @item
4888 Out-of-range values being assigned
4889
4890 @item
4891 Possible order of elaboration problems
4892
4893 @item
4894 Assertions (pragma Assert) that are sure to fail
4895
4896 @item
4897 Unreachable code
4898
4899 @item
4900 Address clauses with possibly unaligned values, or where an attempt is
4901 made to overlay a smaller variable with a larger one.
4902
4903 @item
4904 Fixed-point type declarations with a null range
4905
4906 @item
4907 Direct_IO or Sequential_IO instantiated with a type that has access values
4908
4909 @item
4910 Variables that are never assigned a value
4911
4912 @item
4913 Variables that are referenced before being initialized
4914
4915 @item
4916 Task entries with no corresponding @code{accept} statement
4917
4918 @item
4919 Duplicate accepts for the same task entry in a @code{select}
4920
4921 @item
4922 Objects that take too much storage
4923
4924 @item
4925 Unchecked conversion between types of differing sizes
4926
4927 @item
4928 Missing @code{return} statement along some execution path in a function
4929
4930 @item
4931 Incorrect (unrecognized) pragmas
4932
4933 @item
4934 Incorrect external names
4935
4936 @item
4937 Allocation from empty storage pool
4938
4939 @item
4940 Potentially blocking operation in protected type
4941
4942 @item
4943 Suspicious parenthesization of expressions
4944
4945 @item
4946 Mismatching bounds in an aggregate
4947
4948 @item
4949 Attempt to return local value by reference
4950
4951 @item
4952 Premature instantiation of a generic body
4953
4954 @item
4955 Attempt to pack aliased components
4956
4957 @item
4958 Out of bounds array subscripts
4959
4960 @item
4961 Wrong length on string assignment
4962
4963 @item
4964 Violations of style rules if style checking is enabled
4965
4966 @item
4967 Unused @code{with} clauses
4968
4969 @item
4970 @code{Bit_Order} usage that does not have any effect
4971
4972 @item
4973 @code{Standard.Duration} used to resolve universal fixed expression
4974
4975 @item
4976 Dereference of possibly null value
4977
4978 @item
4979 Declaration that is likely to cause storage error
4980
4981 @item
4982 Internal GNAT unit @code{with}'ed by application unit
4983
4984 @item
4985 Values known to be out of range at compile time
4986
4987 @item
4988 Unreferenced labels and variables
4989
4990 @item
4991 Address overlays that could clobber memory
4992
4993 @item
4994 Unexpected initialization when address clause present
4995
4996 @item
4997 Bad alignment for address clause
4998
4999 @item
5000 Useless type conversions
5001
5002 @item
5003 Redundant assignment statements and other redundant constructs
5004
5005 @item
5006 Useless exception handlers
5007
5008 @item
5009 Accidental hiding of name by child unit
5010
5011 @item
5012 Access before elaboration detected at compile time
5013
5014 @item
5015 A range in a @code{for} loop that is known to be null or might be null
5016
5017 @end itemize
5018
5019 @noindent
5020 The following section lists compiler switches that are available
5021 to control the handling of warning messages. It is also possible
5022 to exercise much finer control over what warnings are issued and
5023 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5024 gnat_rm, GNAT Reference manual}.
5025
5026 @table @option
5027 @c !sort!
5028 @item -gnatwa
5029 @emph{Activate all optional errors.}
5030 @cindex @option{-gnatwa} (@command{gcc})
5031 This switch activates most optional warning messages, see remaining list
5032 in this section for details on optional warning messages that can be
5033 individually controlled.  The warnings that are not turned on by this
5034 switch are
5035 @option{-gnatwd} (implicit dereferencing),
5036 @option{-gnatwh} (hiding),
5037 @option{-gnatwl} (elaboration warnings),
5038 @option{-gnatw.o} (warn on values set by out parameters ignored)
5039 and @option{-gnatwt} (tracking of deleted conditional code).
5040 All other optional warnings are turned on.
5041
5042 @item -gnatwA
5043 @emph{Suppress all optional errors.}
5044 @cindex @option{-gnatwA} (@command{gcc})
5045 This switch suppresses all optional warning messages, see remaining list
5046 in this section for details on optional warning messages that can be
5047 individually controlled.
5048
5049 @item -gnatw.a
5050 @emph{Activate warnings on failing assertions.}
5051 @cindex @option{-gnatw.a} (@command{gcc})
5052 @cindex Assert failures
5053 This switch activates warnings for assertions where the compiler can tell at
5054 compile time that the assertion will fail. Note that this warning is given
5055 even if assertions are disabled. The default is that such warnings are
5056 generated.
5057
5058 @item -gnatw.A
5059 @emph{Suppress warnings on failing assertions.}
5060 @cindex @option{-gnatw.A} (@command{gcc})
5061 @cindex Assert failures
5062 This switch suppresses warnings for assertions where the compiler can tell at
5063 compile time that the assertion will fail.
5064
5065 @item -gnatwb
5066 @emph{Activate warnings on bad fixed values.}
5067 @cindex @option{-gnatwb} (@command{gcc})
5068 @cindex Bad fixed values
5069 @cindex Fixed-point Small value
5070 @cindex Small value
5071 This switch activates warnings for static fixed-point expressions whose
5072 value is not an exact multiple of Small. Such values are implementation
5073 dependent, since an implementation is free to choose either of the multiples
5074 that surround the value. GNAT always chooses the closer one, but this is not
5075 required behavior, and it is better to specify a value that is an exact
5076 multiple, ensuring predictable execution. The default is that such warnings
5077 are not generated.
5078
5079 @item -gnatwB
5080 @emph{Suppress warnings on bad fixed values.}
5081 @cindex @option{-gnatwB} (@command{gcc})
5082 This switch suppresses warnings for static fixed-point expressions whose
5083 value is not an exact multiple of Small.
5084
5085 @item -gnatw.b
5086 @emph{Activate warnings on biased representation.}
5087 @cindex @option{-gnatw.b} (@command{gcc})
5088 @cindex Biased representation
5089 This switch activates warnings when a size clause, value size clause, component
5090 clause, or component size clause forces the use of biased representation for an
5091 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5092 to represent 10/11). The default is that such warnings are generated.
5093
5094 @item -gnatw.B
5095 @emph{Suppress warnings on biased representation.}
5096 @cindex @option{-gnatwB} (@command{gcc})
5097 This switch suppresses warnings for representation clauses that force the use
5098 of biased representation.
5099
5100 @item -gnatwc
5101 @emph{Activate warnings on conditionals.}
5102 @cindex @option{-gnatwc} (@command{gcc})
5103 @cindex Conditionals, constant
5104 This switch activates warnings for conditional expressions used in
5105 tests that are known to be True or False at compile time. The default
5106 is that such warnings are not generated.
5107 Note that this warning does
5108 not get issued for the use of boolean variables or constants whose
5109 values are known at compile time, since this is a standard technique
5110 for conditional compilation in Ada, and this would generate too many
5111 false positive warnings.
5112
5113 This warning option also activates a special test for comparisons using
5114 the operators ``>='' and`` <=''.
5115 If the compiler can tell that only the equality condition is possible,
5116 then it will warn that the ``>'' or ``<'' part of the test
5117 is useless and that the operator could be replaced by ``=''.
5118 An example would be comparing a @code{Natural} variable <= 0.
5119
5120 This warning option also generates warnings if
5121 one or both tests is optimized away in a membership test for integer
5122 values if the result can be determined at compile time. Range tests on
5123 enumeration types are not included, since it is common for such tests
5124 to include an end point.
5125
5126 This warning can also be turned on using @option{-gnatwa}.
5127
5128 @item -gnatwC
5129 @emph{Suppress warnings on conditionals.}
5130 @cindex @option{-gnatwC} (@command{gcc})
5131 This switch suppresses warnings for conditional expressions used in
5132 tests that are known to be True or False at compile time.
5133
5134 @item -gnatw.c
5135 @emph{Activate warnings on missing component clauses.}
5136 @cindex @option{-gnatw.c} (@command{gcc})
5137 @cindex Component clause, missing
5138 This switch activates warnings for record components where a record
5139 representation clause is present and has component clauses for the
5140 majority, but not all, of the components. A warning is given for each
5141 component for which no component clause is present.
5142
5143 This warning can also be turned on using @option{-gnatwa}.
5144
5145 @item -gnatw.C
5146 @emph{Suppress warnings on missing component clauses.}
5147 @cindex @option{-gnatwC} (@command{gcc})
5148 This switch suppresses warnings for record components that are
5149 missing a component clause in the situation described above.
5150
5151 @item -gnatwd
5152 @emph{Activate warnings on implicit dereferencing.}
5153 @cindex @option{-gnatwd} (@command{gcc})
5154 If this switch is set, then the use of a prefix of an access type
5155 in an indexed component, slice, or selected component without an
5156 explicit @code{.all} will generate a warning. With this warning
5157 enabled, access checks occur only at points where an explicit
5158 @code{.all} appears in the source code (assuming no warnings are
5159 generated as a result of this switch). The default is that such
5160 warnings are not generated.
5161 Note that @option{-gnatwa} does not affect the setting of
5162 this warning option.
5163
5164 @item -gnatwD
5165 @emph{Suppress warnings on implicit dereferencing.}
5166 @cindex @option{-gnatwD} (@command{gcc})
5167 @cindex Implicit dereferencing
5168 @cindex Dereferencing, implicit
5169 This switch suppresses warnings for implicit dereferences in
5170 indexed components, slices, and selected components.
5171
5172 @item -gnatwe
5173 @emph{Treat warnings as errors.}
5174 @cindex @option{-gnatwe} (@command{gcc})
5175 @cindex Warnings, treat as error
5176 This switch causes warning messages to be treated as errors.
5177 The warning string still appears, but the warning messages are counted
5178 as errors, and prevent the generation of an object file.
5179
5180 @item -gnatw.e
5181 @emph{Activate every optional warning}
5182 @cindex @option{-gnatw.e} (@command{gcc})
5183 @cindex Warnings, activate every optional warning
5184 This switch activates all optional warnings, including those which
5185 are not activated by @code{-gnatwa}.
5186
5187 @item -gnatwf
5188 @emph{Activate warnings on unreferenced formals.}
5189 @cindex @option{-gnatwf} (@command{gcc})
5190 @cindex Formals, unreferenced
5191 This switch causes a warning to be generated if a formal parameter
5192 is not referenced in the body of the subprogram. This warning can
5193 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5194 default is that these warnings are not generated.
5195
5196 @item -gnatwF
5197 @emph{Suppress warnings on unreferenced formals.}
5198 @cindex @option{-gnatwF} (@command{gcc})
5199 This switch suppresses warnings for unreferenced formal
5200 parameters. Note that the
5201 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5202 effect of warning on unreferenced entities other than subprogram
5203 formals.
5204
5205 @item -gnatwg
5206 @emph{Activate warnings on unrecognized pragmas.}
5207 @cindex @option{-gnatwg} (@command{gcc})
5208 @cindex Pragmas, unrecognized
5209 This switch causes a warning to be generated if an unrecognized
5210 pragma is encountered. Apart from issuing this warning, the
5211 pragma is ignored and has no effect. This warning can
5212 also be turned on using @option{-gnatwa}. The default
5213 is that such warnings are issued (satisfying the Ada Reference
5214 Manual requirement that such warnings appear).
5215
5216 @item -gnatwG
5217 @emph{Suppress warnings on unrecognized pragmas.}
5218 @cindex @option{-gnatwG} (@command{gcc})
5219 This switch suppresses warnings for unrecognized pragmas.
5220
5221 @item -gnatwh
5222 @emph{Activate warnings on hiding.}
5223 @cindex @option{-gnatwh} (@command{gcc})
5224 @cindex Hiding of Declarations
5225 This switch activates warnings on hiding declarations.
5226 A declaration is considered hiding
5227 if it is for a non-overloadable entity, and it declares an entity with the
5228 same name as some other entity that is directly or use-visible. The default
5229 is that such warnings are not generated.
5230 Note that @option{-gnatwa} does not affect the setting of this warning option.
5231
5232 @item -gnatwH
5233 @emph{Suppress warnings on hiding.}
5234 @cindex @option{-gnatwH} (@command{gcc})
5235 This switch suppresses warnings on hiding declarations.
5236
5237 @item -gnatwi
5238 @emph{Activate warnings on implementation units.}
5239 @cindex @option{-gnatwi} (@command{gcc})
5240 This switch activates warnings for a @code{with} of an internal GNAT
5241 implementation unit, defined as any unit from the @code{Ada},
5242 @code{Interfaces}, @code{GNAT},
5243 ^^@code{DEC},^ or @code{System}
5244 hierarchies that is not
5245 documented in either the Ada Reference Manual or the GNAT
5246 Programmer's Reference Manual. Such units are intended only
5247 for internal implementation purposes and should not be @code{with}'ed
5248 by user programs. The default is that such warnings are generated
5249 This warning can also be turned on using @option{-gnatwa}.
5250
5251 @item -gnatwI
5252 @emph{Disable warnings on implementation units.}
5253 @cindex @option{-gnatwI} (@command{gcc})
5254 This switch disables warnings for a @code{with} of an internal GNAT
5255 implementation unit.
5256
5257 @item -gnatwj
5258 @emph{Activate warnings on obsolescent features (Annex J).}
5259 @cindex @option{-gnatwj} (@command{gcc})
5260 @cindex Features, obsolescent
5261 @cindex Obsolescent features
5262 If this warning option is activated, then warnings are generated for
5263 calls to subprograms marked with @code{pragma Obsolescent} and
5264 for use of features in Annex J of the Ada Reference Manual. In the
5265 case of Annex J, not all features are flagged. In particular use
5266 of the renamed packages (like @code{Text_IO}) and use of package
5267 @code{ASCII} are not flagged, since these are very common and
5268 would generate many annoying positive warnings. The default is that
5269 such warnings are not generated. This warning is also turned on by
5270 the use of @option{-gnatwa}.
5271
5272 In addition to the above cases, warnings are also generated for
5273 GNAT features that have been provided in past versions but which
5274 have been superseded (typically by features in the new Ada standard).
5275 For example, @code{pragma Ravenscar} will be flagged since its
5276 function is replaced by @code{pragma Profile(Ravenscar)}.
5277
5278 Note that this warning option functions differently from the
5279 restriction @code{No_Obsolescent_Features} in two respects.
5280 First, the restriction applies only to annex J features.
5281 Second, the restriction does flag uses of package @code{ASCII}.
5282
5283 @item -gnatwJ
5284 @emph{Suppress warnings on obsolescent features (Annex J).}
5285 @cindex @option{-gnatwJ} (@command{gcc})
5286 This switch disables warnings on use of obsolescent features.
5287
5288 @item -gnatwk
5289 @emph{Activate warnings on variables that could be constants.}
5290 @cindex @option{-gnatwk} (@command{gcc})
5291 This switch activates warnings for variables that are initialized but
5292 never modified, and then could be declared constants. The default is that
5293 such warnings are not given.
5294 This warning can also be turned on using @option{-gnatwa}.
5295
5296 @item -gnatwK
5297 @emph{Suppress warnings on variables that could be constants.}
5298 @cindex @option{-gnatwK} (@command{gcc})
5299 This switch disables warnings on variables that could be declared constants.
5300
5301 @item -gnatwl
5302 @emph{Activate warnings for elaboration pragmas.}
5303 @cindex @option{-gnatwl} (@command{gcc})
5304 @cindex Elaboration, warnings
5305 This switch activates warnings on missing
5306 @code{Elaborate_All} and @code{Elaborate} pragmas.
5307 See the section in this guide on elaboration checking for details on
5308 when such pragmas should be used. In dynamic elaboration mode, this switch
5309 generations warnings about the need to add elaboration pragmas. Note however,
5310 that if you blindly follow these warnings, and add @code{Elaborate_All}
5311 warnings wherever they are recommended, you basically end up with the
5312 equivalent of the static elaboration model, which may not be what you want for
5313 legacy code for which the static model does not work.
5314
5315 For the static model, the messages generated are labeled "info:" (for
5316 information messages). They are not warnings to add elaboration pragmas,
5317 merely informational messages showing what implicit elaboration pragmas
5318 have been added, for use in analyzing elaboration circularity problems.
5319
5320 Warnings are also generated if you
5321 are using the static mode of elaboration, and a @code{pragma Elaborate}
5322 is encountered. The default is that such warnings
5323 are not generated.
5324 This warning is not automatically turned on by the use of @option{-gnatwa}.
5325
5326 @item -gnatwL
5327 @emph{Suppress warnings for elaboration pragmas.}
5328 @cindex @option{-gnatwL} (@command{gcc})
5329 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5330 See the section in this guide on elaboration checking for details on
5331 when such pragmas should be used.
5332
5333 @item -gnatwm
5334 @emph{Activate warnings on modified but unreferenced variables.}
5335 @cindex @option{-gnatwm} (@command{gcc})
5336 This switch activates warnings for variables that are assigned (using
5337 an initialization value or with one or more assignment statements) but
5338 whose value is never read. The warning is suppressed for volatile
5339 variables and also for variables that are renamings of other variables
5340 or for which an address clause is given.
5341 This warning can also be turned on using @option{-gnatwa}.
5342 The default is that these warnings are not given.
5343
5344 @item -gnatwM
5345 @emph{Disable warnings on modified but unreferenced variables.}
5346 @cindex @option{-gnatwM} (@command{gcc})
5347 This switch disables warnings for variables that are assigned or
5348 initialized, but never read.
5349
5350 @item -gnatwn
5351 @emph{Set normal warnings mode.}
5352 @cindex @option{-gnatwn} (@command{gcc})
5353 This switch sets normal warning mode, in which enabled warnings are
5354 issued and treated as warnings rather than errors. This is the default
5355 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5356 an explicit @option{-gnatws} or
5357 @option{-gnatwe}. It also cancels the effect of the
5358 implicit @option{-gnatwe} that is activated by the
5359 use of @option{-gnatg}.
5360
5361 @item -gnatwo
5362 @emph{Activate warnings on address clause overlays.}
5363 @cindex @option{-gnatwo} (@command{gcc})
5364 @cindex Address Clauses, warnings
5365 This switch activates warnings for possibly unintended initialization
5366 effects of defining address clauses that cause one variable to overlap
5367 another. The default is that such warnings are generated.
5368 This warning can also be turned on using @option{-gnatwa}.
5369
5370 @item -gnatwO
5371 @emph{Suppress warnings on address clause overlays.}
5372 @cindex @option{-gnatwO} (@command{gcc})
5373 This switch suppresses warnings on possibly unintended initialization
5374 effects of defining address clauses that cause one variable to overlap
5375 another.
5376
5377 @item -gnatw.o
5378 @emph{Activate warnings on modified but unreferenced out parameters.}
5379 @cindex @option{-gnatw.o} (@command{gcc})
5380 This switch activates warnings for variables that are modified by using
5381 them as actuals for a call to a procedure with an out mode formal, where
5382 the resulting assigned value is never read. It is applicable in the case
5383 where there is more than one out mode formal. If there is only one out
5384 mode formal, the warning is issued by default (controlled by -gnatwu).
5385 The warning is suppressed for volatile
5386 variables and also for variables that are renamings of other variables
5387 or for which an address clause is given.
5388 The default is that these warnings are not given. Note that this warning
5389 is not included in -gnatwa, it must be activated explicitly.
5390
5391 @item -gnatw.O
5392 @emph{Disable warnings on modified but unreferenced out parameters.}
5393 @cindex @option{-gnatw.O} (@command{gcc})
5394 This switch suppresses warnings for variables that are modified by using
5395 them as actuals for a call to a procedure with an out mode formal, where
5396 the resulting assigned value is never read.
5397
5398 @item -gnatwp
5399 @emph{Activate warnings on ineffective pragma Inlines.}
5400 @cindex @option{-gnatwp} (@command{gcc})
5401 @cindex Inlining, warnings
5402 This switch activates warnings for failure of front end inlining
5403 (activated by @option{-gnatN}) to inline a particular call. There are
5404 many reasons for not being able to inline a call, including most
5405 commonly that the call is too complex to inline. The default is
5406 that such warnings are not given.
5407 This warning can also be turned on using @option{-gnatwa}.
5408 Warnings on ineffective inlining by the gcc back-end can be activated
5409 separately, using the gcc switch -Winline.
5410
5411 @item -gnatwP
5412 @emph{Suppress warnings on ineffective pragma Inlines.}
5413 @cindex @option{-gnatwP} (@command{gcc})
5414 This switch suppresses warnings on ineffective pragma Inlines. If the
5415 inlining mechanism cannot inline a call, it will simply ignore the
5416 request silently.
5417
5418 @item -gnatw.p
5419 @emph{Activate warnings on parameter ordering.}
5420 @cindex @option{-gnatw.p} (@command{gcc})
5421 @cindex Parameter order, warnings
5422 This switch activates warnings for cases of suspicious parameter
5423 ordering when the list of arguments are all simple identifiers that
5424 match the names of the formals, but are in a different order. The
5425 warning is suppressed if any use of named parameter notation is used,
5426 so this is the appropriate way to suppress a false positive (and
5427 serves to emphasize that the "misordering" is deliberate). The
5428 default is
5429 that such warnings are not given.
5430 This warning can also be turned on using @option{-gnatwa}.
5431
5432 @item -gnatw.P
5433 @emph{Suppress warnings on parameter ordering.}
5434 @cindex @option{-gnatw.P} (@command{gcc})
5435 This switch suppresses warnings on cases of suspicious parameter
5436 ordering.
5437
5438 @item -gnatwq
5439 @emph{Activate warnings on questionable missing parentheses.}
5440 @cindex @option{-gnatwq} (@command{gcc})
5441 @cindex Parentheses, warnings
5442 This switch activates warnings for cases where parentheses are not used and
5443 the result is potential ambiguity from a readers point of view. For example
5444 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5445 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5446 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5447 follow the rule of always parenthesizing to make the association clear, and
5448 this warning switch warns if such parentheses are not present. The default
5449 is that these warnings are given.
5450 This warning can also be turned on using @option{-gnatwa}.
5451
5452 @item -gnatwQ
5453 @emph{Suppress warnings on questionable missing parentheses.}
5454 @cindex @option{-gnatwQ} (@command{gcc})
5455 This switch suppresses warnings for cases where the association is not
5456 clear and the use of parentheses is preferred.
5457
5458 @item -gnatwr
5459 @emph{Activate warnings on redundant constructs.}
5460 @cindex @option{-gnatwr} (@command{gcc})
5461 This switch activates warnings for redundant constructs. The following
5462 is the current list of constructs regarded as redundant:
5463
5464 @itemize @bullet
5465 @item
5466 Assignment of an item to itself.
5467 @item
5468 Type conversion that converts an expression to its own type.
5469 @item
5470 Use of the attribute @code{Base} where @code{typ'Base} is the same
5471 as @code{typ}.
5472 @item
5473 Use of pragma @code{Pack} when all components are placed by a record
5474 representation clause.
5475 @item
5476 Exception handler containing only a reraise statement (raise with no
5477 operand) which has no effect.
5478 @item
5479 Use of the operator abs on an operand that is known at compile time
5480 to be non-negative
5481 @item
5482 Comparison of boolean expressions to an explicit True value.
5483 @end itemize
5484
5485 This warning can also be turned on using @option{-gnatwa}.
5486 The default is that warnings for redundant constructs are not given.
5487
5488 @item -gnatwR
5489 @emph{Suppress warnings on redundant constructs.}
5490 @cindex @option{-gnatwR} (@command{gcc})
5491 This switch suppresses warnings for redundant constructs.
5492
5493 @item -gnatw.r
5494 @emph{Activate warnings for object renaming function.}
5495 @cindex @option{-gnatw.r} (@command{gcc})
5496 This switch activates warnings for an object renaming that renames a
5497 function call, which is equivalent to a constant declaration (as
5498 opposed to renaming the function itself).  The default is that these
5499 warnings are given.  This warning can also be turned on using
5500 @option{-gnatwa}.
5501
5502 @item -gnatw.R
5503 @emph{Suppress warnings for object renaming function.}
5504 @cindex @option{-gnatwT} (@command{gcc})
5505 This switch suppresses warnings for object renaming function.
5506
5507 @item -gnatws
5508 @emph{Suppress all warnings.}
5509 @cindex @option{-gnatws} (@command{gcc})
5510 This switch completely suppresses the
5511 output of all warning messages from the GNAT front end.
5512 Note that it does not suppress warnings from the @command{gcc} back end.
5513 To suppress these back end warnings as well, use the switch @option{-w}
5514 in addition to @option{-gnatws}.
5515
5516 @item -gnatwt
5517 @emph{Activate warnings for tracking of deleted conditional code.}
5518 @cindex @option{-gnatwt} (@command{gcc})
5519 @cindex Deactivated code, warnings
5520 @cindex Deleted code, warnings
5521 This switch activates warnings for tracking of code in conditionals (IF and
5522 CASE statements) that is detected to be dead code which cannot be executed, and
5523 which is removed by the front end. This warning is off by default, and is not
5524 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5525 useful for detecting deactivated code in certified applications.
5526
5527 @item -gnatwT
5528 @emph{Suppress warnings for tracking of deleted conditional code.}
5529 @cindex @option{-gnatwT} (@command{gcc})
5530 This switch suppresses warnings for tracking of deleted conditional code.
5531
5532 @item -gnatwu
5533 @emph{Activate warnings on unused entities.}
5534 @cindex @option{-gnatwu} (@command{gcc})
5535 This switch activates warnings to be generated for entities that
5536 are declared but not referenced, and for units that are @code{with}'ed
5537 and not
5538 referenced. In the case of packages, a warning is also generated if
5539 no entities in the package are referenced. This means that if the package
5540 is referenced but the only references are in @code{use}
5541 clauses or @code{renames}
5542 declarations, a warning is still generated. A warning is also generated
5543 for a generic package that is @code{with}'ed but never instantiated.
5544 In the case where a package or subprogram body is compiled, and there
5545 is a @code{with} on the corresponding spec
5546 that is only referenced in the body,
5547 a warning is also generated, noting that the
5548 @code{with} can be moved to the body. The default is that
5549 such warnings are not generated.
5550 This switch also activates warnings on unreferenced formals
5551 (it includes the effect of @option{-gnatwf}).
5552 This warning can also be turned on using @option{-gnatwa}.
5553
5554 @item -gnatwU
5555 @emph{Suppress warnings on unused entities.}
5556 @cindex @option{-gnatwU} (@command{gcc})
5557 This switch suppresses warnings for unused entities and packages.
5558 It also turns off warnings on unreferenced formals (and thus includes
5559 the effect of @option{-gnatwF}).
5560
5561 @item -gnatwv
5562 @emph{Activate warnings on unassigned variables.}
5563 @cindex @option{-gnatwv} (@command{gcc})
5564 @cindex Unassigned variable warnings
5565 This switch activates warnings for access to variables which
5566 may not be properly initialized. The default is that
5567 such warnings are generated.
5568 This warning can also be turned on using @option{-gnatwa}.
5569
5570 @item -gnatwV
5571 @emph{Suppress warnings on unassigned variables.}
5572 @cindex @option{-gnatwV} (@command{gcc})
5573 This switch suppresses warnings for access to variables which
5574 may not be properly initialized.
5575 For variables of a composite type, the warning can also be suppressed in
5576 Ada 2005 by using a default initialization with a box. For example, if
5577 Table is an array of records whose components are only partially uninitialized,
5578 then the following code:
5579
5580 @smallexample @c ada
5581    Tab : Table := (others => <>);
5582 @end smallexample
5583
5584 will suppress warnings on subsequent statements that access components
5585 of variable Tab.
5586
5587 @item -gnatww
5588 @emph{Activate warnings on wrong low bound assumption.}
5589 @cindex @option{-gnatww} (@command{gcc})
5590 @cindex String indexing warnings
5591 This switch activates warnings for indexing an unconstrained string parameter
5592 with a literal or S'Length. This is a case where the code is assuming that the
5593 low bound is one, which is in general not true (for example when a slice is
5594 passed). The default is that such warnings are generated.
5595 This warning can also be turned on using @option{-gnatwa}.
5596
5597 @item -gnatwW
5598 @emph{Suppress warnings on wrong low bound assumption.}
5599 @cindex @option{-gnatwW} (@command{gcc})
5600 This switch suppresses warnings for indexing an unconstrained string parameter
5601 with a literal or S'Length. Note that this warning can also be suppressed
5602 in a particular case by adding an
5603 assertion that the lower bound is 1,
5604 as shown in the following example.
5605
5606 @smallexample @c ada
5607    procedure K (S : String) is
5608       pragma Assert (S'First = 1);
5609       @dots{}
5610 @end smallexample
5611
5612 @item -gnatw.w
5613 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5614 @cindex @option{-gnatw.w} (@command{gcc})
5615 @cindex Warnings Off control
5616 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5617 where either the pragma is entirely useless (because it suppresses no
5618 warnings), or it could be replaced by @code{pragma Unreferenced} or
5619 @code{pragma Unmodified}.The default is that these warnings are not given.
5620 Note that this warning is not included in -gnatwa, it must be
5621 activated explicitly.
5622
5623 @item -gnatw.W
5624 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5625 @cindex @option{-gnatw.W} (@command{gcc})
5626 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5627
5628 @item -gnatwx
5629 @emph{Activate warnings on Export/Import pragmas.}
5630 @cindex @option{-gnatwx} (@command{gcc})
5631 @cindex Export/Import pragma warnings
5632 This switch activates warnings on Export/Import pragmas when
5633 the compiler detects a possible conflict between the Ada and
5634 foreign language calling sequences. For example, the use of
5635 default parameters in a convention C procedure is dubious
5636 because the C compiler cannot supply the proper default, so
5637 a warning is issued. The default is that such warnings are
5638 generated.
5639 This warning can also be turned on using @option{-gnatwa}.
5640
5641 @item -gnatwX
5642 @emph{Suppress warnings on Export/Import pragmas.}
5643 @cindex @option{-gnatwX} (@command{gcc})
5644 This switch suppresses warnings on Export/Import pragmas.
5645 The sense of this is that you are telling the compiler that
5646 you know what you are doing in writing the pragma, and it
5647 should not complain at you.
5648
5649 @item -gnatw.x
5650 @emph{Activate warnings for No_Exception_Propagation mode.}
5651 @cindex @option{-gnatwm} (@command{gcc})
5652 This switch activates warnings for exception usage when pragma Restrictions
5653 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5654 explicit exception raises which are not covered by a local handler, and for
5655 exception handlers which do not cover a local raise. The default is that these
5656 warnings are not given.
5657
5658 @item -gnatw.X
5659 @emph{Disable warnings for No_Exception_Propagation mode.}
5660 This switch disables warnings for exception usage when pragma Restrictions
5661 (No_Exception_Propagation) is in effect.
5662
5663 @item -gnatwy
5664 @emph{Activate warnings for Ada 2005 compatibility issues.}
5665 @cindex @option{-gnatwy} (@command{gcc})
5666 @cindex Ada 2005 compatibility issues warnings
5667 For the most part Ada 2005 is upwards compatible with Ada 95,
5668 but there are some exceptions (for example the fact that
5669 @code{interface} is now a reserved word in Ada 2005). This
5670 switch activates several warnings to help in identifying
5671 and correcting such incompatibilities. The default is that
5672 these warnings are generated. Note that at one point Ada 2005
5673 was called Ada 0Y, hence the choice of character.
5674 This warning can also be turned on using @option{-gnatwa}.
5675
5676 @item -gnatwY
5677 @emph{Disable warnings for Ada 2005 compatibility issues.}
5678 @cindex @option{-gnatwY} (@command{gcc})
5679 @cindex Ada 2005 compatibility issues warnings
5680 This switch suppresses several warnings intended to help in identifying
5681 incompatibilities between Ada 95 and Ada 2005.
5682
5683 @item -gnatwz
5684 @emph{Activate warnings on unchecked conversions.}
5685 @cindex @option{-gnatwz} (@command{gcc})
5686 @cindex Unchecked_Conversion warnings
5687 This switch activates warnings for unchecked conversions
5688 where the types are known at compile time to have different
5689 sizes. The default
5690 is that such warnings are generated. Warnings are also
5691 generated for subprogram pointers with different conventions,
5692 and, on VMS only, for data pointers with different conventions.
5693 This warning can also be turned on using @option{-gnatwa}.
5694
5695 @item -gnatwZ
5696 @emph{Suppress warnings on unchecked conversions.}
5697 @cindex @option{-gnatwZ} (@command{gcc})
5698 This switch suppresses warnings for unchecked conversions
5699 where the types are known at compile time to have different
5700 sizes or conventions.
5701
5702 @item ^-Wunused^WARNINGS=UNUSED^
5703 @cindex @option{-Wunused}
5704 The warnings controlled by the @option{-gnatw} switch are generated by
5705 the front end of the compiler. The @option{GCC} back end can provide
5706 additional warnings and they are controlled by the @option{-W} switch.
5707 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5708 warnings for entities that are declared but not referenced.
5709
5710 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5711 @cindex @option{-Wuninitialized}
5712 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5713 the back end warning for uninitialized variables. This switch must be
5714 used in conjunction with an optimization level greater than zero.
5715
5716 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5717 @cindex @option{-Wall}
5718 This switch enables all the above warnings from the @option{GCC} back end.
5719 The code generator detects a number of warning situations that are missed
5720 by the @option{GNAT} front end, and this switch can be used to activate them.
5721 The use of this switch also sets the default front end warning mode to
5722 @option{-gnatwa}, that is, most front end warnings activated as well.
5723
5724 @item ^-w^/NO_BACK_END_WARNINGS^
5725 @cindex @option{-w}
5726 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5727 The use of this switch also sets the default front end warning mode to
5728 @option{-gnatws}, that is, front end warnings suppressed as well.
5729
5730 @end table
5731
5732 @noindent
5733 @ifclear vms
5734 A string of warning parameters can be used in the same parameter. For example:
5735
5736 @smallexample
5737 -gnatwaLe
5738 @end smallexample
5739
5740 @noindent
5741 will turn on all optional warnings except for elaboration pragma warnings,
5742 and also specify that warnings should be treated as errors.
5743 @end ifclear
5744 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5745
5746 @table @option
5747 @c !sort!
5748 @item -gnatwC
5749 @item -gnatwD
5750 @item -gnatwF
5751 @item -gnatwg
5752 @item -gnatwH
5753 @item -gnatwi
5754 @item -gnatwJ
5755 @item -gnatwK
5756 @item -gnatwL
5757 @item -gnatwM
5758 @item -gnatwn
5759 @item -gnatwo
5760 @item -gnatwP
5761 @item -gnatwR
5762 @item -gnatwU
5763 @item -gnatwv
5764 @item -gnatwz
5765 @item -gnatwx
5766
5767 @end table
5768
5769 @node Debugging and Assertion Control
5770 @subsection Debugging and Assertion Control
5771
5772 @table @option
5773 @item -gnata
5774 @cindex @option{-gnata} (@command{gcc})
5775 @findex Assert
5776 @findex Debug
5777 @cindex Assertions
5778
5779 @noindent
5780 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5781 are ignored. This switch, where @samp{a} stands for assert, causes
5782 @code{Assert} and @code{Debug} pragmas to be activated.
5783
5784 The pragmas have the form:
5785
5786 @smallexample
5787 @cartouche
5788    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5789                       @var{static-string-expression}@r{]})
5790    @b{pragma} Debug (@var{procedure call})
5791 @end cartouche
5792 @end smallexample
5793
5794 @noindent
5795 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5796 If the result is @code{True}, the pragma has no effect (other than
5797 possible side effects from evaluating the expression). If the result is
5798 @code{False}, the exception @code{Assert_Failure} declared in the package
5799 @code{System.Assertions} is
5800 raised (passing @var{static-string-expression}, if present, as the
5801 message associated with the exception). If no string expression is
5802 given the default is a string giving the file name and line number
5803 of the pragma.
5804
5805 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5806 @code{pragma Debug} may appear within a declaration sequence, allowing
5807 debugging procedures to be called between declarations.
5808
5809 @ifset vms
5810 @item /DEBUG@r{[}=debug-level@r{]}
5811 @itemx  /NODEBUG
5812 Specifies how much debugging information is to be included in
5813 the resulting object file where 'debug-level' is one of the following:
5814 @table @code
5815 @item   TRACEBACK
5816 Include both debugger symbol records and traceback
5817 the object file.
5818 This is the default setting.
5819 @item   ALL
5820 Include both debugger symbol records and traceback in
5821 object file.
5822 @item   NONE
5823 Excludes both debugger symbol records and traceback
5824 the object file. Same as /NODEBUG.
5825 @item   SYMBOLS
5826 Includes only debugger symbol records in the object
5827 file. Note that this doesn't include traceback information.
5828 @end table
5829 @end ifset
5830 @end table
5831
5832 @node Validity Checking
5833 @subsection Validity Checking
5834 @findex Validity Checking
5835
5836 @noindent
5837 The Ada Reference Manual has specific requirements for checking
5838 for invalid values. In particular, RM 13.9.1 requires that the
5839 evaluation of invalid values (for example from unchecked conversions),
5840 not result in erroneous execution. In GNAT, the result of such an
5841 evaluation in normal default mode is to either use the value
5842 unmodified, or to raise Constraint_Error in those cases where use
5843 of the unmodified value would cause erroneous execution. The cases
5844 where unmodified values might lead to erroneous execution are case
5845 statements (where a wild jump might result from an invalid value),
5846 and subscripts on the left hand side (where memory corruption could
5847 occur as a result of an invalid value).
5848
5849 The @option{-gnatB} switch tells the compiler to assume that all
5850 values are valid (that is, within their declared subtype range)
5851 except in the context of a use of the Valid attribute. This means
5852 the compiler can generate more efficient code, since the range
5853 of values is better known at compile time.
5854
5855 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5856 checking mode.
5857 @ifclear vms
5858 The @code{x} argument is a string of letters that
5859 indicate validity checks that are performed or not performed in addition
5860 to the default checks described above.
5861 @end ifclear
5862 @ifset vms
5863 The options allowed for this qualifier
5864 indicate validity checks that are performed or not performed in addition
5865 to the default checks described above.
5866 @end ifset
5867
5868 @table @option
5869 @c !sort!
5870 @item -gnatVa
5871 @emph{All validity checks.}
5872 @cindex @option{-gnatVa} (@command{gcc})
5873 All validity checks are turned on.
5874 @ifclear vms
5875 That is, @option{-gnatVa} is
5876 equivalent to @option{gnatVcdfimorst}.
5877 @end ifclear
5878
5879 @item -gnatVc
5880 @emph{Validity checks for copies.}
5881 @cindex @option{-gnatVc} (@command{gcc})
5882 The right hand side of assignments, and the initializing values of
5883 object declarations are validity checked.
5884
5885 @item -gnatVd
5886 @emph{Default (RM) validity checks.}
5887 @cindex @option{-gnatVd} (@command{gcc})
5888 Some validity checks are done by default following normal Ada semantics
5889 (RM 13.9.1 (9-11)).
5890 A check is done in case statements that the expression is within the range
5891 of the subtype. If it is not, Constraint_Error is raised.
5892 For assignments to array components, a check is done that the expression used
5893 as index is within the range. If it is not, Constraint_Error is raised.
5894 Both these validity checks may be turned off using switch @option{-gnatVD}.
5895 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5896 switch @option{-gnatVd} will leave the checks turned on.
5897 Switch @option{-gnatVD} should be used only if you are sure that all such
5898 expressions have valid values. If you use this switch and invalid values
5899 are present, then the program is erroneous, and wild jumps or memory
5900 overwriting may occur.
5901
5902 @item -gnatVe
5903 @emph{Validity checks for elementary components.}
5904 @cindex @option{-gnatVe} (@command{gcc})
5905 In the absence of this switch, assignments to record or array components are
5906 not validity checked, even if validity checks for assignments generally
5907 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5908 require valid data, but assignment of individual components does. So for
5909 example, there is a difference between copying the elements of an array with a
5910 slice assignment, compared to assigning element by element in a loop. This
5911 switch allows you to turn off validity checking for components, even when they
5912 are assigned component by component.
5913
5914 @item -gnatVf
5915 @emph{Validity checks for floating-point values.}
5916 @cindex @option{-gnatVf} (@command{gcc})
5917 In the absence of this switch, validity checking occurs only for discrete
5918 values. If @option{-gnatVf} is specified, then validity checking also applies
5919 for floating-point values, and NaNs and infinities are considered invalid,
5920 as well as out of range values for constrained types. Note that this means
5921 that standard IEEE infinity mode is not allowed. The exact contexts
5922 in which floating-point values are checked depends on the setting of other
5923 options. For example,
5924 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5925 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5926 (the order does not matter) specifies that floating-point parameters of mode
5927 @code{in} should be validity checked.
5928
5929 @item -gnatVi
5930 @emph{Validity checks for @code{in} mode parameters}
5931 @cindex @option{-gnatVi} (@command{gcc})
5932 Arguments for parameters of mode @code{in} are validity checked in function
5933 and procedure calls at the point of call.
5934
5935 @item -gnatVm
5936 @emph{Validity checks for @code{in out} mode parameters.}
5937 @cindex @option{-gnatVm} (@command{gcc})
5938 Arguments for parameters of mode @code{in out} are validity checked in
5939 procedure calls at the point of call. The @code{'m'} here stands for
5940 modify, since this concerns parameters that can be modified by the call.
5941 Note that there is no specific option to test @code{out} parameters,
5942 but any reference within the subprogram will be tested in the usual
5943 manner, and if an invalid value is copied back, any reference to it
5944 will be subject to validity checking.
5945
5946 @item -gnatVn
5947 @emph{No validity checks.}
5948 @cindex @option{-gnatVn} (@command{gcc})
5949 This switch turns off all validity checking, including the default checking
5950 for case statements and left hand side subscripts. Note that the use of
5951 the switch @option{-gnatp} suppresses all run-time checks, including
5952 validity checks, and thus implies @option{-gnatVn}. When this switch
5953 is used, it cancels any other @option{-gnatV} previously issued.
5954
5955 @item -gnatVo
5956 @emph{Validity checks for operator and attribute operands.}
5957 @cindex @option{-gnatVo} (@command{gcc})
5958 Arguments for predefined operators and attributes are validity checked.
5959 This includes all operators in package @code{Standard},
5960 the shift operators defined as intrinsic in package @code{Interfaces}
5961 and operands for attributes such as @code{Pos}. Checks are also made
5962 on individual component values for composite comparisons, and on the
5963 expressions in type conversions and qualified expressions. Checks are
5964 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
5965
5966 @item -gnatVp
5967 @emph{Validity checks for parameters.}
5968 @cindex @option{-gnatVp} (@command{gcc})
5969 This controls the treatment of parameters within a subprogram (as opposed
5970 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5971 of parameters on a call. If either of these call options is used, then
5972 normally an assumption is made within a subprogram that the input arguments
5973 have been validity checking at the point of call, and do not need checking
5974 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5975 is not made, and parameters are not assumed to be valid, so their validity
5976 will be checked (or rechecked) within the subprogram.
5977
5978 @item -gnatVr
5979 @emph{Validity checks for function returns.}
5980 @cindex @option{-gnatVr} (@command{gcc})
5981 The expression in @code{return} statements in functions is validity
5982 checked.
5983
5984 @item -gnatVs
5985 @emph{Validity checks for subscripts.}
5986 @cindex @option{-gnatVs} (@command{gcc})
5987 All subscripts expressions are checked for validity, whether they appear
5988 on the right side or left side (in default mode only left side subscripts
5989 are validity checked).
5990
5991 @item -gnatVt
5992 @emph{Validity checks for tests.}
5993 @cindex @option{-gnatVt} (@command{gcc})
5994 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5995 statements are checked, as well as guard expressions in entry calls.
5996
5997 @end table
5998
5999 @noindent
6000 The @option{-gnatV} switch may be followed by
6001 ^a string of letters^a list of options^
6002 to turn on a series of validity checking options.
6003 For example,
6004 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6005 specifies that in addition to the default validity checking, copies and
6006 function return expressions are to be validity checked.
6007 In order to make it easier
6008 to specify the desired combination of effects,
6009 @ifclear vms
6010 the upper case letters @code{CDFIMORST} may
6011 be used to turn off the corresponding lower case option.
6012 @end ifclear
6013 @ifset vms
6014 the prefix @code{NO} on an option turns off the corresponding validity
6015 checking:
6016 @itemize @bullet
6017 @item @code{NOCOPIES}
6018 @item @code{NODEFAULT}
6019 @item @code{NOFLOATS}
6020 @item @code{NOIN_PARAMS}
6021 @item @code{NOMOD_PARAMS}
6022 @item @code{NOOPERANDS}
6023 @item @code{NORETURNS}
6024 @item @code{NOSUBSCRIPTS}
6025 @item @code{NOTESTS}
6026 @end itemize
6027 @end ifset
6028 Thus
6029 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6030 turns on all validity checking options except for
6031 checking of @code{@b{in out}} procedure arguments.
6032
6033 The specification of additional validity checking generates extra code (and
6034 in the case of @option{-gnatVa} the code expansion can be substantial).
6035 However, these additional checks can be very useful in detecting
6036 uninitialized variables, incorrect use of unchecked conversion, and other
6037 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6038 is useful in conjunction with the extra validity checking, since this
6039 ensures that wherever possible uninitialized variables have invalid values.
6040
6041 See also the pragma @code{Validity_Checks} which allows modification of
6042 the validity checking mode at the program source level, and also allows for
6043 temporary disabling of validity checks.
6044
6045 @node Style Checking
6046 @subsection Style Checking
6047 @findex Style checking
6048
6049 @noindent
6050 The @option{-gnaty^x^(option,option,@dots{})^} switch
6051 @cindex @option{-gnaty} (@command{gcc})
6052 causes the compiler to
6053 enforce specified style rules. A limited set of style rules has been used
6054 in writing the GNAT sources themselves. This switch allows user programs
6055 to activate all or some of these checks. If the source program fails a
6056 specified style check, an appropriate warning message is given, preceded by
6057 the character sequence ``(style)''.
6058 @ifset vms
6059 @code{(option,option,@dots{})} is a sequence of keywords
6060 @end ifset
6061 @ifclear vms
6062 The string @var{x} is a sequence of letters or digits
6063 @end ifclear
6064 indicating the particular style
6065 checks to be performed. The following checks are defined:
6066
6067 @table @option
6068 @c !sort!
6069 @item 0-9
6070 @emph{Specify indentation level.}
6071 If a digit from 1-9 appears
6072 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6073 then proper indentation is checked, with the digit indicating the
6074 indentation level required. A value of zero turns off this style check.
6075 The general style of required indentation is as specified by
6076 the examples in the Ada Reference Manual. Full line comments must be
6077 aligned with the @code{--} starting on a column that is a multiple of
6078 the alignment level, or they may be aligned the same way as the following
6079 non-blank line (this is useful when full line comments appear in the middle
6080 of a statement.
6081
6082 @item ^a^ATTRIBUTE^
6083 @emph{Check attribute casing.}
6084 Attribute names, including the case of keywords such as @code{digits}
6085 used as attributes names, must be written in mixed case, that is, the
6086 initial letter and any letter following an underscore must be uppercase.
6087 All other letters must be lowercase.
6088
6089 @item ^A^ARRAY_INDEXES^
6090 @emph{Use of array index numbers in array attributes.}
6091 When using the array attributes First, Last, Range,
6092 or Length, the index number must be omitted for one-dimensional arrays
6093 and is required for multi-dimensional arrays.
6094
6095 @item ^b^BLANKS^
6096 @emph{Blanks not allowed at statement end.}
6097 Trailing blanks are not allowed at the end of statements. The purpose of this
6098 rule, together with h (no horizontal tabs), is to enforce a canonical format
6099 for the use of blanks to separate source tokens.
6100
6101 @item ^c^COMMENTS^
6102 @emph{Check comments.}
6103 Comments must meet the following set of rules:
6104
6105 @itemize @bullet
6106
6107 @item
6108 The ``@code{--}'' that starts the column must either start in column one,
6109 or else at least one blank must precede this sequence.
6110
6111 @item
6112 Comments that follow other tokens on a line must have at least one blank
6113 following the ``@code{--}'' at the start of the comment.
6114
6115 @item
6116 Full line comments must have two blanks following the ``@code{--}'' that
6117 starts the comment, with the following exceptions.
6118
6119 @item
6120 A line consisting only of the ``@code{--}'' characters, possibly preceded
6121 by blanks is permitted.
6122
6123 @item
6124 A comment starting with ``@code{--x}'' where @code{x} is a special character
6125 is permitted.
6126 This allows proper processing of the output generated by specialized tools
6127 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6128 annotation
6129 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6130 special character is defined as being in one of the ASCII ranges
6131 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6132 Note that this usage is not permitted
6133 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6134
6135 @item
6136 A line consisting entirely of minus signs, possibly preceded by blanks, is
6137 permitted. This allows the construction of box comments where lines of minus
6138 signs are used to form the top and bottom of the box.
6139
6140 @item
6141 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6142 least one blank follows the initial ``@code{--}''. Together with the preceding
6143 rule, this allows the construction of box comments, as shown in the following
6144 example:
6145 @smallexample
6146 ---------------------------
6147 -- This is a box comment --
6148 -- with two text lines.  --
6149 ---------------------------
6150 @end smallexample
6151 @end itemize
6152
6153 @item ^d^DOS_LINE_ENDINGS^
6154 @emph{Check no DOS line terminators present.}
6155 All lines must be terminated by a single ASCII.LF
6156 character (in particular the DOS line terminator sequence CR/LF is not
6157 allowed).
6158
6159 @item ^e^END^
6160 @emph{Check end/exit labels.}
6161 Optional labels on @code{end} statements ending subprograms and on
6162 @code{exit} statements exiting named loops, are required to be present.
6163
6164 @item ^f^VTABS^
6165 @emph{No form feeds or vertical tabs.}
6166 Neither form feeds nor vertical tab characters are permitted
6167 in the source text.
6168
6169 @item ^g^GNAT^
6170 @emph{GNAT style mode}
6171 The set of style check switches is set to match that used by the GNAT sources.
6172 This may be useful when developing code that is eventually intended to be
6173 incorporated into GNAT. For further details, see GNAT sources.
6174
6175 @item ^h^HTABS^
6176 @emph{No horizontal tabs.}
6177 Horizontal tab characters are not permitted in the source text.
6178 Together with the b (no blanks at end of line) check, this
6179 enforces a canonical form for the use of blanks to separate
6180 source tokens.
6181
6182 @item ^i^IF_THEN^
6183 @emph{Check if-then layout.}
6184 The keyword @code{then} must appear either on the same
6185 line as corresponding @code{if}, or on a line on its own, lined
6186 up under the @code{if} with at least one non-blank line in between
6187 containing all or part of the condition to be tested.
6188
6189 @item ^I^IN_MODE^
6190 @emph{check mode IN keywords}
6191 Mode @code{in} (the default mode) is not
6192 allowed to be given explicitly. @code{in out} is fine,
6193 but not @code{in} on its own.
6194
6195 @item ^k^KEYWORD^
6196 @emph{Check keyword casing.}
6197 All keywords must be in lower case (with the exception of keywords
6198 such as @code{digits} used as attribute names to which this check
6199 does not apply).
6200
6201 @item ^l^LAYOUT^
6202 @emph{Check layout.}
6203 Layout of statement and declaration constructs must follow the
6204 recommendations in the Ada Reference Manual, as indicated by the
6205 form of the syntax rules. For example an @code{else} keyword must
6206 be lined up with the corresponding @code{if} keyword.
6207
6208 There are two respects in which the style rule enforced by this check
6209 option are more liberal than those in the Ada Reference Manual. First
6210 in the case of record declarations, it is permissible to put the
6211 @code{record} keyword on the same line as the @code{type} keyword, and
6212 then the @code{end} in @code{end record} must line up under @code{type}.
6213 This is also permitted when the type declaration is split on two lines.
6214 For example, any of the following three layouts is acceptable:
6215
6216 @smallexample @c ada
6217 @cartouche
6218 type q is record
6219    a : integer;
6220    b : integer;
6221 end record;
6222
6223 type q is
6224    record
6225       a : integer;
6226       b : integer;
6227    end record;
6228
6229 type q is
6230    record
6231       a : integer;
6232       b : integer;
6233 end record;
6234
6235 @end cartouche
6236 @end smallexample
6237
6238 @noindent
6239 Second, in the case of a block statement, a permitted alternative
6240 is to put the block label on the same line as the @code{declare} or
6241 @code{begin} keyword, and then line the @code{end} keyword up under
6242 the block label. For example both the following are permitted:
6243
6244 @smallexample @c ada
6245 @cartouche
6246 Block : declare
6247    A : Integer := 3;
6248 begin
6249    Proc (A, A);
6250 end Block;
6251
6252 Block :
6253    declare
6254       A : Integer := 3;
6255    begin
6256       Proc (A, A);
6257    end Block;
6258 @end cartouche
6259 @end smallexample
6260
6261 @noindent
6262 The same alternative format is allowed for loops. For example, both of
6263 the following are permitted:
6264
6265 @smallexample @c ada
6266 @cartouche
6267 Clear : while J < 10 loop
6268    A (J) := 0;
6269 end loop Clear;
6270
6271 Clear :
6272    while J < 10 loop
6273       A (J) := 0;
6274    end loop Clear;
6275 @end cartouche
6276 @end smallexample
6277
6278 @item ^Lnnn^MAX_NESTING=nnn^
6279 @emph{Set maximum nesting level}
6280 The maximum level of nesting of constructs (including subprograms, loops,
6281 blocks, packages, and conditionals) may not exceed the given value
6282 @option{nnn}. A value of zero disconnects this style check.
6283
6284 @item ^m^LINE_LENGTH^
6285 @emph{Check maximum line length.}
6286 The length of source lines must not exceed 79 characters, including
6287 any trailing blanks. The value of 79 allows convenient display on an
6288 80 character wide device or window, allowing for possible special
6289 treatment of 80 character lines. Note that this count is of
6290 characters in the source text. This means that a tab character counts
6291 as one character in this count but a wide character sequence counts as
6292 a single character (however many bytes are needed in the encoding).
6293
6294 @item ^Mnnn^MAX_LENGTH=nnn^
6295 @emph{Set maximum line length.}
6296 The length of lines must not exceed the
6297 given value @option{nnn}. The maximum value that can be specified is 32767.
6298
6299 @item ^n^STANDARD_CASING^
6300 @emph{Check casing of entities in Standard.}
6301 Any identifier from Standard must be cased
6302 to match the presentation in the Ada Reference Manual (for example,
6303 @code{Integer} and @code{ASCII.NUL}).
6304
6305 @item ^N^NONE^
6306 @emph{Turn off all style checks}
6307 All style check options are turned off.
6308
6309 @item ^o^ORDERED_SUBPROGRAMS^
6310 @emph{Check order of subprogram bodies.}
6311 All subprogram bodies in a given scope
6312 (e.g.@: a package body) must be in alphabetical order. The ordering
6313 rule uses normal Ada rules for comparing strings, ignoring casing
6314 of letters, except that if there is a trailing numeric suffix, then
6315 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6316 before Junk10).
6317
6318 @item ^O^OVERRIDING_INDICATORS^
6319 @emph{Check that overriding subprograms are explicitly marked as such.}
6320 The declaration of a primitive operation of a type extension that overrides
6321 an inherited operation must carry an overriding indicator.
6322
6323 @item ^p^PRAGMA^
6324 @emph{Check pragma casing.}
6325 Pragma names must be written in mixed case, that is, the
6326 initial letter and any letter following an underscore must be uppercase.
6327 All other letters must be lowercase.
6328
6329 @item ^r^REFERENCES^
6330 @emph{Check references.}
6331 All identifier references must be cased in the same way as the
6332 corresponding declaration. No specific casing style is imposed on
6333 identifiers. The only requirement is for consistency of references
6334 with declarations.
6335
6336 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6337 @emph{Check no statements after THEN/ELSE.}
6338 No statements are allowed
6339 on the same line as a THEN or ELSE keyword following the
6340 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6341 and a special exception allows a pragma to appear after ELSE.
6342
6343 @item ^s^SPECS^
6344 @emph{Check separate specs.}
6345 Separate declarations (``specs'') are required for subprograms (a
6346 body is not allowed to serve as its own declaration). The only
6347 exception is that parameterless library level procedures are
6348 not required to have a separate declaration. This exception covers
6349 the most frequent form of main program procedures.
6350
6351 @item ^t^TOKEN^
6352 @emph{Check token spacing.}
6353 The following token spacing rules are enforced:
6354
6355 @itemize @bullet
6356
6357 @item
6358 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6359
6360 @item
6361 The token @code{=>} must be surrounded by spaces.
6362
6363 @item
6364 The token @code{<>} must be preceded by a space or a left parenthesis.
6365
6366 @item
6367 Binary operators other than @code{**} must be surrounded by spaces.
6368 There is no restriction on the layout of the @code{**} binary operator.
6369
6370 @item
6371 Colon must be surrounded by spaces.
6372
6373 @item
6374 Colon-equal (assignment, initialization) must be surrounded by spaces.
6375
6376 @item
6377 Comma must be the first non-blank character on the line, or be
6378 immediately preceded by a non-blank character, and must be followed
6379 by a space.
6380
6381 @item
6382 If the token preceding a left parenthesis ends with a letter or digit, then
6383 a space must separate the two tokens.
6384
6385 @item
6386 A right parenthesis must either be the first non-blank character on
6387 a line, or it must be preceded by a non-blank character.
6388
6389 @item
6390 A semicolon must not be preceded by a space, and must not be followed by
6391 a non-blank character.
6392
6393 @item
6394 A unary plus or minus may not be followed by a space.
6395
6396 @item
6397 A vertical bar must be surrounded by spaces.
6398 @end itemize
6399
6400 @item ^u^UNNECESSARY_BLANK_LINES^
6401 @emph{Check unnecessary blank lines.}
6402 Unnecessary blank lines are not allowed. A blank line is considered
6403 unnecessary if it appears at the end of the file, or if more than
6404 one blank line occurs in sequence.
6405
6406 @item ^x^XTRA_PARENS^
6407 @emph{Check extra parentheses.}
6408 Unnecessary extra level of parentheses (C-style) are not allowed
6409 around conditions in @code{if} statements, @code{while} statements and
6410 @code{exit} statements.
6411
6412 @item ^y^ALL_BUILTIN^
6413 @emph{Set all standard style check options}
6414 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6415 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6416 @option{-gnatyS}, @option{-gnatyLnnn},
6417 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6418
6419 @ifclear vms
6420 @item -
6421 @emph{Remove style check options}
6422 This causes any subsequent options in the string to act as canceling the
6423 corresponding style check option. To cancel maximum nesting level control,
6424 use @option{L} parameter witout any integer value after that, because any
6425 digit following @option{-} in the parameter string of the @option{-gnaty}
6426 option will be threated as canceling indentation check. The same is true
6427 for @option{M} parameter. @option{y} and @option{N} parameters are not
6428 allowed after @option{-}.
6429
6430 @item +
6431 This causes any subsequent options in the string to enable the corresponding
6432 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6433 if any.
6434 @end ifclear
6435
6436 @ifset vms
6437 @item NOxxx
6438 @emph{Removing style check options}
6439 If the name of a style check is preceded by @option{NO} then the corresponding
6440 style check is turned off. For example @option{NOCOMMENTS} turns off style
6441 checking for comments.
6442 @end ifset
6443 @end table
6444
6445 @noindent
6446 In the above rules, appearing in column one is always permitted, that is,
6447 counts as meeting either a requirement for a required preceding space,
6448 or as meeting a requirement for no preceding space.
6449
6450 Appearing at the end of a line is also always permitted, that is, counts
6451 as meeting either a requirement for a following space, or as meeting
6452 a requirement for no following space.
6453
6454 @noindent
6455 If any of these style rules is violated, a message is generated giving
6456 details on the violation. The initial characters of such messages are
6457 always ``@code{(style)}''. Note that these messages are treated as warning
6458 messages, so they normally do not prevent the generation of an object
6459 file. The @option{-gnatwe} switch can be used to treat warning messages,
6460 including style messages, as fatal errors.
6461
6462 The switch
6463 @ifclear vms
6464 @option{-gnaty} on its own (that is not
6465 followed by any letters or digits), then the effect is equivalent
6466 to the use of @option{-gnatyy}, as described above, that is all
6467 built-in standard style check options are enabled.
6468
6469 @end ifclear
6470 @ifset vms
6471 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6472 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6473 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6474 @end ifset
6475
6476
6477
6478 The switch
6479 @ifclear vms
6480 @option{-gnatyN}
6481 @end ifclear
6482 @ifset vms
6483 /STYLE_CHECKS=NONE
6484 @end ifset
6485 clears any previously set style checks.
6486
6487 @node Run-Time Checks
6488 @subsection Run-Time Checks
6489 @cindex Division by zero
6490 @cindex Access before elaboration
6491 @cindex Checks, division by zero
6492 @cindex Checks, access before elaboration
6493 @cindex Checks, stack overflow checking
6494
6495 @noindent
6496 By default, the following checks are suppressed: integer overflow
6497 checks, stack overflow checks, and checks for access before
6498 elaboration on subprogram calls. All other checks, including range
6499 checks and array bounds checks, are turned on by default. The
6500 following @command{gcc} switches refine this default behavior.
6501
6502 @table @option
6503 @c !sort!
6504 @item -gnatp
6505 @cindex @option{-gnatp} (@command{gcc})
6506 @cindex Suppressing checks
6507 @cindex Checks, suppressing
6508 @findex Suppress
6509 This switch causes the unit to be compiled
6510 as though @code{pragma Suppress (All_checks)}
6511 had been present in the source. Validity checks are also eliminated (in
6512 other words @option{-gnatp} also implies @option{-gnatVn}.
6513 Use this switch to improve the performance
6514 of the code at the expense of safety in the presence of invalid data or
6515 program bugs.
6516
6517 Note that when checks are suppressed, the compiler is allowed, but not
6518 required, to omit the checking code. If the run-time cost of the
6519 checking code is zero or near-zero, the compiler will generate it even
6520 if checks are suppressed. In particular, if the compiler can prove
6521 that a certain check will necessarily fail, it will generate code to
6522 do an unconditional ``raise'', even if checks are suppressed. The
6523 compiler warns in this case. Another case in which checks may not be
6524 eliminated is when they are embedded in certain run time routines such
6525 as math library routines.
6526
6527 Of course, run-time checks are omitted whenever the compiler can prove
6528 that they will not fail, whether or not checks are suppressed.
6529
6530 Note that if you suppress a check that would have failed, program
6531 execution is erroneous, which means the behavior is totally
6532 unpredictable. The program might crash, or print wrong answers, or
6533 do anything else. It might even do exactly what you wanted it to do
6534 (and then it might start failing mysteriously next week or next
6535 year). The compiler will generate code based on the assumption that
6536 the condition being checked is true, which can result in disaster if
6537 that assumption is wrong.
6538
6539 @item -gnato
6540 @cindex @option{-gnato} (@command{gcc})
6541 @cindex Overflow checks
6542 @cindex Check, overflow
6543 Enables overflow checking for integer operations.
6544 This causes GNAT to generate slower and larger executable
6545 programs by adding code to check for overflow (resulting in raising
6546 @code{Constraint_Error} as required by standard Ada
6547 semantics). These overflow checks correspond to situations in which
6548 the true value of the result of an operation may be outside the base
6549 range of the result type. The following example shows the distinction:
6550
6551 @smallexample @c ada
6552 X1 : Integer := "Integer'Last";
6553 X2 : Integer range 1 .. 5 := "5";
6554 X3 : Integer := "Integer'Last";
6555 X4 : Integer range 1 .. 5 := "5";
6556 F  : Float := "2.0E+20";
6557 @dots{}
6558 X1 := X1 + 1;
6559 X2 := X2 + 1;
6560 X3 := Integer (F);
6561 X4 := Integer (F);
6562 @end smallexample
6563
6564 @noindent
6565 Note that if explicit values are assigned at compile time, the
6566 compiler may be able to detect overflow at compile time, in which case
6567 no actual run-time checking code is required, and Constraint_Error
6568 will be raised unconditionally, with or without
6569 @option{-gnato}. That's why the assigned values in the above fragment
6570 are in quotes, the meaning is "assign a value not known to the
6571 compiler that happens to be equal to ...". The remaining discussion
6572 assumes that the compiler cannot detect the values at compile time.
6573
6574 Here the first addition results in a value that is outside the base range
6575 of Integer, and hence requires an overflow check for detection of the
6576 constraint error. Thus the first assignment to @code{X1} raises a
6577 @code{Constraint_Error} exception only if @option{-gnato} is set.
6578
6579 The second increment operation results in a violation of the explicit
6580 range constraint; such range checks are performed by default, and are
6581 unaffected by @option{-gnato}.
6582
6583 The two conversions of @code{F} both result in values that are outside
6584 the base range of type @code{Integer} and thus will raise
6585 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6586 The fact that the result of the second conversion is assigned to
6587 variable @code{X4} with a restricted range is irrelevant, since the problem
6588 is in the conversion, not the assignment.
6589
6590 Basically the rule is that in the default mode (@option{-gnato} not
6591 used), the generated code assures that all integer variables stay
6592 within their declared ranges, or within the base range if there is
6593 no declared range. This prevents any serious problems like indexes
6594 out of range for array operations.
6595
6596 What is not checked in default mode is an overflow that results in
6597 an in-range, but incorrect value. In the above example, the assignments
6598 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6599 range of the target variable, but the result is wrong in the sense that
6600 it is too large to be represented correctly. Typically the assignment
6601 to @code{X1} will result in wrap around to the largest negative number.
6602 The conversions of @code{F} will result in some @code{Integer} value
6603 and if that integer value is out of the @code{X4} range then the
6604 subsequent assignment would generate an exception.
6605
6606 @findex Machine_Overflows
6607 Note that the @option{-gnato} switch does not affect the code generated
6608 for any floating-point operations; it applies only to integer
6609 semantics).
6610 For floating-point, GNAT has the @code{Machine_Overflows}
6611 attribute set to @code{False} and the normal mode of operation is to
6612 generate IEEE NaN and infinite values on overflow or invalid operations
6613 (such as dividing 0.0 by 0.0).
6614
6615 The reason that we distinguish overflow checking from other kinds of
6616 range constraint checking is that a failure of an overflow check, unlike
6617 for example the failure of a range check, can result in an incorrect
6618 value, but cannot cause random memory destruction (like an out of range
6619 subscript), or a wild jump (from an out of range case value). Overflow
6620 checking is also quite expensive in time and space, since in general it
6621 requires the use of double length arithmetic.
6622
6623 Note again that @option{-gnato} is off by default, so overflow checking is
6624 not performed in default mode. This means that out of the box, with the
6625 default settings, GNAT does not do all the checks expected from the
6626 language description in the Ada Reference Manual. If you want all constraint
6627 checks to be performed, as described in this Manual, then you must
6628 explicitly use the -gnato switch either on the @command{gnatmake} or
6629 @command{gcc} command.
6630
6631 @item -gnatE
6632 @cindex @option{-gnatE} (@command{gcc})
6633 @cindex Elaboration checks
6634 @cindex Check, elaboration
6635 Enables dynamic checks for access-before-elaboration
6636 on subprogram calls and generic instantiations.
6637 Note that @option{-gnatE} is not necessary for safety, because in the
6638 default mode, GNAT ensures statically that the checks would not fail.
6639 For full details of the effect and use of this switch,
6640 @xref{Compiling Using gcc}.
6641
6642 @item -fstack-check
6643 @cindex @option{-fstack-check} (@command{gcc})
6644 @cindex Stack Overflow Checking
6645 @cindex Checks, stack overflow checking
6646 Activates stack overflow checking. For full details of the effect and use of
6647 this switch see @ref{Stack Overflow Checking}.
6648 @end table
6649
6650 @findex Unsuppress
6651 @noindent
6652 The setting of these switches only controls the default setting of the
6653 checks. You may modify them using either @code{Suppress} (to remove
6654 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6655 the program source.
6656
6657 @node Using gcc for Syntax Checking
6658 @subsection Using @command{gcc} for Syntax Checking
6659 @table @option
6660 @item -gnats
6661 @cindex @option{-gnats} (@command{gcc})
6662 @ifclear vms
6663
6664 @noindent
6665 The @code{s} stands for ``syntax''.
6666 @end ifclear
6667
6668 Run GNAT in syntax checking only mode. For
6669 example, the command
6670
6671 @smallexample
6672 $ gcc -c -gnats x.adb
6673 @end smallexample
6674
6675 @noindent
6676 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6677 series of files in a single command
6678 @ifclear vms
6679 , and can use wild cards to specify such a group of files.
6680 Note that you must specify the @option{-c} (compile
6681 only) flag in addition to the @option{-gnats} flag.
6682 @end ifclear
6683 .
6684 You may use other switches in conjunction with @option{-gnats}. In
6685 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6686 format of any generated error messages.
6687
6688 When the source file is empty or contains only empty lines and/or comments,
6689 the output is a warning:
6690
6691 @smallexample
6692 $ gcc -c -gnats -x ada toto.txt
6693 toto.txt:1:01: warning: empty file, contains no compilation units
6694 $
6695 @end smallexample
6696
6697 Otherwise, the output is simply the error messages, if any. No object file or
6698 ALI file is generated by a syntax-only compilation. Also, no units other
6699 than the one specified are accessed. For example, if a unit @code{X}
6700 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6701 check only mode does not access the source file containing unit
6702 @code{Y}.
6703
6704 @cindex Multiple units, syntax checking
6705 Normally, GNAT allows only a single unit in a source file. However, this
6706 restriction does not apply in syntax-check-only mode, and it is possible
6707 to check a file containing multiple compilation units concatenated
6708 together. This is primarily used by the @code{gnatchop} utility
6709 (@pxref{Renaming Files Using gnatchop}).
6710 @end table
6711
6712 @node Using gcc for Semantic Checking
6713 @subsection Using @command{gcc} for Semantic Checking
6714 @table @option
6715 @item -gnatc
6716 @cindex @option{-gnatc} (@command{gcc})
6717
6718 @ifclear vms
6719 @noindent
6720 The @code{c} stands for ``check''.
6721 @end ifclear
6722 Causes the compiler to operate in semantic check mode,
6723 with full checking for all illegalities specified in the
6724 Ada Reference Manual, but without generation of any object code
6725 (no object file is generated).
6726
6727 Because dependent files must be accessed, you must follow the GNAT
6728 semantic restrictions on file structuring to operate in this mode:
6729
6730 @itemize @bullet
6731 @item
6732 The needed source files must be accessible
6733 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6734
6735 @item
6736 Each file must contain only one compilation unit.
6737
6738 @item
6739 The file name and unit name must match (@pxref{File Naming Rules}).
6740 @end itemize
6741
6742 The output consists of error messages as appropriate. No object file is
6743 generated. An @file{ALI} file is generated for use in the context of
6744 cross-reference tools, but this file is marked as not being suitable
6745 for binding (since no object file is generated).
6746 The checking corresponds exactly to the notion of
6747 legality in the Ada Reference Manual.
6748
6749 Any unit can be compiled in semantics-checking-only mode, including
6750 units that would not normally be compiled (subunits,
6751 and specifications where a separate body is present).
6752 @end table
6753
6754 @node Compiling Different Versions of Ada
6755 @subsection Compiling Different Versions of Ada
6756
6757 @noindent
6758 The switches described in this section allow you to explicitly specify
6759 the version of the Ada language that your programs are written in.
6760 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6761 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6762 indicate Ada 83 compatibility mode.
6763
6764 @table @option
6765 @cindex Compatibility with Ada 83
6766
6767 @item -gnat83 (Ada 83 Compatibility Mode)
6768 @cindex @option{-gnat83} (@command{gcc})
6769 @cindex ACVC, Ada 83 tests
6770 @cindex Ada 83 mode
6771
6772 @noindent
6773 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6774 specifies that the program is to be compiled in Ada 83 mode. With
6775 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6776 semantics where this can be done easily.
6777 It is not possible to guarantee this switch does a perfect
6778 job; some subtle tests, such as are
6779 found in earlier ACVC tests (and that have been removed from the ACATS suite
6780 for Ada 95), might not compile correctly.
6781 Nevertheless, this switch may be useful in some circumstances, for example
6782 where, due to contractual reasons, existing code needs to be maintained
6783 using only Ada 83 features.
6784
6785 With few exceptions (most notably the need to use @code{<>} on
6786 @cindex Generic formal parameters
6787 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6788 reserved words, and the use of packages
6789 with optional bodies), it is not necessary to specify the
6790 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6791 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6792 a correct Ada 83 program is usually also a correct program
6793 in these later versions of the language standard.
6794 For further information, please refer to @ref{Compatibility and Porting Guide}.
6795
6796 @item -gnat95 (Ada 95 mode)
6797 @cindex @option{-gnat95} (@command{gcc})
6798 @cindex Ada 95 mode
6799
6800 @noindent
6801 This switch directs the compiler to implement the Ada 95 version of the
6802 language.
6803 Since Ada 95 is almost completely upwards
6804 compatible with Ada 83, Ada 83 programs may generally be compiled using
6805 this switch (see the description of the @option{-gnat83} switch for further
6806 information about Ada 83 mode).
6807 If an Ada 2005 program is compiled in Ada 95 mode,
6808 uses of the new Ada 2005 features will cause error
6809 messages or warnings.
6810
6811 This switch also can be used to cancel the effect of a previous
6812 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6813
6814 @item -gnat05 (Ada 2005 mode)
6815 @cindex @option{-gnat05} (@command{gcc})
6816 @cindex Ada 2005 mode
6817
6818 @noindent
6819 This switch directs the compiler to implement the Ada 2005 version of the
6820 language.
6821 Since Ada 2005 is almost completely upwards
6822 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6823 may generally be compiled using this switch (see the description of the
6824 @option{-gnat83} and @option{-gnat95} switches for further
6825 information).
6826
6827 For information about the approved ``Ada Issues'' that have been incorporated
6828 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6829 Included with GNAT releases is a file @file{features-ada0y} that describes
6830 the set of implemented Ada 2005 features.
6831 @end table
6832
6833
6834 @node Character Set Control
6835 @subsection Character Set Control
6836 @table @option
6837 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6838 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6839
6840 @noindent
6841 Normally GNAT recognizes the Latin-1 character set in source program
6842 identifiers, as described in the Ada Reference Manual.
6843 This switch causes
6844 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6845 single character ^^or word^ indicating the character set, as follows:
6846
6847 @table @code
6848 @item 1
6849 ISO 8859-1 (Latin-1) identifiers
6850
6851 @item 2
6852 ISO 8859-2 (Latin-2) letters allowed in identifiers
6853
6854 @item 3
6855 ISO 8859-3 (Latin-3) letters allowed in identifiers
6856
6857 @item 4
6858 ISO 8859-4 (Latin-4) letters allowed in identifiers
6859
6860 @item 5
6861 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6862
6863 @item 9
6864 ISO 8859-15 (Latin-9) letters allowed in identifiers
6865
6866 @item ^p^PC^
6867 IBM PC letters (code page 437) allowed in identifiers
6868
6869 @item ^8^PC850^
6870 IBM PC letters (code page 850) allowed in identifiers
6871
6872 @item ^f^FULL_UPPER^
6873 Full upper-half codes allowed in identifiers
6874
6875 @item ^n^NO_UPPER^
6876 No upper-half codes allowed in identifiers
6877
6878 @item ^w^WIDE^
6879 Wide-character codes (that is, codes greater than 255)
6880 allowed in identifiers
6881 @end table
6882
6883 @xref{Foreign Language Representation}, for full details on the
6884 implementation of these character sets.
6885
6886 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6887 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6888 Specify the method of encoding for wide characters.
6889 @var{e} is one of the following:
6890
6891 @table @code
6892
6893 @item ^h^HEX^
6894 Hex encoding (brackets coding also recognized)
6895
6896 @item ^u^UPPER^
6897 Upper half encoding (brackets encoding also recognized)
6898
6899 @item ^s^SHIFT_JIS^
6900 Shift/JIS encoding (brackets encoding also recognized)
6901
6902 @item ^e^EUC^
6903 EUC encoding (brackets encoding also recognized)
6904
6905 @item ^8^UTF8^
6906 UTF-8 encoding (brackets encoding also recognized)
6907
6908 @item ^b^BRACKETS^
6909 Brackets encoding only (default value)
6910 @end table
6911 For full details on these encoding
6912 methods see @ref{Wide Character Encodings}.
6913 Note that brackets coding is always accepted, even if one of the other
6914 options is specified, so for example @option{-gnatW8} specifies that both
6915 brackets and UTF-8 encodings will be recognized. The units that are
6916 with'ed directly or indirectly will be scanned using the specified
6917 representation scheme, and so if one of the non-brackets scheme is
6918 used, it must be used consistently throughout the program. However,
6919 since brackets encoding is always recognized, it may be conveniently
6920 used in standard libraries, allowing these libraries to be used with
6921 any of the available coding schemes.
6922 scheme.
6923
6924 If no @option{-gnatW?} parameter is present, then the default
6925 representation is normally Brackets encoding only. However, if the
6926 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6927 byte order mark or BOM for UTF-8), then these three characters are
6928 skipped and the default representation for the file is set to UTF-8.
6929
6930 Note that the wide character representation that is specified (explicitly
6931 or by default) for the main program also acts as the default encoding used
6932 for Wide_Text_IO files if not specifically overridden by a WCEM form
6933 parameter.
6934
6935 @end table
6936 @node File Naming Control
6937 @subsection File Naming Control
6938
6939 @table @option
6940 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6941 @cindex @option{-gnatk} (@command{gcc})
6942 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6943 1-999, indicates the maximum allowable length of a file name (not
6944 including the @file{.ads} or @file{.adb} extension). The default is not
6945 to enable file name krunching.
6946
6947 For the source file naming rules, @xref{File Naming Rules}.
6948 @end table
6949
6950 @node Subprogram Inlining Control
6951 @subsection Subprogram Inlining Control
6952
6953 @table @option
6954 @c !sort!
6955 @item -gnatn
6956 @cindex @option{-gnatn} (@command{gcc})
6957 @ifclear vms
6958 The @code{n} here is intended to suggest the first syllable of the
6959 word ``inline''.
6960 @end ifclear
6961 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6962 inlining to actually occur, optimization must be enabled. To enable
6963 inlining of subprograms specified by pragma @code{Inline},
6964 you must also specify this switch.
6965 In the absence of this switch, GNAT does not attempt
6966 inlining and does not need to access the bodies of
6967 subprograms for which @code{pragma Inline} is specified if they are not
6968 in the current unit.
6969
6970 If you specify this switch the compiler will access these bodies,
6971 creating an extra source dependency for the resulting object file, and
6972 where possible, the call will be inlined.
6973 For further details on when inlining is possible
6974 see @ref{Inlining of Subprograms}.
6975
6976 @item -gnatN
6977 @cindex @option{-gnatN} (@command{gcc})
6978 This switch activates front-end inlining which also
6979 generates additional dependencies.
6980
6981 When using a gcc-based back end (in practice this means using any version
6982 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
6983 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
6984 Historically front end inlining was more extensive than the gcc back end
6985 inlining, but that is no longer the case.
6986 @end table
6987
6988 @node Auxiliary Output Control
6989 @subsection Auxiliary Output Control
6990
6991 @table @option
6992 @item -gnatt
6993 @cindex @option{-gnatt} (@command{gcc})
6994 @cindex Writing internal trees
6995 @cindex Internal trees, writing to file
6996 Causes GNAT to write the internal tree for a unit to a file (with the
6997 extension @file{.adt}.
6998 This not normally required, but is used by separate analysis tools.
6999 Typically
7000 these tools do the necessary compilations automatically, so you should
7001 not have to specify this switch in normal operation.
7002 Note that the combination of switches @option{-gnatct}
7003 generates a tree in the form required by ASIS applications.
7004
7005 @item -gnatu
7006 @cindex @option{-gnatu} (@command{gcc})
7007 Print a list of units required by this compilation on @file{stdout}.
7008 The listing includes all units on which the unit being compiled depends
7009 either directly or indirectly.
7010
7011 @ifclear vms
7012 @item -pass-exit-codes
7013 @cindex @option{-pass-exit-codes} (@command{gcc})
7014 If this switch is not used, the exit code returned by @command{gcc} when
7015 compiling multiple files indicates whether all source files have
7016 been successfully used to generate object files or not.
7017
7018 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7019 exit status and allows an integrated development environment to better
7020 react to a compilation failure. Those exit status are:
7021
7022 @table @asis
7023 @item 5
7024 There was an error in at least one source file.
7025 @item 3
7026 At least one source file did not generate an object file.
7027 @item 2
7028 The compiler died unexpectedly (internal error for example).
7029 @item 0
7030 An object file has been generated for every source file.
7031 @end table
7032 @end ifclear
7033 @end table
7034
7035 @node Debugging Control
7036 @subsection Debugging Control
7037
7038 @table @option
7039 @c !sort!
7040 @cindex Debugging options
7041 @ifclear vms
7042 @item -gnatd@var{x}
7043 @cindex @option{-gnatd} (@command{gcc})
7044 Activate internal debugging switches. @var{x} is a letter or digit, or
7045 string of letters or digits, which specifies the type of debugging
7046 outputs desired. Normally these are used only for internal development
7047 or system debugging purposes. You can find full documentation for these
7048 switches in the body of the @code{Debug} unit in the compiler source
7049 file @file{debug.adb}.
7050 @end ifclear
7051
7052 @item -gnatG[=nn]
7053 @cindex @option{-gnatG} (@command{gcc})
7054 This switch causes the compiler to generate auxiliary output containing
7055 a pseudo-source listing of the generated expanded code. Like most Ada
7056 compilers, GNAT works by first transforming the high level Ada code into
7057 lower level constructs. For example, tasking operations are transformed
7058 into calls to the tasking run-time routines. A unique capability of GNAT
7059 is to list this expanded code in a form very close to normal Ada source.
7060 This is very useful in understanding the implications of various Ada
7061 usage on the efficiency of the generated code. There are many cases in
7062 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7063 generate a lot of run-time code. By using @option{-gnatG} you can identify
7064 these cases, and consider whether it may be desirable to modify the coding
7065 approach to improve efficiency.
7066
7067 The optional parameter @code{nn} if present after -gnatG specifies an
7068 alternative maximum line length that overrides the normal default of 72.
7069 This value is in the range 40-999999, values less than 40 being silently
7070 reset to 40. The equal sign is optional.
7071
7072 The format of the output is very similar to standard Ada source, and is
7073 easily understood by an Ada programmer. The following special syntactic
7074 additions correspond to low level features used in the generated code that
7075 do not have any exact analogies in pure Ada source form. The following
7076 is a partial list of these special constructions. See the spec
7077 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7078
7079 If the switch @option{-gnatL} is used in conjunction with
7080 @cindex @option{-gnatL} (@command{gcc})
7081 @option{-gnatG}, then the original source lines are interspersed
7082 in the expanded source (as comment lines with the original line number).
7083
7084 @table @code
7085 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7086 Shows the storage pool being used for an allocator.
7087
7088 @item at end @var{procedure-name};
7089 Shows the finalization (cleanup) procedure for a scope.
7090
7091 @item (if @var{expr} then @var{expr} else @var{expr})
7092 Conditional expression equivalent to the @code{x?y:z} construction in C.
7093
7094 @item @var{target}^^^(@var{source})
7095 A conversion with floating-point truncation instead of rounding.
7096
7097 @item @var{target}?(@var{source})
7098 A conversion that bypasses normal Ada semantic checking. In particular
7099 enumeration types and fixed-point types are treated simply as integers.
7100
7101 @item @var{target}?^^^(@var{source})
7102 Combines the above two cases.
7103
7104 @item @var{x} #/ @var{y}
7105 @itemx @var{x} #mod @var{y}
7106 @itemx @var{x} #* @var{y}
7107 @itemx @var{x} #rem @var{y}
7108 A division or multiplication of fixed-point values which are treated as
7109 integers without any kind of scaling.
7110
7111 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7112 Shows the storage pool associated with a @code{free} statement.
7113
7114 @item [subtype or type declaration]
7115 Used to list an equivalent declaration for an internally generated
7116 type that is referenced elsewhere in the listing.
7117
7118 @item freeze @var{type-name} @ovar{actions}
7119 Shows the point at which @var{type-name} is frozen, with possible
7120 associated actions to be performed at the freeze point.
7121
7122 @item reference @var{itype}
7123 Reference (and hence definition) to internal type @var{itype}.
7124
7125 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7126 Intrinsic function call.
7127
7128 @item @var{label-name} : label
7129 Declaration of label @var{labelname}.
7130
7131 @item #$ @var{subprogram-name}
7132 An implicit call to a run-time support routine
7133 (to meet the requirement of H.3.1(9) in a
7134 convenient manner).
7135
7136 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7137 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7138 @var{expr}, but handled more efficiently).
7139
7140 @item [constraint_error]
7141 Raise the @code{Constraint_Error} exception.
7142
7143 @item @var{expression}'reference
7144 A pointer to the result of evaluating @var{expression}.
7145
7146 @item @var{target-type}!(@var{source-expression})
7147 An unchecked conversion of @var{source-expression} to @var{target-type}.
7148
7149 @item [@var{numerator}/@var{denominator}]
7150 Used to represent internal real literals (that) have no exact
7151 representation in base 2-16 (for example, the result of compile time
7152 evaluation of the expression 1.0/27.0).
7153 @end table
7154
7155 @item -gnatD[=nn]
7156 @cindex @option{-gnatD} (@command{gcc})
7157 When used in conjunction with @option{-gnatG}, this switch causes
7158 the expanded source, as described above for
7159 @option{-gnatG} to be written to files with names
7160 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7161 instead of to the standard output file. For
7162 example, if the source file name is @file{hello.adb}, then a file
7163 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7164 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7165 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7166 you to do source level debugging using the generated code which is
7167 sometimes useful for complex code, for example to find out exactly
7168 which part of a complex construction raised an exception. This switch
7169 also suppress generation of cross-reference information (see
7170 @option{-gnatx}) since otherwise the cross-reference information
7171 would refer to the @file{^.dg^.DG^} file, which would cause
7172 confusion since this is not the original source file.
7173
7174 Note that @option{-gnatD} actually implies @option{-gnatG}
7175 automatically, so it is not necessary to give both options.
7176 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7177
7178 If the switch @option{-gnatL} is used in conjunction with
7179 @cindex @option{-gnatL} (@command{gcc})
7180 @option{-gnatDG}, then the original source lines are interspersed
7181 in the expanded source (as comment lines with the original line number).
7182
7183 The optional parameter @code{nn} if present after -gnatD specifies an
7184 alternative maximum line length that overrides the normal default of 72.
7185 This value is in the range 40-999999, values less than 40 being silently
7186 reset to 40. The equal sign is optional.
7187
7188 @item -gnatr
7189 @cindex @option{-gnatr} (@command{gcc})
7190 @cindex pragma Restrictions
7191 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7192 so that violation of restrictions causes warnings rather than illegalities.
7193 This is useful during the development process when new restrictions are added
7194 or investigated. The switch also causes pragma Profile to be treated as
7195 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7196 restriction warnings rather than restrictions.
7197
7198 @ifclear vms
7199 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7200 @cindex @option{-gnatR} (@command{gcc})
7201 This switch controls output from the compiler of a listing showing
7202 representation information for declared types and objects. For
7203 @option{-gnatR0}, no information is output (equivalent to omitting
7204 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7205 so @option{-gnatR} with no parameter has the same effect), size and alignment
7206 information is listed for declared array and record types. For
7207 @option{-gnatR2}, size and alignment information is listed for all
7208 declared types and objects. Finally @option{-gnatR3} includes symbolic
7209 expressions for values that are computed at run time for
7210 variant records. These symbolic expressions have a mostly obvious
7211 format with #n being used to represent the value of the n'th
7212 discriminant. See source files @file{repinfo.ads/adb} in the
7213 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7214 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7215 the output is to a file with the name @file{^file.rep^file_REP^} where
7216 file is the name of the corresponding source file.
7217 @end ifclear
7218 @ifset vms
7219 @item /REPRESENTATION_INFO
7220 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7221 This qualifier controls output from the compiler of a listing showing
7222 representation information for declared types and objects. For
7223 @option{/REPRESENTATION_INFO=NONE}, no information is output
7224 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7225 @option{/REPRESENTATION_INFO} without option is equivalent to
7226 @option{/REPRESENTATION_INFO=ARRAYS}.
7227 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7228 information is listed for declared array and record types. For
7229 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7230 is listed for all expression information for values that are computed
7231 at run time for variant records. These symbolic expressions have a mostly
7232 obvious format with #n being used to represent the value of the n'th
7233 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7234 @code{GNAT} sources for full details on the format of
7235 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7236 If _FILE is added at the end of an option
7237 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7238 then the output is to a file with the name @file{file_REP} where
7239 file is the name of the corresponding source file.
7240 @end ifset
7241 Note that it is possible for record components to have zero size. In
7242 this case, the component clause uses an obvious extension of permitted
7243 Ada syntax, for example @code{at 0 range 0 .. -1}.
7244
7245 Representation information requires that code be generated (since it is the
7246 code generator that lays out complex data structures). If an attempt is made
7247 to output representation information when no code is generated, for example
7248 when a subunit is compiled on its own, then no information can be generated
7249 and the compiler outputs a message to this effect.
7250
7251 @item -gnatS
7252 @cindex @option{-gnatS} (@command{gcc})
7253 The use of the switch @option{-gnatS} for an
7254 Ada compilation will cause the compiler to output a
7255 representation of package Standard in a form very
7256 close to standard Ada. It is not quite possible to
7257 do this entirely in standard Ada (since new
7258 numeric base types cannot be created in standard
7259 Ada), but the output is easily
7260 readable to any Ada programmer, and is useful to
7261 determine the characteristics of target dependent
7262 types in package Standard.
7263
7264 @item -gnatx
7265 @cindex @option{-gnatx} (@command{gcc})
7266 Normally the compiler generates full cross-referencing information in
7267 the @file{ALI} file. This information is used by a number of tools,
7268 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7269 suppresses this information. This saves some space and may slightly
7270 speed up compilation, but means that these tools cannot be used.
7271 @end table
7272
7273 @node Exception Handling Control
7274 @subsection Exception Handling Control
7275
7276 @noindent
7277 GNAT uses two methods for handling exceptions at run-time. The
7278 @code{setjmp/longjmp} method saves the context when entering
7279 a frame with an exception handler. Then when an exception is
7280 raised, the context can be restored immediately, without the
7281 need for tracing stack frames. This method provides very fast
7282 exception propagation, but introduces significant overhead for
7283 the use of exception handlers, even if no exception is raised.
7284
7285 The other approach is called ``zero cost'' exception handling.
7286 With this method, the compiler builds static tables to describe
7287 the exception ranges. No dynamic code is required when entering
7288 a frame containing an exception handler. When an exception is
7289 raised, the tables are used to control a back trace of the
7290 subprogram invocation stack to locate the required exception
7291 handler. This method has considerably poorer performance for
7292 the propagation of exceptions, but there is no overhead for
7293 exception handlers if no exception is raised. Note that in this
7294 mode and in the context of mixed Ada and C/C++ programming,
7295 to propagate an exception through a C/C++ code, the C/C++ code
7296 must be compiled with the @option{-funwind-tables} GCC's
7297 option.
7298
7299 The following switches may be used to control which of the
7300 two exception handling methods is used.
7301
7302 @table @option
7303 @c !sort!
7304
7305 @item --RTS=sjlj
7306 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7307 This switch causes the setjmp/longjmp run-time (when available) to be used
7308 for exception handling. If the default
7309 mechanism for the target is zero cost exceptions, then
7310 this switch can be used to modify this default, and must be
7311 used for all units in the partition.
7312 This option is rarely used. One case in which it may be
7313 advantageous is if you have an application where exception
7314 raising is common and the overall performance of the
7315 application is improved by favoring exception propagation.
7316
7317 @item --RTS=zcx
7318 @cindex @option{--RTS=zcx} (@command{gnatmake})
7319 @cindex Zero Cost Exceptions
7320 This switch causes the zero cost approach to be used
7321 for exception handling. If this is the default mechanism for the
7322 target (see below), then this switch is unneeded. If the default
7323 mechanism for the target is setjmp/longjmp exceptions, then
7324 this switch can be used to modify this default, and must be
7325 used for all units in the partition.
7326 This option can only be used if the zero cost approach
7327 is available for the target in use, otherwise it will generate an error.
7328 @end table
7329
7330 @noindent
7331 The same option @option{--RTS} must be used both for @command{gcc}
7332 and @command{gnatbind}. Passing this option to @command{gnatmake}
7333 (@pxref{Switches for gnatmake}) will ensure the required consistency
7334 through the compilation and binding steps.
7335
7336 @node Units to Sources Mapping Files
7337 @subsection Units to Sources Mapping Files
7338
7339 @table @option
7340
7341 @item -gnatem^^=^@var{path}
7342 @cindex @option{-gnatem} (@command{gcc})
7343 A mapping file is a way to communicate to the compiler two mappings:
7344 from unit names to file names (without any directory information) and from
7345 file names to path names (with full directory information). These mappings
7346 are used by the compiler to short-circuit the path search.
7347
7348 The use of mapping files is not required for correct operation of the
7349 compiler, but mapping files can improve efficiency, particularly when
7350 sources are read over a slow network connection. In normal operation,
7351 you need not be concerned with the format or use of mapping files,
7352 and the @option{-gnatem} switch is not a switch that you would use
7353 explicitly. it is intended only for use by automatic tools such as
7354 @command{gnatmake} running under the project file facility. The
7355 description here of the format of mapping files is provided
7356 for completeness and for possible use by other tools.
7357
7358 A mapping file is a sequence of sets of three lines. In each set,
7359 the first line is the unit name, in lower case, with ``@code{%s}''
7360 appended for
7361 specs and ``@code{%b}'' appended for bodies; the second line is the
7362 file name; and the third line is the path name.
7363
7364 Example:
7365 @smallexample
7366    main%b
7367    main.2.ada
7368    /gnat/project1/sources/main.2.ada
7369 @end smallexample
7370
7371 When the switch @option{-gnatem} is specified, the compiler will create
7372 in memory the two mappings from the specified file. If there is any problem
7373 (nonexistent file, truncated file or duplicate entries), no mapping will
7374 be created.
7375
7376 Several @option{-gnatem} switches may be specified; however, only the last
7377 one on the command line will be taken into account.
7378
7379 When using a project file, @command{gnatmake} create a temporary mapping file
7380 and communicates it to the compiler using this switch.
7381
7382 @end table
7383
7384 @node Integrated Preprocessing
7385 @subsection Integrated Preprocessing
7386
7387 @noindent
7388 GNAT sources may be preprocessed immediately before compilation.
7389 In this case, the actual
7390 text of the source is not the text of the source file, but is derived from it
7391 through a process called preprocessing. Integrated preprocessing is specified
7392 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7393 indicates, through a text file, the preprocessing data to be used.
7394 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7395
7396 @noindent
7397 Note that when integrated preprocessing is used, the output from the
7398 preprocessor is not written to any external file. Instead it is passed
7399 internally to the compiler. If you need to preserve the result of
7400 preprocessing in a file, then you should use @command{gnatprep}
7401 to perform the desired preprocessing in stand-alone mode.
7402
7403 @noindent
7404 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7405 used when Integrated Preprocessing is used. The reason is that preprocessing
7406 with another Preprocessing Data file without changing the sources will
7407 not trigger recompilation without this switch.
7408
7409 @noindent
7410 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7411 always trigger recompilation for sources that are preprocessed,
7412 because @command{gnatmake} cannot compute the checksum of the source after
7413 preprocessing.
7414
7415 @noindent
7416 The actual preprocessing function is described in details in section
7417 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7418 preprocessing is triggered and parameterized.
7419
7420 @table @code
7421
7422 @item -gnatep=@var{file}
7423 @cindex @option{-gnatep} (@command{gcc})
7424 This switch indicates to the compiler the file name (without directory
7425 information) of the preprocessor data file to use. The preprocessor data file
7426 should be found in the source directories.
7427
7428 @noindent
7429 A preprocessing data file is a text file with significant lines indicating
7430 how should be preprocessed either a specific source or all sources not
7431 mentioned in other lines. A significant line is a nonempty, non-comment line.
7432 Comments are similar to Ada comments.
7433
7434 @noindent
7435 Each significant line starts with either a literal string or the character '*'.
7436 A literal string is the file name (without directory information) of the source
7437 to preprocess. A character '*' indicates the preprocessing for all the sources
7438 that are not specified explicitly on other lines (order of the lines is not
7439 significant). It is an error to have two lines with the same file name or two
7440 lines starting with the character '*'.
7441
7442 @noindent
7443 After the file name or the character '*', another optional literal string
7444 indicating the file name of the definition file to be used for preprocessing
7445 (@pxref{Form of Definitions File}). The definition files are found by the
7446 compiler in one of the source directories. In some cases, when compiling
7447 a source in a directory other than the current directory, if the definition
7448 file is in the current directory, it may be necessary to add the current
7449 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7450 the compiler would not find the definition file.
7451
7452 @noindent
7453 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7454 be found. Those ^switches^switches^ are:
7455
7456 @table @code
7457
7458 @item -b
7459 Causes both preprocessor lines and the lines deleted by
7460 preprocessing to be replaced by blank lines, preserving the line number.
7461 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7462 it cancels the effect of @option{-c}.
7463
7464 @item -c
7465 Causes both preprocessor lines and the lines deleted
7466 by preprocessing to be retained as comments marked
7467 with the special string ``@code{--! }''.
7468
7469 @item -Dsymbol=value
7470 Define or redefine a symbol, associated with value. A symbol is an Ada
7471 identifier, or an Ada reserved word, with the exception of @code{if},
7472 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7473 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7474 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7475 same name defined in a definition file.
7476
7477 @item -s
7478 Causes a sorted list of symbol names and values to be
7479 listed on the standard output file.
7480
7481 @item -u
7482 Causes undefined symbols to be treated as having the value @code{FALSE}
7483 in the context
7484 of a preprocessor test. In the absence of this option, an undefined symbol in
7485 a @code{#if} or @code{#elsif} test will be treated as an error.
7486
7487 @end table
7488
7489 @noindent
7490 Examples of valid lines in a preprocessor data file:
7491
7492 @smallexample
7493   "toto.adb"  "prep.def" -u
7494   --  preprocess "toto.adb", using definition file "prep.def",
7495   --  undefined symbol are False.
7496
7497   * -c -DVERSION=V101
7498   --  preprocess all other sources without a definition file;
7499   --  suppressed lined are commented; symbol VERSION has the value V101.
7500
7501   "titi.adb" "prep2.def" -s
7502   --  preprocess "titi.adb", using definition file "prep2.def";
7503   --  list all symbols with their values.
7504 @end smallexample
7505
7506 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7507 @cindex @option{-gnateD} (@command{gcc})
7508 Define or redefine a preprocessing symbol, associated with value. If no value
7509 is given on the command line, then the value of the symbol is @code{True}.
7510 A symbol is an identifier, following normal Ada (case-insensitive)
7511 rules for its syntax, and value is any sequence (including an empty sequence)
7512 of characters from the set (letters, digits, period, underline).
7513 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7514 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7515
7516 @noindent
7517 A symbol declared with this ^switch^switch^ on the command line replaces a
7518 symbol with the same name either in a definition file or specified with a
7519 ^switch^switch^ -D in the preprocessor data file.
7520
7521 @noindent
7522 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7523
7524 @item -gnateG
7525 When integrated preprocessing is performed and the preprocessor modifies
7526 the source text, write the result of this preprocessing into a file
7527 <source>^.prep^_prep^.
7528
7529 @end table
7530
7531 @node Code Generation Control
7532 @subsection Code Generation Control
7533
7534 @noindent
7535
7536 The GCC technology provides a wide range of target dependent
7537 @option{-m} switches for controlling
7538 details of code generation with respect to different versions of
7539 architectures. This includes variations in instruction sets (e.g.@:
7540 different members of the power pc family), and different requirements
7541 for optimal arrangement of instructions (e.g.@: different members of
7542 the x86 family). The list of available @option{-m} switches may be
7543 found in the GCC documentation.
7544
7545 Use of these @option{-m} switches may in some cases result in improved
7546 code performance.
7547
7548 The GNAT Pro technology is tested and qualified without any
7549 @option{-m} switches,
7550 so generally the most reliable approach is to avoid the use of these
7551 switches. However, we generally expect most of these switches to work
7552 successfully with GNAT Pro, and many customers have reported successful
7553 use of these options.
7554
7555 Our general advice is to avoid the use of @option{-m} switches unless
7556 special needs lead to requirements in this area. In particular,
7557 there is no point in using @option{-m} switches to improve performance
7558 unless you actually see a performance improvement.
7559
7560 @ifset vms
7561 @node Return Codes
7562 @subsection Return Codes
7563 @cindex Return Codes
7564 @cindex @option{/RETURN_CODES=VMS}
7565
7566 @noindent
7567 On VMS, GNAT compiled programs return POSIX-style codes by default,
7568 e.g.@: @option{/RETURN_CODES=POSIX}.
7569
7570 To enable VMS style return codes, use GNAT BIND and LINK with the option
7571 @option{/RETURN_CODES=VMS}. For example:
7572
7573 @smallexample
7574 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7575 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7576 @end smallexample
7577
7578 @noindent
7579 Programs built with /RETURN_CODES=VMS are suitable to be called in
7580 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7581 are suitable for spawning with appropriate GNAT RTL routines.
7582
7583 @end ifset
7584
7585 @node Search Paths and the Run-Time Library (RTL)
7586 @section Search Paths and the Run-Time Library (RTL)
7587
7588 @noindent
7589 With the GNAT source-based library system, the compiler must be able to
7590 find source files for units that are needed by the unit being compiled.
7591 Search paths are used to guide this process.
7592
7593 The compiler compiles one source file whose name must be given
7594 explicitly on the command line. In other words, no searching is done
7595 for this file. To find all other source files that are needed (the most
7596 common being the specs of units), the compiler examines the following
7597 directories, in the following order:
7598
7599 @enumerate
7600 @item
7601 The directory containing the source file of the main unit being compiled
7602 (the file name on the command line).
7603
7604 @item
7605 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7606 @command{gcc} command line, in the order given.
7607
7608 @item
7609 @findex ADA_PRJ_INCLUDE_FILE
7610 Each of the directories listed in the text file whose name is given
7611 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7612
7613 @noindent
7614 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7615 driver when project files are used. It should not normally be set
7616 by other means.
7617
7618 @item
7619 @findex ADA_INCLUDE_PATH
7620 Each of the directories listed in the value of the
7621 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7622 @ifclear vms
7623 Construct this value
7624 exactly as the @env{PATH} environment variable: a list of directory
7625 names separated by colons (semicolons when working with the NT version).
7626 @end ifclear
7627 @ifset vms
7628 Normally, define this value as a logical name containing a comma separated
7629 list of directory names.
7630
7631 This variable can also be defined by means of an environment string
7632 (an argument to the HP C exec* set of functions).
7633
7634 Logical Name:
7635 @smallexample
7636 DEFINE ANOTHER_PATH FOO:[BAG]
7637 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7638 @end smallexample
7639
7640 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7641 first, followed by the standard Ada
7642 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7643 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7644 (Text_IO, Sequential_IO, etc)
7645 instead of the standard Ada packages. Thus, in order to get the standard Ada
7646 packages by default, ADA_INCLUDE_PATH must be redefined.
7647 @end ifset
7648
7649 @item
7650 The content of the @file{ada_source_path} file which is part of the GNAT
7651 installation tree and is used to store standard libraries such as the
7652 GNAT Run Time Library (RTL) source files.
7653 @ifclear vms
7654 @ref{Installing a library}
7655 @end ifclear
7656 @end enumerate
7657
7658 @noindent
7659 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7660 inhibits the use of the directory
7661 containing the source file named in the command line. You can still
7662 have this directory on your search path, but in this case it must be
7663 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7664
7665 Specifying the switch @option{-nostdinc}
7666 inhibits the search of the default location for the GNAT Run Time
7667 Library (RTL) source files.
7668
7669 The compiler outputs its object files and ALI files in the current
7670 working directory.
7671 @ifclear vms
7672 Caution: The object file can be redirected with the @option{-o} switch;
7673 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7674 so the @file{ALI} file will not go to the right place. Therefore, you should
7675 avoid using the @option{-o} switch.
7676 @end ifclear
7677
7678 @findex System.IO
7679 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7680 children make up the GNAT RTL, together with the simple @code{System.IO}
7681 package used in the @code{"Hello World"} example. The sources for these units
7682 are needed by the compiler and are kept together in one directory. Not
7683 all of the bodies are needed, but all of the sources are kept together
7684 anyway. In a normal installation, you need not specify these directory
7685 names when compiling or binding. Either the environment variables or
7686 the built-in defaults cause these files to be found.
7687
7688 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7689 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7690 consisting of child units of @code{GNAT}. This is a collection of generally
7691 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7692 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7693
7694 Besides simplifying access to the RTL, a major use of search paths is
7695 in compiling sources from multiple directories. This can make
7696 development environments much more flexible.
7697
7698 @node Order of Compilation Issues
7699 @section Order of Compilation Issues
7700
7701 @noindent
7702 If, in our earlier example, there was a spec for the @code{hello}
7703 procedure, it would be contained in the file @file{hello.ads}; yet this
7704 file would not have to be explicitly compiled. This is the result of the
7705 model we chose to implement library management. Some of the consequences
7706 of this model are as follows:
7707
7708 @itemize @bullet
7709 @item
7710 There is no point in compiling specs (except for package
7711 specs with no bodies) because these are compiled as needed by clients. If
7712 you attempt a useless compilation, you will receive an error message.
7713 It is also useless to compile subunits because they are compiled as needed
7714 by the parent.
7715
7716 @item
7717 There are no order of compilation requirements: performing a
7718 compilation never obsoletes anything. The only way you can obsolete
7719 something and require recompilations is to modify one of the
7720 source files on which it depends.
7721
7722 @item
7723 There is no library as such, apart from the ALI files
7724 (@pxref{The Ada Library Information Files}, for information on the format
7725 of these files). For now we find it convenient to create separate ALI files,
7726 but eventually the information therein may be incorporated into the object
7727 file directly.
7728
7729 @item
7730 When you compile a unit, the source files for the specs of all units
7731 that it @code{with}'s, all its subunits, and the bodies of any generics it
7732 instantiates must be available (reachable by the search-paths mechanism
7733 described above), or you will receive a fatal error message.
7734 @end itemize
7735
7736 @node Examples
7737 @section Examples
7738
7739 @noindent
7740 The following are some typical Ada compilation command line examples:
7741
7742 @table @code
7743 @item $ gcc -c xyz.adb
7744 Compile body in file @file{xyz.adb} with all default options.
7745
7746 @ifclear vms
7747 @item $ gcc -c -O2 -gnata xyz-def.adb
7748 @end ifclear
7749 @ifset vms
7750 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7751 @end ifset
7752
7753 Compile the child unit package in file @file{xyz-def.adb} with extensive
7754 optimizations, and pragma @code{Assert}/@code{Debug} statements
7755 enabled.
7756
7757 @item $ gcc -c -gnatc abc-def.adb
7758 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7759 mode.
7760 @end table
7761
7762 @node Binding Using gnatbind
7763 @chapter Binding Using @code{gnatbind}
7764 @findex gnatbind
7765
7766 @menu
7767 * Running gnatbind::
7768 * Switches for gnatbind::
7769 * Command-Line Access::
7770 * Search Paths for gnatbind::
7771 * Examples of gnatbind Usage::
7772 @end menu
7773
7774 @noindent
7775 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7776 to bind compiled GNAT objects.
7777
7778 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7779 driver (see @ref{The GNAT Driver and Project Files}).
7780
7781 The @code{gnatbind} program performs four separate functions:
7782
7783 @enumerate
7784 @item
7785 Checks that a program is consistent, in accordance with the rules in
7786 Chapter 10 of the Ada Reference Manual. In particular, error
7787 messages are generated if a program uses inconsistent versions of a
7788 given unit.
7789
7790 @item
7791 Checks that an acceptable order of elaboration exists for the program
7792 and issues an error message if it cannot find an order of elaboration
7793 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7794
7795 @item
7796 Generates a main program incorporating the given elaboration order.
7797 This program is a small Ada package (body and spec) that
7798 must be subsequently compiled
7799 using the GNAT compiler. The necessary compilation step is usually
7800 performed automatically by @command{gnatlink}. The two most important
7801 functions of this program
7802 are to call the elaboration routines of units in an appropriate order
7803 and to call the main program.
7804
7805 @item
7806 Determines the set of object files required by the given main program.
7807 This information is output in the forms of comments in the generated program,
7808 to be read by the @command{gnatlink} utility used to link the Ada application.
7809 @end enumerate
7810
7811 @node Running gnatbind
7812 @section Running @code{gnatbind}
7813
7814 @noindent
7815 The form of the @code{gnatbind} command is
7816
7817 @smallexample
7818 $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7819 @end smallexample
7820
7821 @noindent
7822 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7823 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7824 package in two files whose names are
7825 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7826 For example, if given the
7827 parameter @file{hello.ali}, for a main program contained in file
7828 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7829 and @file{b~hello.adb}.
7830
7831 When doing consistency checking, the binder takes into consideration
7832 any source files it can locate. For example, if the binder determines
7833 that the given main program requires the package @code{Pack}, whose
7834 @file{.ALI}
7835 file is @file{pack.ali} and whose corresponding source spec file is
7836 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7837 (using the same search path conventions as previously described for the
7838 @command{gcc} command). If it can locate this source file, it checks that
7839 the time stamps
7840 or source checksums of the source and its references to in @file{ALI} files
7841 match. In other words, any @file{ALI} files that mentions this spec must have
7842 resulted from compiling this version of the source file (or in the case
7843 where the source checksums match, a version close enough that the
7844 difference does not matter).
7845
7846 @cindex Source files, use by binder
7847 The effect of this consistency checking, which includes source files, is
7848 that the binder ensures that the program is consistent with the latest
7849 version of the source files that can be located at bind time. Editing a
7850 source file without compiling files that depend on the source file cause
7851 error messages to be generated by the binder.
7852
7853 For example, suppose you have a main program @file{hello.adb} and a
7854 package @code{P}, from file @file{p.ads} and you perform the following
7855 steps:
7856
7857 @enumerate
7858 @item
7859 Enter @code{gcc -c hello.adb} to compile the main program.
7860
7861 @item
7862 Enter @code{gcc -c p.ads} to compile package @code{P}.
7863
7864 @item
7865 Edit file @file{p.ads}.
7866
7867 @item
7868 Enter @code{gnatbind hello}.
7869 @end enumerate
7870
7871 @noindent
7872 At this point, the file @file{p.ali} contains an out-of-date time stamp
7873 because the file @file{p.ads} has been edited. The attempt at binding
7874 fails, and the binder generates the following error messages:
7875
7876 @smallexample
7877 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7878 error: "p.ads" has been modified and must be recompiled
7879 @end smallexample
7880
7881 @noindent
7882 Now both files must be recompiled as indicated, and then the bind can
7883 succeed, generating a main program. You need not normally be concerned
7884 with the contents of this file, but for reference purposes a sample
7885 binder output file is given in @ref{Example of Binder Output File}.
7886
7887 In most normal usage, the default mode of @command{gnatbind} which is to
7888 generate the main package in Ada, as described in the previous section.
7889 In particular, this means that any Ada programmer can read and understand
7890 the generated main program. It can also be debugged just like any other
7891 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7892 @command{gnatbind} and @command{gnatlink}.
7893
7894 However for some purposes it may be convenient to generate the main
7895 program in C rather than Ada. This may for example be helpful when you
7896 are generating a mixed language program with the main program in C. The
7897 GNAT compiler itself is an example.
7898 The use of the @option{^-C^/BIND_FILE=C^} switch
7899 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7900 be generated in C (and compiled using the gnu C compiler).
7901
7902 @node Switches for gnatbind
7903 @section Switches for @command{gnatbind}
7904
7905 @noindent
7906 The following switches are available with @code{gnatbind}; details will
7907 be presented in subsequent sections.
7908
7909 @menu
7910 * Consistency-Checking Modes::
7911 * Binder Error Message Control::
7912 * Elaboration Control::
7913 * Output Control::
7914 * Binding with Non-Ada Main Programs::
7915 * Binding Programs with No Main Subprogram::
7916 @end menu
7917
7918 @table @option
7919 @c !sort!
7920
7921 @item --version
7922 @cindex @option{--version} @command{gnatbind}
7923 Display Copyright and version, then exit disregarding all other options.
7924
7925 @item --help
7926 @cindex @option{--help} @command{gnatbind}
7927 If @option{--version} was not used, display usage, then exit disregarding
7928 all other options.
7929
7930 @item -a
7931 @cindex @option{-a} @command{gnatbind}
7932 Indicates that, if supported by the platform, the adainit procedure should
7933 be treated as an initialisation routine by the linker (a constructor). This
7934 is intended to be used by the Project Manager to automatically initialize
7935 shared Stand-Alone Libraries.
7936
7937 @item ^-aO^/OBJECT_SEARCH^
7938 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7939 Specify directory to be searched for ALI files.
7940
7941 @item ^-aI^/SOURCE_SEARCH^
7942 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7943 Specify directory to be searched for source file.
7944
7945 @item ^-A^/BIND_FILE=ADA^
7946 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7947 Generate binder program in Ada (default)
7948
7949 @item ^-b^/REPORT_ERRORS=BRIEF^
7950 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7951 Generate brief messages to @file{stderr} even if verbose mode set.
7952
7953 @item ^-c^/NOOUTPUT^
7954 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7955 Check only, no generation of binder output file.
7956
7957 @item ^-C^/BIND_FILE=C^
7958 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7959 Generate binder program in C
7960
7961 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7962 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
7963 This switch can be used to change the default task stack size value
7964 to a specified size @var{nn}, which is expressed in bytes by default, or
7965 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7966 with @var{m}.
7967 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
7968 in effect, to completing all task specs with
7969 @smallexample @c ada
7970    pragma Storage_Size (nn);
7971 @end smallexample
7972 When they do not already have such a pragma.
7973
7974 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7975 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7976 This switch can be used to change the default secondary stack size value
7977 to a specified size @var{nn}, which is expressed in bytes by default, or
7978 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7979 with @var{m}.
7980
7981 The secondary stack is used to deal with functions that return a variable
7982 sized result, for example a function returning an unconstrained
7983 String. There are two ways in which this secondary stack is allocated.
7984
7985 For most targets, the secondary stack is growing on demand and is allocated
7986 as a chain of blocks in the heap. The -D option is not very
7987 relevant. It only give some control over the size of the allocated
7988 blocks (whose size is the minimum of the default secondary stack size value,
7989 and the actual size needed for the current allocation request).
7990
7991 For certain targets, notably VxWorks 653,
7992 the secondary stack is allocated by carving off a fixed ratio chunk of the
7993 primary task stack. The -D option is used to define the
7994 size of the environment task's secondary stack.
7995
7996 @item ^-e^/ELABORATION_DEPENDENCIES^
7997 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7998 Output complete list of elaboration-order dependencies.
7999
8000 @item ^-E^/STORE_TRACEBACKS^
8001 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8002 Store tracebacks in exception occurrences when the target supports it.
8003 This is the default with the zero cost exception mechanism.
8004 @ignore
8005 @c The following may get moved to an appendix
8006 This option is currently supported on the following targets:
8007 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8008 @end ignore
8009 See also the packages @code{GNAT.Traceback} and
8010 @code{GNAT.Traceback.Symbolic} for more information.
8011 @ifclear vms
8012 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8013 @command{gcc} option.
8014 @end ifclear
8015
8016 @item ^-F^/FORCE_ELABS_FLAGS^
8017 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8018 Force the checks of elaboration flags. @command{gnatbind} does not normally
8019 generate checks of elaboration flags for the main executable, except when
8020 a Stand-Alone Library is used. However, there are cases when this cannot be
8021 detected by gnatbind. An example is importing an interface of a Stand-Alone
8022 Library through a pragma Import and only specifying through a linker switch
8023 this Stand-Alone Library. This switch is used to guarantee that elaboration
8024 flag checks are generated.
8025
8026 @item ^-h^/HELP^
8027 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8028 Output usage (help) information
8029
8030 @item ^-I^/SEARCH^
8031 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8032 Specify directory to be searched for source and ALI files.
8033
8034 @item ^-I-^/NOCURRENT_DIRECTORY^
8035 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8036 Do not look for sources in the current directory where @code{gnatbind} was
8037 invoked, and do not look for ALI files in the directory containing the
8038 ALI file named in the @code{gnatbind} command line.
8039
8040 @item ^-l^/ORDER_OF_ELABORATION^
8041 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8042 Output chosen elaboration order.
8043
8044 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8045 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8046 Bind the units for library building. In this case the adainit and
8047 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8048 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8049 ^@var{xxx}final^@var{XXX}FINAL^.
8050 Implies ^-n^/NOCOMPILE^.
8051 @ifclear vms
8052 (@xref{GNAT and Libraries}, for more details.)
8053 @end ifclear
8054 @ifset vms
8055 On OpenVMS, these init and final procedures are exported in uppercase
8056 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8057 the init procedure will be "TOTOINIT" and the exported name of the final
8058 procedure will be "TOTOFINAL".
8059 @end ifset
8060
8061 @item ^-Mxyz^/RENAME_MAIN=xyz^
8062 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8063 Rename generated main program from main to xyz. This option is
8064 supported on cross environments only.
8065
8066 @item ^-m^/ERROR_LIMIT=^@var{n}
8067 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8068 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8069 in the range 1..999999. The default value if no switch is
8070 given is 9999. If the number of warnings reaches this limit, then a
8071 message is output and further warnings are suppressed, the bind
8072 continues in this case. If the number of errors reaches this
8073 limit, then a message is output and the bind is abandoned.
8074 A value of zero means that no limit is enforced. The equal
8075 sign is optional.
8076
8077 @ifset unw
8078 Furthermore, under Windows, the sources pointed to by the libraries path
8079 set in the registry are not searched for.
8080 @end ifset
8081
8082 @item ^-n^/NOMAIN^
8083 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8084 No main program.
8085
8086 @item -nostdinc
8087 @cindex @option{-nostdinc} (@command{gnatbind})
8088 Do not look for sources in the system default directory.
8089
8090 @item -nostdlib
8091 @cindex @option{-nostdlib} (@command{gnatbind})
8092 Do not look for library files in the system default directory.
8093
8094 @item --RTS=@var{rts-path}
8095 @cindex @option{--RTS} (@code{gnatbind})
8096 Specifies the default location of the runtime library. Same meaning as the
8097 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8098
8099 @item ^-o ^/OUTPUT=^@var{file}
8100 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8101 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8102 Note that if this option is used, then linking must be done manually,
8103 gnatlink cannot be used.
8104
8105 @item ^-O^/OBJECT_LIST^
8106 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8107 Output object list.
8108
8109 @item ^-p^/PESSIMISTIC_ELABORATION^
8110 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8111 Pessimistic (worst-case) elaboration order
8112
8113 @item ^-R^-R^
8114 @cindex @option{^-R^-R^} (@command{gnatbind})
8115 Output closure source list.
8116
8117 @item ^-s^/READ_SOURCES=ALL^
8118 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8119 Require all source files to be present.
8120
8121 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8122 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8123 Specifies the value to be used when detecting uninitialized scalar
8124 objects with pragma Initialize_Scalars.
8125 The @var{xxx} ^string specified with the switch^option^ may be either
8126 @itemize @bullet
8127 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8128 @item ``@option{^lo^LOW^}'' for the lowest possible value
8129 @item ``@option{^hi^HIGH^}'' for the highest possible value
8130 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8131 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8132 @end itemize
8133
8134 In addition, you can specify @option{-Sev} to indicate that the value is
8135 to be set at run time. In this case, the program will look for an environment
8136 @cindex GNAT_INIT_SCALARS
8137 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8138 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8139 If no environment variable is found, or if it does not have a valid value,
8140 then the default is @option{in} (invalid values).
8141
8142 @ifclear vms
8143 @item -static
8144 @cindex @option{-static} (@code{gnatbind})
8145 Link against a static GNAT run time.
8146
8147 @item -shared
8148 @cindex @option{-shared} (@code{gnatbind})
8149 Link against a shared GNAT run time when available.
8150 @end ifclear
8151
8152 @item ^-t^/NOTIME_STAMP_CHECK^
8153 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8154 Tolerate time stamp and other consistency errors
8155
8156 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8157 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8158 Set the time slice value to @var{n} milliseconds. If the system supports
8159 the specification of a specific time slice value, then the indicated value
8160 is used. If the system does not support specific time slice values, but
8161 does support some general notion of round-robin scheduling, then any
8162 nonzero value will activate round-robin scheduling.
8163
8164 A value of zero is treated specially. It turns off time
8165 slicing, and in addition, indicates to the tasking run time that the
8166 semantics should match as closely as possible the Annex D
8167 requirements of the Ada RM, and in particular sets the default
8168 scheduling policy to @code{FIFO_Within_Priorities}.
8169
8170 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8171 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8172 Enable dynamic stack usage, with @var{n} results stored and displayed
8173 at program termination. A result is generated when a task
8174 terminates. Results that can't be stored are displayed on the fly, at
8175 task termination. This option is currently not supported on Itanium
8176 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8177
8178 @item ^-v^/REPORT_ERRORS=VERBOSE^
8179 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8180 Verbose mode. Write error messages, header, summary output to
8181 @file{stdout}.
8182
8183 @ifclear vms
8184 @item -w@var{x}
8185 @cindex @option{-w} (@code{gnatbind})
8186 Warning mode (@var{x}=s/e for suppress/treat as error)
8187 @end ifclear
8188
8189 @ifset vms
8190 @item /WARNINGS=NORMAL
8191 @cindex @option{/WARNINGS} (@code{gnatbind})
8192 Normal warnings mode. Warnings are issued but ignored
8193
8194 @item /WARNINGS=SUPPRESS
8195 @cindex @option{/WARNINGS} (@code{gnatbind})
8196 All warning messages are suppressed
8197
8198 @item /WARNINGS=ERROR
8199 @cindex @option{/WARNINGS} (@code{gnatbind})
8200 Warning messages are treated as fatal errors
8201 @end ifset
8202
8203 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8204 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8205 Override default wide character encoding for standard Text_IO files.
8206
8207 @item ^-x^/READ_SOURCES=NONE^
8208 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8209 Exclude source files (check object consistency only).
8210
8211 @ifset vms
8212 @item /READ_SOURCES=AVAILABLE
8213 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8214 Default mode, in which sources are checked for consistency only if
8215 they are available.
8216 @end ifset
8217
8218 @item ^-y^/ENABLE_LEAP_SECONDS^
8219 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8220 Enable leap seconds support in @code{Ada.Calendar} and its children.
8221
8222 @item ^-z^/ZERO_MAIN^
8223 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8224 No main subprogram.
8225 @end table
8226
8227 @ifclear vms
8228 @noindent
8229 You may obtain this listing of switches by running @code{gnatbind} with
8230 no arguments.
8231 @end ifclear
8232
8233 @node Consistency-Checking Modes
8234 @subsection Consistency-Checking Modes
8235
8236 @noindent
8237 As described earlier, by default @code{gnatbind} checks
8238 that object files are consistent with one another and are consistent
8239 with any source files it can locate. The following switches control binder
8240 access to sources.
8241
8242 @table @option
8243 @c !sort!
8244 @item ^-s^/READ_SOURCES=ALL^
8245 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8246 Require source files to be present. In this mode, the binder must be
8247 able to locate all source files that are referenced, in order to check
8248 their consistency. In normal mode, if a source file cannot be located it
8249 is simply ignored. If you specify this switch, a missing source
8250 file is an error.
8251
8252 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8253 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8254 Override default wide character encoding for standard Text_IO files.
8255 Normally the default wide character encoding method used for standard
8256 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8257 the main source input (see description of switch
8258 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8259 use of this switch for the binder (which has the same set of
8260 possible arguments) overrides this default as specified.
8261
8262 @item ^-x^/READ_SOURCES=NONE^
8263 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8264 Exclude source files. In this mode, the binder only checks that ALI
8265 files are consistent with one another. Source files are not accessed.
8266 The binder runs faster in this mode, and there is still a guarantee that
8267 the resulting program is self-consistent.
8268 If a source file has been edited since it was last compiled, and you
8269 specify this switch, the binder will not detect that the object
8270 file is out of date with respect to the source file. Note that this is the
8271 mode that is automatically used by @command{gnatmake} because in this
8272 case the checking against sources has already been performed by
8273 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8274
8275 @ifset vms
8276 @item /READ_SOURCES=AVAILABLE
8277 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8278 This is the default mode in which source files are checked if they are
8279 available, and ignored if they are not available.
8280 @end ifset
8281 @end table
8282
8283 @node Binder Error Message Control
8284 @subsection Binder Error Message Control
8285
8286 @noindent
8287 The following switches provide control over the generation of error
8288 messages from the binder:
8289
8290 @table @option
8291 @c !sort!
8292 @item ^-v^/REPORT_ERRORS=VERBOSE^
8293 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8294 Verbose mode. In the normal mode, brief error messages are generated to
8295 @file{stderr}. If this switch is present, a header is written
8296 to @file{stdout} and any error messages are directed to @file{stdout}.
8297 All that is written to @file{stderr} is a brief summary message.
8298
8299 @item ^-b^/REPORT_ERRORS=BRIEF^
8300 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8301 Generate brief error messages to @file{stderr} even if verbose mode is
8302 specified. This is relevant only when used with the
8303 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8304
8305 @ifclear vms
8306 @item -m@var{n}
8307 @cindex @option{-m} (@code{gnatbind})
8308 Limits the number of error messages to @var{n}, a decimal integer in the
8309 range 1-999. The binder terminates immediately if this limit is reached.
8310
8311 @item -M@var{xxx}
8312 @cindex @option{-M} (@code{gnatbind})
8313 Renames the generated main program from @code{main} to @code{xxx}.
8314 This is useful in the case of some cross-building environments, where
8315 the actual main program is separate from the one generated
8316 by @code{gnatbind}.
8317 @end ifclear
8318
8319 @item ^-ws^/WARNINGS=SUPPRESS^
8320 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8321 @cindex Warnings
8322 Suppress all warning messages.
8323
8324 @item ^-we^/WARNINGS=ERROR^
8325 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8326 Treat any warning messages as fatal errors.
8327
8328 @ifset vms
8329 @item /WARNINGS=NORMAL
8330 Standard mode with warnings generated, but warnings do not get treated
8331 as errors.
8332 @end ifset
8333
8334 @item ^-t^/NOTIME_STAMP_CHECK^
8335 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8336 @cindex Time stamp checks, in binder
8337 @cindex Binder consistency checks
8338 @cindex Consistency checks, in binder
8339 The binder performs a number of consistency checks including:
8340
8341 @itemize @bullet
8342 @item
8343 Check that time stamps of a given source unit are consistent
8344 @item
8345 Check that checksums of a given source unit are consistent
8346 @item
8347 Check that consistent versions of @code{GNAT} were used for compilation
8348 @item
8349 Check consistency of configuration pragmas as required
8350 @end itemize
8351
8352 @noindent
8353 Normally failure of such checks, in accordance with the consistency
8354 requirements of the Ada Reference Manual, causes error messages to be
8355 generated which abort the binder and prevent the output of a binder
8356 file and subsequent link to obtain an executable.
8357
8358 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8359 into warnings, so that
8360 binding and linking can continue to completion even in the presence of such
8361 errors. The result may be a failed link (due to missing symbols), or a
8362 non-functional executable which has undefined semantics.
8363 @emph{This means that
8364 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8365 with extreme care.}
8366 @end table
8367
8368 @node Elaboration Control
8369 @subsection Elaboration Control
8370
8371 @noindent
8372 The following switches provide additional control over the elaboration
8373 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8374
8375 @table @option
8376 @item ^-p^/PESSIMISTIC_ELABORATION^
8377 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8378 Normally the binder attempts to choose an elaboration order that is
8379 likely to minimize the likelihood of an elaboration order error resulting
8380 in raising a @code{Program_Error} exception. This switch reverses the
8381 action of the binder, and requests that it deliberately choose an order
8382 that is likely to maximize the likelihood of an elaboration error.
8383 This is useful in ensuring portability and avoiding dependence on
8384 accidental fortuitous elaboration ordering.
8385
8386 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8387 switch if dynamic
8388 elaboration checking is used (@option{-gnatE} switch used for compilation).
8389 This is because in the default static elaboration mode, all necessary
8390 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8391 These implicit pragmas are still respected by the binder in
8392 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8393 safe elaboration order is assured.
8394 @end table
8395
8396 @node Output Control
8397 @subsection Output Control
8398
8399 @noindent
8400 The following switches allow additional control over the output
8401 generated by the binder.
8402
8403 @table @option
8404 @c !sort!
8405
8406 @item ^-A^/BIND_FILE=ADA^
8407 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
8408 Generate binder program in Ada (default). The binder program is named
8409 @file{b~@var{mainprog}.adb} by default. This can be changed with
8410 @option{^-o^/OUTPUT^} @code{gnatbind} option.
8411
8412 @item ^-c^/NOOUTPUT^
8413 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8414 Check only. Do not generate the binder output file. In this mode the
8415 binder performs all error checks but does not generate an output file.
8416
8417 @item ^-C^/BIND_FILE=C^
8418 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
8419 Generate binder program in C. The binder program is named
8420 @file{b_@var{mainprog}.c}.
8421 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
8422 option.
8423
8424 @item ^-e^/ELABORATION_DEPENDENCIES^
8425 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8426 Output complete list of elaboration-order dependencies, showing the
8427 reason for each dependency. This output can be rather extensive but may
8428 be useful in diagnosing problems with elaboration order. The output is
8429 written to @file{stdout}.
8430
8431 @item ^-h^/HELP^
8432 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8433 Output usage information. The output is written to @file{stdout}.
8434
8435 @item ^-K^/LINKER_OPTION_LIST^
8436 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8437 Output linker options to @file{stdout}. Includes library search paths,
8438 contents of pragmas Ident and Linker_Options, and libraries added
8439 by @code{gnatbind}.
8440
8441 @item ^-l^/ORDER_OF_ELABORATION^
8442 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8443 Output chosen elaboration order. The output is written to @file{stdout}.
8444
8445 @item ^-O^/OBJECT_LIST^
8446 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8447 Output full names of all the object files that must be linked to provide
8448 the Ada component of the program. The output is written to @file{stdout}.
8449 This list includes the files explicitly supplied and referenced by the user
8450 as well as implicitly referenced run-time unit files. The latter are
8451 omitted if the corresponding units reside in shared libraries. The
8452 directory names for the run-time units depend on the system configuration.
8453
8454 @item ^-o ^/OUTPUT=^@var{file}
8455 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8456 Set name of output file to @var{file} instead of the normal
8457 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8458 binder generated body filename. In C mode you would normally give
8459 @var{file} an extension of @file{.c} because it will be a C source program.
8460 Note that if this option is used, then linking must be done manually.
8461 It is not possible to use gnatlink in this case, since it cannot locate
8462 the binder file.
8463
8464 @item ^-r^/RESTRICTION_LIST^
8465 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8466 Generate list of @code{pragma Restrictions} that could be applied to
8467 the current unit. This is useful for code audit purposes, and also may
8468 be used to improve code generation in some cases.
8469
8470 @end table
8471
8472 @node Binding with Non-Ada Main Programs
8473 @subsection Binding with Non-Ada Main Programs
8474
8475 @noindent
8476 In our description so far we have assumed that the main
8477 program is in Ada, and that the task of the binder is to generate a
8478 corresponding function @code{main} that invokes this Ada main
8479 program. GNAT also supports the building of executable programs where
8480 the main program is not in Ada, but some of the called routines are
8481 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8482 The following switch is used in this situation:
8483
8484 @table @option
8485 @item ^-n^/NOMAIN^
8486 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8487 No main program. The main program is not in Ada.
8488 @end table
8489
8490 @noindent
8491 In this case, most of the functions of the binder are still required,
8492 but instead of generating a main program, the binder generates a file
8493 containing the following callable routines:
8494
8495 @table @code
8496 @item adainit
8497 @findex adainit
8498 You must call this routine to initialize the Ada part of the program by
8499 calling the necessary elaboration routines. A call to @code{adainit} is
8500 required before the first call to an Ada subprogram.
8501
8502 Note that it is assumed that the basic execution environment must be setup
8503 to be appropriate for Ada execution at the point where the first Ada
8504 subprogram is called. In particular, if the Ada code will do any
8505 floating-point operations, then the FPU must be setup in an appropriate
8506 manner. For the case of the x86, for example, full precision mode is
8507 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8508 that the FPU is in the right state.
8509
8510 @item adafinal
8511 @findex adafinal
8512 You must call this routine to perform any library-level finalization
8513 required by the Ada subprograms. A call to @code{adafinal} is required
8514 after the last call to an Ada subprogram, and before the program
8515 terminates.
8516 @end table
8517
8518 @noindent
8519 If the @option{^-n^/NOMAIN^} switch
8520 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8521 @cindex Binder, multiple input files
8522 is given, more than one ALI file may appear on
8523 the command line for @code{gnatbind}. The normal @dfn{closure}
8524 calculation is performed for each of the specified units. Calculating
8525 the closure means finding out the set of units involved by tracing
8526 @code{with} references. The reason it is necessary to be able to
8527 specify more than one ALI file is that a given program may invoke two or
8528 more quite separate groups of Ada units.
8529
8530 The binder takes the name of its output file from the last specified ALI
8531 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8532 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8533 The output is an Ada unit in source form that can
8534 be compiled with GNAT unless the -C switch is used in which case the
8535 output is a C source file, which must be compiled using the C compiler.
8536 This compilation occurs automatically as part of the @command{gnatlink}
8537 processing.
8538
8539 Currently the GNAT run time requires a FPU using 80 bits mode
8540 precision. Under targets where this is not the default it is required to
8541 call GNAT.Float_Control.Reset before using floating point numbers (this
8542 include float computation, float input and output) in the Ada code. A
8543 side effect is that this could be the wrong mode for the foreign code
8544 where floating point computation could be broken after this call.
8545
8546 @node Binding Programs with No Main Subprogram
8547 @subsection Binding Programs with No Main Subprogram
8548
8549 @noindent
8550 It is possible to have an Ada program which does not have a main
8551 subprogram. This program will call the elaboration routines of all the
8552 packages, then the finalization routines.
8553
8554 The following switch is used to bind programs organized in this manner:
8555
8556 @table @option
8557 @item ^-z^/ZERO_MAIN^
8558 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8559 Normally the binder checks that the unit name given on the command line
8560 corresponds to a suitable main subprogram. When this switch is used,
8561 a list of ALI files can be given, and the execution of the program
8562 consists of elaboration of these units in an appropriate order. Note
8563 that the default wide character encoding method for standard Text_IO
8564 files is always set to Brackets if this switch is set (you can use
8565 the binder switch
8566 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8567 @end table
8568
8569 @node Command-Line Access
8570 @section Command-Line Access
8571
8572 @noindent
8573 The package @code{Ada.Command_Line} provides access to the command-line
8574 arguments and program name. In order for this interface to operate
8575 correctly, the two variables
8576
8577 @smallexample
8578 @group
8579 int gnat_argc;
8580 char **gnat_argv;
8581 @end group
8582 @end smallexample
8583
8584 @noindent
8585 @findex gnat_argv
8586 @findex gnat_argc
8587 are declared in one of the GNAT library routines. These variables must
8588 be set from the actual @code{argc} and @code{argv} values passed to the
8589 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8590 generates the C main program to automatically set these variables.
8591 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8592 set these variables. If they are not set, the procedures in
8593 @code{Ada.Command_Line} will not be available, and any attempt to use
8594 them will raise @code{Constraint_Error}. If command line access is
8595 required, your main program must set @code{gnat_argc} and
8596 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8597 it.
8598
8599 @node Search Paths for gnatbind
8600 @section Search Paths for @code{gnatbind}
8601
8602 @noindent
8603 The binder takes the name of an ALI file as its argument and needs to
8604 locate source files as well as other ALI files to verify object consistency.
8605
8606 For source files, it follows exactly the same search rules as @command{gcc}
8607 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8608 directories searched are:
8609
8610 @enumerate
8611 @item
8612 The directory containing the ALI file named in the command line, unless
8613 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8614
8615 @item
8616 All directories specified by @option{^-I^/SEARCH^}
8617 switches on the @code{gnatbind}
8618 command line, in the order given.
8619
8620 @item
8621 @findex ADA_PRJ_OBJECTS_FILE
8622 Each of the directories listed in the text file whose name is given
8623 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8624
8625 @noindent
8626 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8627 driver when project files are used. It should not normally be set
8628 by other means.
8629
8630 @item
8631 @findex ADA_OBJECTS_PATH
8632 Each of the directories listed in the value of the
8633 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8634 @ifset unw
8635 Construct this value
8636 exactly as the @env{PATH} environment variable: a list of directory
8637 names separated by colons (semicolons when working with the NT version
8638 of GNAT).
8639 @end ifset
8640 @ifset vms
8641 Normally, define this value as a logical name containing a comma separated
8642 list of directory names.
8643
8644 This variable can also be defined by means of an environment string
8645 (an argument to the HP C exec* set of functions).
8646
8647 Logical Name:
8648 @smallexample
8649 DEFINE ANOTHER_PATH FOO:[BAG]
8650 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8651 @end smallexample
8652
8653 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8654 first, followed by the standard Ada
8655 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8656 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8657 (Text_IO, Sequential_IO, etc)
8658 instead of the standard Ada packages. Thus, in order to get the standard Ada
8659 packages by default, ADA_OBJECTS_PATH must be redefined.
8660 @end ifset
8661
8662 @item
8663 The content of the @file{ada_object_path} file which is part of the GNAT
8664 installation tree and is used to store standard libraries such as the
8665 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8666 specified.
8667 @ifclear vms
8668 @ref{Installing a library}
8669 @end ifclear
8670 @end enumerate
8671
8672 @noindent
8673 In the binder the switch @option{^-I^/SEARCH^}
8674 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8675 is used to specify both source and
8676 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8677 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8678 instead if you want to specify
8679 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8680 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8681 if you want to specify library paths
8682 only. This means that for the binder
8683 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8684 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8685 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8686 The binder generates the bind file (a C language source file) in the
8687 current working directory.
8688
8689 @findex Ada
8690 @findex System
8691 @findex Interfaces
8692 @findex GNAT
8693 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8694 children make up the GNAT Run-Time Library, together with the package
8695 GNAT and its children, which contain a set of useful additional
8696 library functions provided by GNAT. The sources for these units are
8697 needed by the compiler and are kept together in one directory. The ALI
8698 files and object files generated by compiling the RTL are needed by the
8699 binder and the linker and are kept together in one directory, typically
8700 different from the directory containing the sources. In a normal
8701 installation, you need not specify these directory names when compiling
8702 or binding. Either the environment variables or the built-in defaults
8703 cause these files to be found.
8704
8705 Besides simplifying access to the RTL, a major use of search paths is
8706 in compiling sources from multiple directories. This can make
8707 development environments much more flexible.
8708
8709 @node Examples of gnatbind Usage
8710 @section Examples of @code{gnatbind} Usage
8711
8712 @noindent
8713 This section contains a number of examples of using the GNAT binding
8714 utility @code{gnatbind}.
8715
8716 @table @code
8717 @item gnatbind hello
8718 The main program @code{Hello} (source program in @file{hello.adb}) is
8719 bound using the standard switch settings. The generated main program is
8720 @file{b~hello.adb}. This is the normal, default use of the binder.
8721
8722 @ifclear vms
8723 @item gnatbind hello -o mainprog.adb
8724 @end ifclear
8725 @ifset vms
8726 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8727 @end ifset
8728 The main program @code{Hello} (source program in @file{hello.adb}) is
8729 bound using the standard switch settings. The generated main program is
8730 @file{mainprog.adb} with the associated spec in
8731 @file{mainprog.ads}. Note that you must specify the body here not the
8732 spec, in the case where the output is in Ada. Note that if this option
8733 is used, then linking must be done manually, since gnatlink will not
8734 be able to find the generated file.
8735
8736 @ifclear vms
8737 @item gnatbind main -C -o mainprog.c -x
8738 @end ifclear
8739 @ifset vms
8740 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8741 @end ifset
8742 The main program @code{Main} (source program in
8743 @file{main.adb}) is bound, excluding source files from the
8744 consistency checking, generating
8745 the file @file{mainprog.c}.
8746
8747 @ifclear vms
8748 @item gnatbind -x main_program -C -o mainprog.c
8749 This command is exactly the same as the previous example. Switches may
8750 appear anywhere in the command line, and single letter switches may be
8751 combined into a single switch.
8752 @end ifclear
8753
8754 @ifclear vms
8755 @item gnatbind -n math dbase -C -o ada-control.c
8756 @end ifclear
8757 @ifset vms
8758 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8759 @end ifset
8760 The main program is in a language other than Ada, but calls to
8761 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8762 to @code{gnatbind} generates the file @file{ada-control.c} containing
8763 the @code{adainit} and @code{adafinal} routines to be called before and
8764 after accessing the Ada units.
8765 @end table
8766
8767 @c ------------------------------------
8768 @node Linking Using gnatlink
8769 @chapter Linking Using @command{gnatlink}
8770 @c ------------------------------------
8771 @findex gnatlink
8772
8773 @noindent
8774 This chapter discusses @command{gnatlink}, a tool that links
8775 an Ada program and builds an executable file. This utility
8776 invokes the system linker ^(via the @command{gcc} command)^^
8777 with a correct list of object files and library references.
8778 @command{gnatlink} automatically determines the list of files and
8779 references for the Ada part of a program. It uses the binder file
8780 generated by the @command{gnatbind} to determine this list.
8781
8782 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8783 driver (see @ref{The GNAT Driver and Project Files}).
8784
8785 @menu
8786 * Running gnatlink::
8787 * Switches for gnatlink::
8788 @end menu
8789
8790 @node Running gnatlink
8791 @section Running @command{gnatlink}
8792
8793 @noindent
8794 The form of the @command{gnatlink} command is
8795
8796 @smallexample
8797 $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8798            @ovar{non-Ada objects} @ovar{linker options}
8799 @end smallexample
8800
8801 @noindent
8802 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8803 non-Ada objects
8804 or linker options) may be in any order, provided that no non-Ada object may
8805 be mistaken for a main @file{ALI} file.
8806 Any file name @file{F} without the @file{.ali}
8807 extension will be taken as the main @file{ALI} file if a file exists
8808 whose name is the concatenation of @file{F} and @file{.ali}.
8809
8810 @noindent
8811 @file{@var{mainprog}.ali} references the ALI file of the main program.
8812 The @file{.ali} extension of this file can be omitted. From this
8813 reference, @command{gnatlink} locates the corresponding binder file
8814 @file{b~@var{mainprog}.adb} and, using the information in this file along
8815 with the list of non-Ada objects and linker options, constructs a
8816 linker command file to create the executable.
8817
8818 The arguments other than the @command{gnatlink} switches and the main
8819 @file{ALI} file are passed to the linker uninterpreted.
8820 They typically include the names of
8821 object files for units written in other languages than Ada and any library
8822 references required to resolve references in any of these foreign language
8823 units, or in @code{Import} pragmas in any Ada units.
8824
8825 @var{linker options} is an optional list of linker specific
8826 switches.
8827 The default linker called by gnatlink is @command{gcc} which in
8828 turn calls the appropriate system linker.
8829 Standard options for the linker such as @option{-lmy_lib} or
8830 @option{-Ldir} can be added as is.
8831 For options that are not recognized by
8832 @command{gcc} as linker options, use the @command{gcc} switches
8833 @option{-Xlinker} or @option{-Wl,}.
8834 Refer to the GCC documentation for
8835 details. Here is an example showing how to generate a linker map:
8836
8837 @smallexample
8838 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8839 @end smallexample
8840
8841 Using @var{linker options} it is possible to set the program stack and
8842 heap size.
8843 @ifset unw
8844 See @ref{Setting Stack Size from gnatlink} and
8845 @ref{Setting Heap Size from gnatlink}.
8846 @end ifset
8847
8848 @command{gnatlink} determines the list of objects required by the Ada
8849 program and prepends them to the list of objects passed to the linker.
8850 @command{gnatlink} also gathers any arguments set by the use of
8851 @code{pragma Linker_Options} and adds them to the list of arguments
8852 presented to the linker.
8853
8854 @ifset vms
8855 @command{gnatlink} accepts the following types of extra files on the command
8856 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8857 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8858 handled according to their extension.
8859 @end ifset
8860
8861 @node Switches for gnatlink
8862 @section Switches for @command{gnatlink}
8863
8864 @noindent
8865 The following switches are available with the @command{gnatlink} utility:
8866
8867 @table @option
8868 @c !sort!
8869
8870 @item --version
8871 @cindex @option{--version} @command{gnatlink}
8872 Display Copyright and version, then exit disregarding all other options.
8873
8874 @item --help
8875 @cindex @option{--help} @command{gnatlink}
8876 If @option{--version} was not used, display usage, then exit disregarding
8877 all other options.
8878
8879 @item ^-A^/BIND_FILE=ADA^
8880 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8881 The binder has generated code in Ada. This is the default.
8882
8883 @item ^-C^/BIND_FILE=C^
8884 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8885 If instead of generating a file in Ada, the binder has generated one in
8886 C, then the linker needs to know about it. Use this switch to signal
8887 to @command{gnatlink} that the binder has generated C code rather than
8888 Ada code.
8889
8890 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8891 @cindex Command line length
8892 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8893 On some targets, the command line length is limited, and @command{gnatlink}
8894 will generate a separate file for the linker if the list of object files
8895 is too long.
8896 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8897 to be generated even if
8898 the limit is not exceeded. This is useful in some cases to deal with
8899 special situations where the command line length is exceeded.
8900
8901 @item ^-g^/DEBUG^
8902 @cindex Debugging information, including
8903 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8904 The option to include debugging information causes the Ada bind file (in
8905 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8906 @option{^-g^/DEBUG^}.
8907 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8908 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8909 Without @option{^-g^/DEBUG^}, the binder removes these files by
8910 default. The same procedure apply if a C bind file was generated using
8911 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8912 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8913
8914 @item ^-n^/NOCOMPILE^
8915 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8916 Do not compile the file generated by the binder. This may be used when
8917 a link is rerun with different options, but there is no need to recompile
8918 the binder file.
8919
8920 @item ^-v^/VERBOSE^
8921 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8922 Causes additional information to be output, including a full list of the
8923 included object files. This switch option is most useful when you want
8924 to see what set of object files are being used in the link step.
8925
8926 @item ^-v -v^/VERBOSE/VERBOSE^
8927 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8928 Very verbose mode. Requests that the compiler operate in verbose mode when
8929 it compiles the binder file, and that the system linker run in verbose mode.
8930
8931 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8932 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8933 @var{exec-name} specifies an alternate name for the generated
8934 executable program. If this switch is omitted, the executable has the same
8935 name as the main unit. For example, @code{gnatlink try.ali} creates
8936 an executable called @file{^try^TRY.EXE^}.
8937
8938 @ifclear vms
8939 @item -b @var{target}
8940 @cindex @option{-b} (@command{gnatlink})
8941 Compile your program to run on @var{target}, which is the name of a
8942 system configuration. You must have a GNAT cross-compiler built if
8943 @var{target} is not the same as your host system.
8944
8945 @item -B@var{dir}
8946 @cindex @option{-B} (@command{gnatlink})
8947 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8948 from @var{dir} instead of the default location. Only use this switch
8949 when multiple versions of the GNAT compiler are available.
8950 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8951 for further details. You would normally use the @option{-b} or
8952 @option{-V} switch instead.
8953
8954 @item --GCC=@var{compiler_name}
8955 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8956 Program used for compiling the binder file. The default is
8957 @command{gcc}. You need to use quotes around @var{compiler_name} if
8958 @code{compiler_name} contains spaces or other separator characters.
8959 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8960 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8961 inserted after your command name. Thus in the above example the compiler
8962 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8963 A limitation of this syntax is that the name and path name of the executable
8964 itself must not include any embedded spaces. If the compiler executable is
8965 different from the default one (gcc or <prefix>-gcc), then the back-end
8966 switches in the ALI file are not used to compile the binder generated source.
8967 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
8968 switches will be used for @option{--GCC="gcc -gnatv"}. If several
8969 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8970 is taken into account. However, all the additional switches are also taken
8971 into account. Thus,
8972 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8973 @option{--GCC="bar -x -y -z -t"}.
8974
8975 @item --LINK=@var{name}
8976 @cindex @option{--LINK=} (@command{gnatlink})
8977 @var{name} is the name of the linker to be invoked. This is especially
8978 useful in mixed language programs since languages such as C++ require
8979 their own linker to be used. When this switch is omitted, the default
8980 name for the linker is @command{gcc}. When this switch is used, the
8981 specified linker is called instead of @command{gcc} with exactly the same
8982 parameters that would have been passed to @command{gcc} so if the desired
8983 linker requires different parameters it is necessary to use a wrapper
8984 script that massages the parameters before invoking the real linker. It
8985 may be useful to control the exact invocation by using the verbose
8986 switch.
8987
8988 @end ifclear
8989
8990 @ifset vms
8991 @item /DEBUG=TRACEBACK
8992 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8993 This qualifier causes sufficient information to be included in the
8994 executable file to allow a traceback, but does not include the full
8995 symbol information needed by the debugger.
8996
8997 @item /IDENTIFICATION="<string>"
8998 @code{"<string>"} specifies the string to be stored in the image file
8999 identification field in the image header.
9000 It overrides any pragma @code{Ident} specified string.
9001
9002 @item /NOINHIBIT-EXEC
9003 Generate the executable file even if there are linker warnings.
9004
9005 @item /NOSTART_FILES
9006 Don't link in the object file containing the ``main'' transfer address.
9007 Used when linking with a foreign language main program compiled with an
9008 HP compiler.
9009
9010 @item /STATIC
9011 Prefer linking with object libraries over sharable images, even without
9012 /DEBUG.
9013 @end ifset
9014
9015 @end table
9016
9017 @node The GNAT Make Program gnatmake
9018 @chapter The GNAT Make Program @command{gnatmake}
9019 @findex gnatmake
9020
9021 @menu
9022 * Running gnatmake::
9023 * Switches for gnatmake::
9024 * Mode Switches for gnatmake::
9025 * Notes on the Command Line::
9026 * How gnatmake Works::
9027 * Examples of gnatmake Usage::
9028 @end menu
9029 @noindent
9030 A typical development cycle when working on an Ada program consists of
9031 the following steps:
9032
9033 @enumerate
9034 @item
9035 Edit some sources to fix bugs.
9036
9037 @item
9038 Add enhancements.
9039
9040 @item
9041 Compile all sources affected.
9042
9043 @item
9044 Rebind and relink.
9045
9046 @item
9047 Test.
9048 @end enumerate
9049
9050 @noindent
9051 The third step can be tricky, because not only do the modified files
9052 @cindex Dependency rules
9053 have to be compiled, but any files depending on these files must also be
9054 recompiled. The dependency rules in Ada can be quite complex, especially
9055 in the presence of overloading, @code{use} clauses, generics and inlined
9056 subprograms.
9057
9058 @command{gnatmake} automatically takes care of the third and fourth steps
9059 of this process. It determines which sources need to be compiled,
9060 compiles them, and binds and links the resulting object files.
9061
9062 Unlike some other Ada make programs, the dependencies are always
9063 accurately recomputed from the new sources. The source based approach of
9064 the GNAT compilation model makes this possible. This means that if
9065 changes to the source program cause corresponding changes in
9066 dependencies, they will always be tracked exactly correctly by
9067 @command{gnatmake}.
9068
9069 @node Running gnatmake
9070 @section Running @command{gnatmake}
9071
9072 @noindent
9073 The usual form of the @command{gnatmake} command is
9074
9075 @smallexample
9076 $ gnatmake @ovar{switches} @var{file_name}
9077       @ovar{file_names} @ovar{mode_switches}
9078 @end smallexample
9079
9080 @noindent
9081 The only required argument is one @var{file_name}, which specifies
9082 a compilation unit that is a main program. Several @var{file_names} can be
9083 specified: this will result in several executables being built.
9084 If @code{switches} are present, they can be placed before the first
9085 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9086 If @var{mode_switches} are present, they must always be placed after
9087 the last @var{file_name} and all @code{switches}.
9088
9089 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9090 extension may be omitted from the @var{file_name} arguments. However, if
9091 you are using non-standard extensions, then it is required that the
9092 extension be given. A relative or absolute directory path can be
9093 specified in a @var{file_name}, in which case, the input source file will
9094 be searched for in the specified directory only. Otherwise, the input
9095 source file will first be searched in the directory where
9096 @command{gnatmake} was invoked and if it is not found, it will be search on
9097 the source path of the compiler as described in
9098 @ref{Search Paths and the Run-Time Library (RTL)}.
9099
9100 All @command{gnatmake} output (except when you specify
9101 @option{^-M^/DEPENDENCIES_LIST^}) is to
9102 @file{stderr}. The output produced by the
9103 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9104 @file{stdout}.
9105
9106 @node Switches for gnatmake
9107 @section Switches for @command{gnatmake}
9108
9109 @noindent
9110 You may specify any of the following switches to @command{gnatmake}:
9111
9112 @table @option
9113 @c !sort!
9114
9115 @item --version
9116 @cindex @option{--version} @command{gnatmake}
9117 Display Copyright and version, then exit disregarding all other options.
9118
9119 @item --help
9120 @cindex @option{--help} @command{gnatmake}
9121 If @option{--version} was not used, display usage, then exit disregarding
9122 all other options.
9123
9124 @ifclear vms
9125 @item --GCC=@var{compiler_name}
9126 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9127 Program used for compiling. The default is `@command{gcc}'. You need to use
9128 quotes around @var{compiler_name} if @code{compiler_name} contains
9129 spaces or other separator characters. As an example @option{--GCC="foo -x
9130 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9131 compiler. A limitation of this syntax is that the name and path name of
9132 the executable itself must not include any embedded spaces. Note that
9133 switch @option{-c} is always inserted after your command name. Thus in the
9134 above example the compiler command that will be used by @command{gnatmake}
9135 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9136 used, only the last @var{compiler_name} is taken into account. However,
9137 all the additional switches are also taken into account. Thus,
9138 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9139 @option{--GCC="bar -x -y -z -t"}.
9140
9141 @item --GNATBIND=@var{binder_name}
9142 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9143 Program used for binding. The default is `@code{gnatbind}'. You need to
9144 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9145 or other separator characters. As an example @option{--GNATBIND="bar -x
9146 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9147 binder. Binder switches that are normally appended by @command{gnatmake}
9148 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9149 A limitation of this syntax is that the name and path name of the executable
9150 itself must not include any embedded spaces.
9151
9152 @item --GNATLINK=@var{linker_name}
9153 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9154 Program used for linking. The default is `@command{gnatlink}'. You need to
9155 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9156 or other separator characters. As an example @option{--GNATLINK="lan -x
9157 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9158 linker. Linker switches that are normally appended by @command{gnatmake} to
9159 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9160 A limitation of this syntax is that the name and path name of the executable
9161 itself must not include any embedded spaces.
9162
9163 @end ifclear
9164
9165 @item ^-a^/ALL_FILES^
9166 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9167 Consider all files in the make process, even the GNAT internal system
9168 files (for example, the predefined Ada library files), as well as any
9169 locked files. Locked files are files whose ALI file is write-protected.
9170 By default,
9171 @command{gnatmake} does not check these files,
9172 because the assumption is that the GNAT internal files are properly up
9173 to date, and also that any write protected ALI files have been properly
9174 installed. Note that if there is an installation problem, such that one
9175 of these files is not up to date, it will be properly caught by the
9176 binder.
9177 You may have to specify this switch if you are working on GNAT
9178 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9179 in conjunction with @option{^-f^/FORCE_COMPILE^}
9180 if you need to recompile an entire application,
9181 including run-time files, using special configuration pragmas,
9182 such as a @code{Normalize_Scalars} pragma.
9183
9184 By default
9185 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9186 internal files with
9187 @ifclear vms
9188 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9189 @end ifclear
9190 @ifset vms
9191 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9192 @end ifset
9193
9194 @item ^-b^/ACTIONS=BIND^
9195 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9196 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9197 compilation and binding, but no link.
9198 Can be combined with @option{^-l^/ACTIONS=LINK^}
9199 to do binding and linking. When not combined with
9200 @option{^-c^/ACTIONS=COMPILE^}
9201 all the units in the closure of the main program must have been previously
9202 compiled and must be up to date. The root unit specified by @var{file_name}
9203 may be given without extension, with the source extension or, if no GNAT
9204 Project File is specified, with the ALI file extension.
9205
9206 @item ^-c^/ACTIONS=COMPILE^
9207 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9208 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9209 is also specified. Do not perform linking, except if both
9210 @option{^-b^/ACTIONS=BIND^} and
9211 @option{^-l^/ACTIONS=LINK^} are also specified.
9212 If the root unit specified by @var{file_name} is not a main unit, this is the
9213 default. Otherwise @command{gnatmake} will attempt binding and linking
9214 unless all objects are up to date and the executable is more recent than
9215 the objects.
9216
9217 @item ^-C^/MAPPING^
9218 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9219 Use a temporary mapping file. A mapping file is a way to communicate to the
9220 compiler two mappings: from unit names to file names (without any directory
9221 information) and from file names to path names (with full directory
9222 information). These mappings are used by the compiler to short-circuit the path
9223 search. When @command{gnatmake} is invoked with this switch, it will create
9224 a temporary mapping file, initially populated by the project manager,
9225 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
9226 Each invocation of the compiler will add the newly accessed sources to the
9227 mapping file. This will improve the source search during the next invocation
9228 of the compiler.
9229
9230 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9231 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9232 Use a specific mapping file. The file, specified as a path name (absolute or
9233 relative) by this switch, should already exist, otherwise the switch is
9234 ineffective. The specified mapping file will be communicated to the compiler.
9235 This switch is not compatible with a project file
9236 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9237 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9238
9239 @item ^-d^/DISPLAY_PROGRESS^
9240 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9241 Display progress for each source, up to date or not, as a single line
9242
9243 @smallexample
9244 completed x out of y (zz%)
9245 @end smallexample
9246
9247 If the file needs to be compiled this is displayed after the invocation of
9248 the compiler. These lines are displayed even in quiet output mode.
9249
9250 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9251 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9252 Put all object files and ALI file in directory @var{dir}.
9253 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9254 and ALI files go in the current working directory.
9255
9256 This switch cannot be used when using a project file.
9257
9258 @ifclear vms
9259 @item -eL
9260 @cindex @option{-eL} (@command{gnatmake})
9261 Follow all symbolic links when processing project files.
9262 @end ifclear
9263
9264 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9265 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9266 Output the commands for the compiler, the binder and the linker
9267 on ^standard output^SYS$OUTPUT^,
9268 instead of ^standard error^SYS$ERROR^.
9269
9270 @item ^-f^/FORCE_COMPILE^
9271 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9272 Force recompilations. Recompile all sources, even though some object
9273 files may be up to date, but don't recompile predefined or GNAT internal
9274 files or locked files (files with a write-protected ALI file),
9275 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9276
9277 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9278 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9279 When using project files, if some errors or warnings are detected during
9280 parsing and verbose mode is not in effect (no use of switch
9281 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9282 file, rather than its simple file name.
9283
9284 @item ^-g^/DEBUG^
9285 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9286 Enable debugging. This switch is simply passed to the compiler and to the
9287 linker.
9288
9289 @item ^-i^/IN_PLACE^
9290 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9291 In normal mode, @command{gnatmake} compiles all object files and ALI files
9292 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9293 then instead object files and ALI files that already exist are overwritten
9294 in place. This means that once a large project is organized into separate
9295 directories in the desired manner, then @command{gnatmake} will automatically
9296 maintain and update this organization. If no ALI files are found on the
9297 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9298 the new object and ALI files are created in the
9299 directory containing the source being compiled. If another organization
9300 is desired, where objects and sources are kept in different directories,
9301 a useful technique is to create dummy ALI files in the desired directories.
9302 When detecting such a dummy file, @command{gnatmake} will be forced to
9303 recompile the corresponding source file, and it will be put the resulting
9304 object and ALI files in the directory where it found the dummy file.
9305
9306 @item ^-j^/PROCESSES=^@var{n}
9307 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9308 @cindex Parallel make
9309 Use @var{n} processes to carry out the (re)compilations. On a
9310 multiprocessor machine compilations will occur in parallel. In the
9311 event of compilation errors, messages from various compilations might
9312 get interspersed (but @command{gnatmake} will give you the full ordered
9313 list of failing compiles at the end). If this is problematic, rerun
9314 the make process with n set to 1 to get a clean list of messages.
9315
9316 @item ^-k^/CONTINUE_ON_ERROR^
9317 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9318 Keep going. Continue as much as possible after a compilation error. To
9319 ease the programmer's task in case of compilation errors, the list of
9320 sources for which the compile fails is given when @command{gnatmake}
9321 terminates.
9322
9323 If @command{gnatmake} is invoked with several @file{file_names} and with this
9324 switch, if there are compilation errors when building an executable,
9325 @command{gnatmake} will not attempt to build the following executables.
9326
9327 @item ^-l^/ACTIONS=LINK^
9328 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9329 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9330 and linking. Linking will not be performed if combined with
9331 @option{^-c^/ACTIONS=COMPILE^}
9332 but not with @option{^-b^/ACTIONS=BIND^}.
9333 When not combined with @option{^-b^/ACTIONS=BIND^}
9334 all the units in the closure of the main program must have been previously
9335 compiled and must be up to date, and the main program needs to have been bound.
9336 The root unit specified by @var{file_name}
9337 may be given without extension, with the source extension or, if no GNAT
9338 Project File is specified, with the ALI file extension.
9339
9340 @item ^-m^/MINIMAL_RECOMPILATION^
9341 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9342 Specify that the minimum necessary amount of recompilations
9343 be performed. In this mode @command{gnatmake} ignores time
9344 stamp differences when the only
9345 modifications to a source file consist in adding/removing comments,
9346 empty lines, spaces or tabs. This means that if you have changed the
9347 comments in a source file or have simply reformatted it, using this
9348 switch will tell @command{gnatmake} not to recompile files that depend on it
9349 (provided other sources on which these files depend have undergone no
9350 semantic modifications). Note that the debugging information may be
9351 out of date with respect to the sources if the @option{-m} switch causes
9352 a compilation to be switched, so the use of this switch represents a
9353 trade-off between compilation time and accurate debugging information.
9354
9355 @item ^-M^/DEPENDENCIES_LIST^
9356 @cindex Dependencies, producing list
9357 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9358 Check if all objects are up to date. If they are, output the object
9359 dependences to @file{stdout} in a form that can be directly exploited in
9360 a @file{Makefile}. By default, each source file is prefixed with its
9361 (relative or absolute) directory name. This name is whatever you
9362 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9363 and @option{^-I^/SEARCH^} switches. If you use
9364 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9365 @option{^-q^/QUIET^}
9366 (see below), only the source file names,
9367 without relative paths, are output. If you just specify the
9368 @option{^-M^/DEPENDENCIES_LIST^}
9369 switch, dependencies of the GNAT internal system files are omitted. This
9370 is typically what you want. If you also specify
9371 the @option{^-a^/ALL_FILES^} switch,
9372 dependencies of the GNAT internal files are also listed. Note that
9373 dependencies of the objects in external Ada libraries (see switch
9374 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9375 are never reported.
9376
9377 @item ^-n^/DO_OBJECT_CHECK^
9378 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9379 Don't compile, bind, or link. Checks if all objects are up to date.
9380 If they are not, the full name of the first file that needs to be
9381 recompiled is printed.
9382 Repeated use of this option, followed by compiling the indicated source
9383 file, will eventually result in recompiling all required units.
9384
9385 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9386 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9387 Output executable name. The name of the final executable program will be
9388 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9389 name for the executable will be the name of the input file in appropriate form
9390 for an executable file on the host system.
9391
9392 This switch cannot be used when invoking @command{gnatmake} with several
9393 @file{file_names}.
9394
9395 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9396 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9397 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9398 automatically missing object directories, library directories and exec
9399 directories.
9400
9401 @item ^-P^/PROJECT_FILE=^@var{project}
9402 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9403 Use project file @var{project}. Only one such switch can be used.
9404 @xref{gnatmake and Project Files}.
9405
9406 @item ^-q^/QUIET^
9407 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9408 Quiet. When this flag is not set, the commands carried out by
9409 @command{gnatmake} are displayed.
9410
9411 @item ^-s^/SWITCH_CHECK/^
9412 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9413 Recompile if compiler switches have changed since last compilation.
9414 All compiler switches but -I and -o are taken into account in the
9415 following way:
9416 orders between different ``first letter'' switches are ignored, but
9417 orders between same switches are taken into account. For example,
9418 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9419 is equivalent to @option{-O -g}.
9420
9421 This switch is recommended when Integrated Preprocessing is used.
9422
9423 @item ^-u^/UNIQUE^
9424 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9425 Unique. Recompile at most the main files. It implies -c. Combined with
9426 -f, it is equivalent to calling the compiler directly. Note that using
9427 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9428 (@pxref{Project Files and Main Subprograms}).
9429
9430 @item ^-U^/ALL_PROJECTS^
9431 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9432 When used without a project file or with one or several mains on the command
9433 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9434 on the command line, all sources of all project files are checked and compiled
9435 if not up to date, and libraries are rebuilt, if necessary.
9436
9437 @item ^-v^/REASONS^
9438 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9439 Verbose. Display the reason for all recompilations @command{gnatmake}
9440 decides are necessary, with the highest verbosity level.
9441
9442 @item ^-vl^/LOW_VERBOSITY^
9443 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9444 Verbosity level Low. Display fewer lines than in verbosity Medium.
9445
9446 @item ^-vm^/MEDIUM_VERBOSITY^
9447 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9448 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9449
9450 @item ^-vh^/HIGH_VERBOSITY^
9451 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9452 Verbosity level High. Equivalent to ^-v^/REASONS^.
9453
9454 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9455 Indicate the verbosity of the parsing of GNAT project files.
9456 @xref{Switches Related to Project Files}.
9457
9458 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9459 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9460 Indicate that sources that are not part of any Project File may be compiled.
9461 Normally, when using Project Files, only sources that are part of a Project
9462 File may be compile. When this switch is used, a source outside of all Project
9463 Files may be compiled. The ALI file and the object file will be put in the
9464 object directory of the main Project. The compilation switches used will only
9465 be those specified on the command line. Even when
9466 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9467 command line need to be sources of a project file.
9468
9469 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9470 Indicate that external variable @var{name} has the value @var{value}.
9471 The Project Manager will use this value for occurrences of
9472 @code{external(name)} when parsing the project file.
9473 @xref{Switches Related to Project Files}.
9474
9475 @item ^-z^/NOMAIN^
9476 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9477 No main subprogram. Bind and link the program even if the unit name
9478 given on the command line is a package name. The resulting executable
9479 will execute the elaboration routines of the package and its closure,
9480 then the finalization routines.
9481
9482 @end table
9483
9484 @table @asis
9485 @item @command{gcc} @asis{switches}
9486 @ifclear vms
9487 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9488 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9489 @end ifclear
9490 @ifset vms
9491 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9492 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9493 automatically treated as a compiler switch, and passed on to all
9494 compilations that are carried out.
9495 @end ifset
9496 @end table
9497
9498 @noindent
9499 Source and library search path switches:
9500
9501 @table @option
9502 @c !sort!
9503 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9504 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9505 When looking for source files also look in directory @var{dir}.
9506 The order in which source files search is undertaken is
9507 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9508
9509 @item ^-aL^/SKIP_MISSING=^@var{dir}
9510 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9511 Consider @var{dir} as being an externally provided Ada library.
9512 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9513 files have been located in directory @var{dir}. This allows you to have
9514 missing bodies for the units in @var{dir} and to ignore out of date bodies
9515 for the same units. You still need to specify
9516 the location of the specs for these units by using the switches
9517 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9518 or @option{^-I^/SEARCH=^@var{dir}}.
9519 Note: this switch is provided for compatibility with previous versions
9520 of @command{gnatmake}. The easier method of causing standard libraries
9521 to be excluded from consideration is to write-protect the corresponding
9522 ALI files.
9523
9524 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9525 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9526 When searching for library and object files, look in directory
9527 @var{dir}. The order in which library files are searched is described in
9528 @ref{Search Paths for gnatbind}.
9529
9530 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9531 @cindex Search paths, for @command{gnatmake}
9532 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9533 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9534 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9535
9536 @item ^-I^/SEARCH=^@var{dir}
9537 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9538 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9539 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9540
9541 @item ^-I-^/NOCURRENT_DIRECTORY^
9542 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9543 @cindex Source files, suppressing search
9544 Do not look for source files in the directory containing the source
9545 file named in the command line.
9546 Do not look for ALI or object files in the directory
9547 where @command{gnatmake} was invoked.
9548
9549 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9550 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9551 @cindex Linker libraries
9552 Add directory @var{dir} to the list of directories in which the linker
9553 will search for libraries. This is equivalent to
9554 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9555 @ifclear vms
9556 Furthermore, under Windows, the sources pointed to by the libraries path
9557 set in the registry are not searched for.
9558 @end ifclear
9559
9560 @item -nostdinc
9561 @cindex @option{-nostdinc} (@command{gnatmake})
9562 Do not look for source files in the system default directory.
9563
9564 @item -nostdlib
9565 @cindex @option{-nostdlib} (@command{gnatmake})
9566 Do not look for library files in the system default directory.
9567
9568 @item --RTS=@var{rts-path}
9569 @cindex @option{--RTS} (@command{gnatmake})
9570 Specifies the default location of the runtime library. GNAT looks for the
9571 runtime
9572 in the following directories, and stops as soon as a valid runtime is found
9573 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9574 @file{ada_object_path} present):
9575
9576 @itemize @bullet
9577 @item <current directory>/$rts_path
9578
9579 @item <default-search-dir>/$rts_path
9580
9581 @item <default-search-dir>/rts-$rts_path
9582 @end itemize
9583
9584 @noindent
9585 The selected path is handled like a normal RTS path.
9586
9587 @end table
9588
9589 @node Mode Switches for gnatmake
9590 @section Mode Switches for @command{gnatmake}
9591
9592 @noindent
9593 The mode switches (referred to as @code{mode_switches}) allow the
9594 inclusion of switches that are to be passed to the compiler itself, the
9595 binder or the linker. The effect of a mode switch is to cause all
9596 subsequent switches up to the end of the switch list, or up to the next
9597 mode switch, to be interpreted as switches to be passed on to the
9598 designated component of GNAT.
9599
9600 @table @option
9601 @c !sort!
9602 @item -cargs @var{switches}
9603 @cindex @option{-cargs} (@command{gnatmake})
9604 Compiler switches. Here @var{switches} is a list of switches
9605 that are valid switches for @command{gcc}. They will be passed on to
9606 all compile steps performed by @command{gnatmake}.
9607
9608 @item -bargs @var{switches}
9609 @cindex @option{-bargs} (@command{gnatmake})
9610 Binder switches. Here @var{switches} is a list of switches
9611 that are valid switches for @code{gnatbind}. They will be passed on to
9612 all bind steps performed by @command{gnatmake}.
9613
9614 @item -largs @var{switches}
9615 @cindex @option{-largs} (@command{gnatmake})
9616 Linker switches. Here @var{switches} is a list of switches
9617 that are valid switches for @command{gnatlink}. They will be passed on to
9618 all link steps performed by @command{gnatmake}.
9619
9620 @item -margs @var{switches}
9621 @cindex @option{-margs} (@command{gnatmake})
9622 Make switches. The switches are directly interpreted by @command{gnatmake},
9623 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9624 or @option{-largs}.
9625 @end table
9626
9627 @node Notes on the Command Line
9628 @section Notes on the Command Line
9629
9630 @noindent
9631 This section contains some additional useful notes on the operation
9632 of the @command{gnatmake} command.
9633
9634 @itemize @bullet
9635 @item
9636 @cindex Recompilation, by @command{gnatmake}
9637 If @command{gnatmake} finds no ALI files, it recompiles the main program
9638 and all other units required by the main program.
9639 This means that @command{gnatmake}
9640 can be used for the initial compile, as well as during subsequent steps of
9641 the development cycle.
9642
9643 @item
9644 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9645 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9646 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9647 warning.
9648
9649 @item
9650 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9651 is used to specify both source and
9652 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9653 instead if you just want to specify
9654 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9655 if you want to specify library paths
9656 only.
9657
9658 @item
9659 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9660 This may conveniently be used to exclude standard libraries from
9661 consideration and in particular it means that the use of the
9662 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9663 unless @option{^-a^/ALL_FILES^} is also specified.
9664
9665 @item
9666 @command{gnatmake} has been designed to make the use of Ada libraries
9667 particularly convenient. Assume you have an Ada library organized
9668 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9669 of your Ada compilation units,
9670 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9671 specs of these units, but no bodies. Then to compile a unit
9672 stored in @code{main.adb}, which uses this Ada library you would just type
9673
9674 @smallexample
9675 @ifclear vms
9676 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9677 @end ifclear
9678 @ifset vms
9679 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9680            /SKIP_MISSING=@i{[OBJ_DIR]} main
9681 @end ifset
9682 @end smallexample
9683
9684 @item
9685 Using @command{gnatmake} along with the
9686 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9687 switch provides a mechanism for avoiding unnecessary recompilations. Using
9688 this switch,
9689 you can update the comments/format of your
9690 source files without having to recompile everything. Note, however, that
9691 adding or deleting lines in a source files may render its debugging
9692 info obsolete. If the file in question is a spec, the impact is rather
9693 limited, as that debugging info will only be useful during the
9694 elaboration phase of your program. For bodies the impact can be more
9695 significant. In all events, your debugger will warn you if a source file
9696 is more recent than the corresponding object, and alert you to the fact
9697 that the debugging information may be out of date.
9698 @end itemize
9699
9700 @node How gnatmake Works
9701 @section How @command{gnatmake} Works
9702
9703 @noindent
9704 Generally @command{gnatmake} automatically performs all necessary
9705 recompilations and you don't need to worry about how it works. However,
9706 it may be useful to have some basic understanding of the @command{gnatmake}
9707 approach and in particular to understand how it uses the results of
9708 previous compilations without incorrectly depending on them.
9709
9710 First a definition: an object file is considered @dfn{up to date} if the
9711 corresponding ALI file exists and if all the source files listed in the
9712 dependency section of this ALI file have time stamps matching those in
9713 the ALI file. This means that neither the source file itself nor any
9714 files that it depends on have been modified, and hence there is no need
9715 to recompile this file.
9716
9717 @command{gnatmake} works by first checking if the specified main unit is up
9718 to date. If so, no compilations are required for the main unit. If not,
9719 @command{gnatmake} compiles the main program to build a new ALI file that
9720 reflects the latest sources. Then the ALI file of the main unit is
9721 examined to find all the source files on which the main program depends,
9722 and @command{gnatmake} recursively applies the above procedure on all these
9723 files.
9724
9725 This process ensures that @command{gnatmake} only trusts the dependencies
9726 in an existing ALI file if they are known to be correct. Otherwise it
9727 always recompiles to determine a new, guaranteed accurate set of
9728 dependencies. As a result the program is compiled ``upside down'' from what may
9729 be more familiar as the required order of compilation in some other Ada
9730 systems. In particular, clients are compiled before the units on which
9731 they depend. The ability of GNAT to compile in any order is critical in
9732 allowing an order of compilation to be chosen that guarantees that
9733 @command{gnatmake} will recompute a correct set of new dependencies if
9734 necessary.
9735
9736 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9737 imported by several of the executables, it will be recompiled at most once.
9738
9739 Note: when using non-standard naming conventions
9740 (@pxref{Using Other File Names}), changing through a configuration pragmas
9741 file the version of a source and invoking @command{gnatmake} to recompile may
9742 have no effect, if the previous version of the source is still accessible
9743 by @command{gnatmake}. It may be necessary to use the switch
9744 ^-f^/FORCE_COMPILE^.
9745
9746 @node Examples of gnatmake Usage
9747 @section Examples of @command{gnatmake} Usage
9748
9749 @table @code
9750 @item gnatmake hello.adb
9751 Compile all files necessary to bind and link the main program
9752 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9753 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9754
9755 @item gnatmake main1 main2 main3
9756 Compile all files necessary to bind and link the main programs
9757 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9758 (containing unit @code{Main2}) and @file{main3.adb}
9759 (containing unit @code{Main3}) and bind and link the resulting object files
9760 to generate three executable files @file{^main1^MAIN1.EXE^},
9761 @file{^main2^MAIN2.EXE^}
9762 and @file{^main3^MAIN3.EXE^}.
9763
9764 @ifclear vms
9765 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9766 @end ifclear
9767
9768 @ifset vms
9769 @item gnatmake Main_Unit /QUIET
9770 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9771 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9772 @end ifset
9773 Compile all files necessary to bind and link the main program unit
9774 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9775 be done with optimization level 2 and the order of elaboration will be
9776 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9777 displaying commands it is executing.
9778 @end table
9779
9780 @c *************************
9781 @node Improving Performance
9782 @chapter Improving Performance
9783 @cindex Improving performance
9784
9785 @noindent
9786 This chapter presents several topics related to program performance.
9787 It first describes some of the tradeoffs that need to be considered
9788 and some of the techniques for making your program run faster.
9789 It then documents the @command{gnatelim} tool and unused subprogram/data
9790 elimination feature, which can reduce the size of program executables.
9791
9792 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9793 driver (see @ref{The GNAT Driver and Project Files}).
9794
9795 @ifnottex
9796 @menu
9797 * Performance Considerations::
9798 * Text_IO Suggestions::
9799 * Reducing Size of Ada Executables with gnatelim::
9800 * Reducing Size of Executables with unused subprogram/data elimination::
9801 @end menu
9802 @end ifnottex
9803
9804 @c *****************************
9805 @node Performance Considerations
9806 @section Performance Considerations
9807
9808 @noindent
9809 The GNAT system provides a number of options that allow a trade-off
9810 between
9811
9812 @itemize @bullet
9813 @item
9814 performance of the generated code
9815
9816 @item
9817 speed of compilation
9818
9819 @item
9820 minimization of dependences and recompilation
9821
9822 @item
9823 the degree of run-time checking.
9824 @end itemize
9825
9826 @noindent
9827 The defaults (if no options are selected) aim at improving the speed
9828 of compilation and minimizing dependences, at the expense of performance
9829 of the generated code:
9830
9831 @itemize @bullet
9832 @item
9833 no optimization
9834
9835 @item
9836 no inlining of subprogram calls
9837
9838 @item
9839 all run-time checks enabled except overflow and elaboration checks
9840 @end itemize
9841
9842 @noindent
9843 These options are suitable for most program development purposes. This
9844 chapter describes how you can modify these choices, and also provides
9845 some guidelines on debugging optimized code.
9846
9847 @menu
9848 * Controlling Run-Time Checks::
9849 * Use of Restrictions::
9850 * Optimization Levels::
9851 * Debugging Optimized Code::
9852 * Inlining of Subprograms::
9853 * Other Optimization Switches::
9854 * Optimization and Strict Aliasing::
9855
9856 @ifset vms
9857 * Coverage Analysis::
9858 @end ifset
9859 @end menu
9860
9861 @node Controlling Run-Time Checks
9862 @subsection Controlling Run-Time Checks
9863
9864 @noindent
9865 By default, GNAT generates all run-time checks, except integer overflow
9866 checks, stack overflow checks, and checks for access before elaboration on
9867 subprogram calls. The latter are not required in default mode, because all
9868 necessary checking is done at compile time.
9869 @cindex @option{-gnatp} (@command{gcc})
9870 @cindex @option{-gnato} (@command{gcc})
9871 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9872 be modified. @xref{Run-Time Checks}.
9873
9874 Our experience is that the default is suitable for most development
9875 purposes.
9876
9877 We treat integer overflow specially because these
9878 are quite expensive and in our experience are not as important as other
9879 run-time checks in the development process. Note that division by zero
9880 is not considered an overflow check, and divide by zero checks are
9881 generated where required by default.
9882
9883 Elaboration checks are off by default, and also not needed by default, since
9884 GNAT uses a static elaboration analysis approach that avoids the need for
9885 run-time checking. This manual contains a full chapter discussing the issue
9886 of elaboration checks, and if the default is not satisfactory for your use,
9887 you should read this chapter.
9888
9889 For validity checks, the minimal checks required by the Ada Reference
9890 Manual (for case statements and assignments to array elements) are on
9891 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9892 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9893 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9894 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9895 are also suppressed entirely if @option{-gnatp} is used.
9896
9897 @cindex Overflow checks
9898 @cindex Checks, overflow
9899 @findex Suppress
9900 @findex Unsuppress
9901 @cindex pragma Suppress
9902 @cindex pragma Unsuppress
9903 Note that the setting of the switches controls the default setting of
9904 the checks. They may be modified using either @code{pragma Suppress} (to
9905 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9906 checks) in the program source.
9907
9908 @node Use of Restrictions
9909 @subsection Use of Restrictions
9910
9911 @noindent
9912 The use of pragma Restrictions allows you to control which features are
9913 permitted in your program. Apart from the obvious point that if you avoid
9914 relatively expensive features like finalization (enforceable by the use
9915 of pragma Restrictions (No_Finalization), the use of this pragma does not
9916 affect the generated code in most cases.
9917
9918 One notable exception to this rule is that the possibility of task abort
9919 results in some distributed overhead, particularly if finalization or
9920 exception handlers are used. The reason is that certain sections of code
9921 have to be marked as non-abortable.
9922
9923 If you use neither the @code{abort} statement, nor asynchronous transfer
9924 of control (@code{select @dots{} then abort}), then this distributed overhead
9925 is removed, which may have a general positive effect in improving
9926 overall performance.  Especially code involving frequent use of tasking
9927 constructs and controlled types will show much improved performance.
9928 The relevant restrictions pragmas are
9929
9930 @smallexample @c ada
9931    pragma Restrictions (No_Abort_Statements);
9932    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9933 @end smallexample
9934
9935 @noindent
9936 It is recommended that these restriction pragmas be used if possible. Note
9937 that this also means that you can write code without worrying about the
9938 possibility of an immediate abort at any point.
9939
9940 @node Optimization Levels
9941 @subsection Optimization Levels
9942 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9943
9944 @noindent
9945 Without any optimization ^option,^qualifier,^
9946 the compiler's goal is to reduce the cost of
9947 compilation and to make debugging produce the expected results.
9948 Statements are independent: if you stop the program with a breakpoint between
9949 statements, you can then assign a new value to any variable or change
9950 the program counter to any other statement in the subprogram and get exactly
9951 the results you would expect from the source code.
9952
9953 Turning on optimization makes the compiler attempt to improve the
9954 performance and/or code size at the expense of compilation time and
9955 possibly the ability to debug the program.
9956
9957 If you use multiple
9958 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
9959 the last such option is the one that is effective.
9960
9961 @noindent
9962 The default is optimization off. This results in the fastest compile
9963 times, but GNAT makes absolutely no attempt to optimize, and the
9964 generated programs are considerably larger and slower than when
9965 optimization is enabled. You can use the
9966 @ifclear vms
9967 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9968 @option{-O2}, @option{-O3}, and @option{-Os})
9969 @end ifclear
9970 @ifset vms
9971 @code{OPTIMIZE} qualifier
9972 @end ifset
9973 to @command{gcc} to control the optimization level:
9974
9975 @table @option
9976 @item ^-O0^/OPTIMIZE=NONE^
9977 No optimization (the default);
9978 generates unoptimized code but has
9979 the fastest compilation time.
9980
9981 Note that many other compilers do fairly extensive optimization
9982 even if ``no optimization'' is specified. With gcc, it is
9983 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9984 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9985 really does mean no optimization at all. This difference between
9986 gcc and other compilers should be kept in mind when doing
9987 performance comparisons.
9988
9989 @item ^-O1^/OPTIMIZE=SOME^
9990 Moderate optimization;
9991 optimizes reasonably well but does not
9992 degrade compilation time significantly.
9993
9994 @item ^-O2^/OPTIMIZE=ALL^
9995 @ifset vms
9996 @itemx /OPTIMIZE=DEVELOPMENT
9997 @end ifset
9998 Full optimization;
9999 generates highly optimized code and has
10000 the slowest compilation time.
10001
10002 @item ^-O3^/OPTIMIZE=INLINING^
10003 Full optimization as in @option{-O2},
10004 and also attempts automatic inlining of small
10005 subprograms within a unit (@pxref{Inlining of Subprograms}).
10006
10007 @item ^-Os^/OPTIMIZE=SPACE^
10008 Optimize space usage of resulting program.
10009 @end table
10010
10011 @noindent
10012 Higher optimization levels perform more global transformations on the
10013 program and apply more expensive analysis algorithms in order to generate
10014 faster and more compact code. The price in compilation time, and the
10015 resulting improvement in execution time,
10016 both depend on the particular application and the hardware environment.
10017 You should experiment to find the best level for your application.
10018
10019 Since the precise set of optimizations done at each level will vary from
10020 release to release (and sometime from target to target), it is best to think
10021 of the optimization settings in general terms.
10022 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10023 the GNU Compiler Collection (GCC)}, for details about
10024 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10025 individually enable or disable specific optimizations.
10026
10027 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10028 been tested extensively at all optimization levels. There are some bugs
10029 which appear only with optimization turned on, but there have also been
10030 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10031 level of optimization does not improve the reliability of the code
10032 generator, which in practice is highly reliable at all optimization
10033 levels.
10034
10035 Note regarding the use of @option{-O3}: The use of this optimization level
10036 is generally discouraged with GNAT, since it often results in larger
10037 executables which run more slowly. See further discussion of this point
10038 in @ref{Inlining of Subprograms}.
10039
10040 @node Debugging Optimized Code
10041 @subsection Debugging Optimized Code
10042 @cindex Debugging optimized code
10043 @cindex Optimization and debugging
10044
10045 @noindent
10046 Although it is possible to do a reasonable amount of debugging at
10047 @ifclear vms
10048 nonzero optimization levels,
10049 the higher the level the more likely that
10050 @end ifclear
10051 @ifset vms
10052 @option{/OPTIMIZE} settings other than @code{NONE},
10053 such settings will make it more likely that
10054 @end ifset
10055 source-level constructs will have been eliminated by optimization.
10056 For example, if a loop is strength-reduced, the loop
10057 control variable may be completely eliminated and thus cannot be
10058 displayed in the debugger.
10059 This can only happen at @option{-O2} or @option{-O3}.
10060 Explicit temporary variables that you code might be eliminated at
10061 ^level^setting^ @option{-O1} or higher.
10062
10063 The use of the @option{^-g^/DEBUG^} switch,
10064 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10065 which is needed for source-level debugging,
10066 affects the size of the program executable on disk,
10067 and indeed the debugging information can be quite large.
10068 However, it has no effect on the generated code (and thus does not
10069 degrade performance)
10070
10071 Since the compiler generates debugging tables for a compilation unit before
10072 it performs optimizations, the optimizing transformations may invalidate some
10073 of the debugging data.  You therefore need to anticipate certain
10074 anomalous situations that may arise while debugging optimized code.
10075 These are the most common cases:
10076
10077 @enumerate
10078 @item
10079 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10080 commands show
10081 the PC bouncing back and forth in the code.  This may result from any of
10082 the following optimizations:
10083
10084 @itemize @bullet
10085 @item
10086 @i{Common subexpression elimination:} using a single instance of code for a
10087 quantity that the source computes several times.  As a result you
10088 may not be able to stop on what looks like a statement.
10089
10090 @item
10091 @i{Invariant code motion:} moving an expression that does not change within a
10092 loop, to the beginning of the loop.
10093
10094 @item
10095 @i{Instruction scheduling:} moving instructions so as to
10096 overlap loads and stores (typically) with other code, or in
10097 general to move computations of values closer to their uses. Often
10098 this causes you to pass an assignment statement without the assignment
10099 happening and then later bounce back to the statement when the
10100 value is actually needed.  Placing a breakpoint on a line of code
10101 and then stepping over it may, therefore, not always cause all the
10102 expected side-effects.
10103 @end itemize
10104
10105 @item
10106 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10107 two identical pieces of code are merged and the program counter suddenly
10108 jumps to a statement that is not supposed to be executed, simply because
10109 it (and the code following) translates to the same thing as the code
10110 that @emph{was} supposed to be executed.  This effect is typically seen in
10111 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10112 a @code{break} in a C @code{^switch^switch^} statement.
10113
10114 @item
10115 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10116 There are various reasons for this effect:
10117
10118 @itemize @bullet
10119 @item
10120 In a subprogram prologue, a parameter may not yet have been moved to its
10121 ``home''.
10122
10123 @item
10124 A variable may be dead, and its register re-used.  This is
10125 probably the most common cause.
10126
10127 @item
10128 As mentioned above, the assignment of a value to a variable may
10129 have been moved.
10130
10131 @item
10132 A variable may be eliminated entirely by value propagation or
10133 other means.  In this case, GCC may incorrectly generate debugging
10134 information for the variable
10135 @end itemize
10136
10137 @noindent
10138 In general, when an unexpected value appears for a local variable or parameter
10139 you should first ascertain if that value was actually computed by
10140 your program, as opposed to being incorrectly reported by the debugger.
10141 Record fields or
10142 array elements in an object designated by an access value
10143 are generally less of a problem, once you have ascertained that the access
10144 value is sensible.
10145 Typically, this means checking variables in the preceding code and in the
10146 calling subprogram to verify that the value observed is explainable from other
10147 values (one must apply the procedure recursively to those
10148 other values); or re-running the code and stopping a little earlier
10149 (perhaps before the call) and stepping to better see how the variable obtained
10150 the value in question; or continuing to step @emph{from} the point of the
10151 strange value to see if code motion had simply moved the variable's
10152 assignments later.
10153 @end enumerate
10154
10155 @noindent
10156 In light of such anomalies, a recommended technique is to use @option{-O0}
10157 early in the software development cycle, when extensive debugging capabilities
10158 are most needed, and then move to @option{-O1} and later @option{-O2} as
10159 the debugger becomes less critical.
10160 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10161 a release management issue.
10162 @ifclear vms
10163 Note that if you use @option{-g} you can then use the @command{strip} program
10164 on the resulting executable,
10165 which removes both debugging information and global symbols.
10166 @end ifclear
10167
10168 @node Inlining of Subprograms
10169 @subsection Inlining of Subprograms
10170
10171 @noindent
10172 A call to a subprogram in the current unit is inlined if all the
10173 following conditions are met:
10174
10175 @itemize @bullet
10176 @item
10177 The optimization level is at least @option{-O1}.
10178
10179 @item
10180 The called subprogram is suitable for inlining: It must be small enough
10181 and not contain something that @command{gcc} cannot support in inlined
10182 subprograms.
10183
10184 @item
10185 @cindex pragma Inline
10186 @findex Inline
10187 Either @code{pragma Inline} applies to the subprogram, or it is local
10188 to the unit and called once from within it, or it is small and automatic
10189 inlining (optimization level @option{-O3}) is specified.
10190 @end itemize
10191
10192 @noindent
10193 Calls to subprograms in @code{with}'ed units are normally not inlined.
10194 To achieve actual inlining (that is, replacement of the call by the code
10195 in the body of the subprogram), the following conditions must all be true.
10196
10197 @itemize @bullet
10198 @item
10199 The optimization level is at least @option{-O1}.
10200
10201 @item
10202 The called subprogram is suitable for inlining: It must be small enough
10203 and not contain something that @command{gcc} cannot support in inlined
10204 subprograms.
10205
10206 @item
10207 The call appears in a body (not in a package spec).
10208
10209 @item
10210 There is a @code{pragma Inline} for the subprogram.
10211
10212 @item
10213 @cindex @option{-gnatn} (@command{gcc})
10214 The @option{^-gnatn^/INLINE^} switch
10215 is used in the @command{gcc} command line
10216 @end itemize
10217
10218 Even if all these conditions are met, it may not be possible for
10219 the compiler to inline the call, due to the length of the body,
10220 or features in the body that make it impossible for the compiler
10221 to do the inlining.
10222
10223 Note that specifying the @option{-gnatn} switch causes additional
10224 compilation dependencies. Consider the following:
10225
10226 @smallexample @c ada
10227 @cartouche
10228 package R is
10229    procedure Q;
10230    pragma Inline (Q);
10231 end R;
10232 package body R is
10233    @dots{}
10234 end R;
10235
10236 with R;
10237 procedure Main is
10238 begin
10239    @dots{}
10240    R.Q;
10241 end Main;
10242 @end cartouche
10243 @end smallexample
10244
10245 @noindent
10246 With the default behavior (no @option{-gnatn} switch specified), the
10247 compilation of the @code{Main} procedure depends only on its own source,
10248 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10249 means that editing the body of @code{R} does not require recompiling
10250 @code{Main}.
10251
10252 On the other hand, the call @code{R.Q} is not inlined under these
10253 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10254 is compiled, the call will be inlined if the body of @code{Q} is small
10255 enough, but now @code{Main} depends on the body of @code{R} in
10256 @file{r.adb} as well as on the spec. This means that if this body is edited,
10257 the main program must be recompiled. Note that this extra dependency
10258 occurs whether or not the call is in fact inlined by @command{gcc}.
10259
10260 The use of front end inlining with @option{-gnatN} generates similar
10261 additional dependencies.
10262
10263 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10264 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10265 can be used to prevent
10266 all inlining. This switch overrides all other conditions and ensures
10267 that no inlining occurs. The extra dependences resulting from
10268 @option{-gnatn} will still be active, even if
10269 this switch is used to suppress the resulting inlining actions.
10270
10271 @cindex @option{-fno-inline-functions} (@command{gcc})
10272 Note: The @option{-fno-inline-functions} switch can be used to prevent
10273 automatic inlining of small subprograms if @option{-O3} is used.
10274
10275 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10276 Note: The @option{-fno-inline-functions-called-once} switch
10277 can be used to prevent inlining of subprograms local to the unit
10278 and called once from within it if @option{-O1} is used.
10279
10280 Note regarding the use of @option{-O3}: There is no difference in inlining
10281 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10282 pragma @code{Inline} assuming the use of @option{-gnatn}
10283 or @option{-gnatN} (the switches that activate inlining). If you have used
10284 pragma @code{Inline} in appropriate cases, then it is usually much better
10285 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10286 in this case only has the effect of inlining subprograms you did not
10287 think should be inlined. We often find that the use of @option{-O3} slows
10288 down code by performing excessive inlining, leading to increased instruction
10289 cache pressure from the increased code size. So the bottom line here is
10290 that you should not automatically assume that @option{-O3} is better than
10291 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10292 it actually improves performance.
10293
10294 @node Other Optimization Switches
10295 @subsection Other Optimization Switches
10296 @cindex Optimization Switches
10297
10298 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10299 @command{gcc} optimization switches are potentially usable. These switches
10300 have not been extensively tested with GNAT but can generally be expected
10301 to work. Examples of switches in this category are
10302 @option{-funroll-loops} and
10303 the various target-specific @option{-m} options (in particular, it has been
10304 observed that @option{-march=pentium4} can significantly improve performance
10305 on appropriate machines). For full details of these switches, see
10306 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10307 the GNU Compiler Collection (GCC)}.
10308
10309 @node Optimization and Strict Aliasing
10310 @subsection Optimization and Strict Aliasing
10311 @cindex Aliasing
10312 @cindex Strict Aliasing
10313 @cindex No_Strict_Aliasing
10314
10315 @noindent
10316 The strong typing capabilities of Ada allow an optimizer to generate
10317 efficient code in situations where other languages would be forced to
10318 make worst case assumptions preventing such optimizations. Consider
10319 the following example:
10320
10321 @smallexample @c ada
10322 @cartouche
10323 procedure R is
10324    type Int1 is new Integer;
10325    type Int2 is new Integer;
10326    type Int1A is access Int1;
10327    type Int2A is access Int2;
10328    Int1V : Int1A;
10329    Int2V : Int2A;
10330    @dots{}
10331
10332 begin
10333    @dots{}
10334    for J in Data'Range loop
10335       if Data (J) = Int1V.all then
10336          Int2V.all := Int2V.all + 1;
10337       end if;
10338    end loop;
10339    @dots{}
10340 end R;
10341 @end cartouche
10342 @end smallexample
10343
10344 @noindent
10345 In this example, since the variable @code{Int1V} can only access objects
10346 of type @code{Int1}, and @code{Int2V} can only access objects of type
10347 @code{Int2}, there is no possibility that the assignment to
10348 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10349 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10350 for all iterations of the loop and avoid the extra memory reference
10351 required to dereference it each time through the loop.
10352
10353 This kind of optimization, called strict aliasing analysis, is
10354 triggered by specifying an optimization level of @option{-O2} or
10355 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10356 when access values are involved.
10357
10358 However, although this optimization is always correct in terms of
10359 the formal semantics of the Ada Reference Manual, difficulties can
10360 arise if features like @code{Unchecked_Conversion} are used to break
10361 the typing system. Consider the following complete program example:
10362
10363 @smallexample @c ada
10364 @cartouche
10365 package p1 is
10366    type int1 is new integer;
10367    type int2 is new integer;
10368    type a1 is access int1;
10369    type a2 is access int2;
10370 end p1;
10371
10372 with p1; use p1;
10373 package p2 is
10374    function to_a2 (Input : a1) return a2;
10375 end p2;
10376
10377 with Unchecked_Conversion;
10378 package body p2 is
10379    function to_a2 (Input : a1) return a2 is
10380       function to_a2u is
10381         new Unchecked_Conversion (a1, a2);
10382    begin
10383       return to_a2u (Input);
10384    end to_a2;
10385 end p2;
10386
10387 with p2; use p2;
10388 with p1; use p1;
10389 with Text_IO; use Text_IO;
10390 procedure m is
10391    v1 : a1 := new int1;
10392    v2 : a2 := to_a2 (v1);
10393 begin
10394    v1.all := 1;
10395    v2.all := 0;
10396    put_line (int1'image (v1.all));
10397 end;
10398 @end cartouche
10399 @end smallexample
10400
10401 @noindent
10402 This program prints out 0 in @option{-O0} or @option{-O1}
10403 mode, but it prints out 1 in @option{-O2} mode. That's
10404 because in strict aliasing mode, the compiler can and
10405 does assume that the assignment to @code{v2.all} could not
10406 affect the value of @code{v1.all}, since different types
10407 are involved.
10408
10409 This behavior is not a case of non-conformance with the standard, since
10410 the Ada RM specifies that an unchecked conversion where the resulting
10411 bit pattern is not a correct value of the target type can result in an
10412 abnormal value and attempting to reference an abnormal value makes the
10413 execution of a program erroneous.  That's the case here since the result
10414 does not point to an object of type @code{int2}.  This means that the
10415 effect is entirely unpredictable.
10416
10417 However, although that explanation may satisfy a language
10418 lawyer, in practice an applications programmer expects an
10419 unchecked conversion involving pointers to create true
10420 aliases and the behavior of printing 1 seems plain wrong.
10421 In this case, the strict aliasing optimization is unwelcome.
10422
10423 Indeed the compiler recognizes this possibility, and the
10424 unchecked conversion generates a warning:
10425
10426 @smallexample
10427 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10428 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10429 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10430 @end smallexample
10431
10432 @noindent
10433 Unfortunately the problem is recognized when compiling the body of
10434 package @code{p2}, but the actual "bad" code is generated while
10435 compiling the body of @code{m} and this latter compilation does not see
10436 the suspicious @code{Unchecked_Conversion}.
10437
10438 As implied by the warning message, there are approaches you can use to
10439 avoid the unwanted strict aliasing optimization in a case like this.
10440
10441 One possibility is to simply avoid the use of @option{-O2}, but
10442 that is a bit drastic, since it throws away a number of useful
10443 optimizations that do not involve strict aliasing assumptions.
10444
10445 A less drastic approach is to compile the program using the
10446 option @option{-fno-strict-aliasing}. Actually it is only the
10447 unit containing the dereferencing of the suspicious pointer
10448 that needs to be compiled. So in this case, if we compile
10449 unit @code{m} with this switch, then we get the expected
10450 value of zero printed. Analyzing which units might need
10451 the switch can be painful, so a more reasonable approach
10452 is to compile the entire program with options @option{-O2}
10453 and @option{-fno-strict-aliasing}. If the performance is
10454 satisfactory with this combination of options, then the
10455 advantage is that the entire issue of possible "wrong"
10456 optimization due to strict aliasing is avoided.
10457
10458 To avoid the use of compiler switches, the configuration
10459 pragma @code{No_Strict_Aliasing} with no parameters may be
10460 used to specify that for all access types, the strict
10461 aliasing optimization should be suppressed.
10462
10463 However, these approaches are still overkill, in that they causes
10464 all manipulations of all access values to be deoptimized. A more
10465 refined approach is to concentrate attention on the specific
10466 access type identified as problematic.
10467
10468 First, if a careful analysis of uses of the pointer shows
10469 that there are no possible problematic references, then
10470 the warning can be suppressed by bracketing the
10471 instantiation of @code{Unchecked_Conversion} to turn
10472 the warning off:
10473
10474 @smallexample @c ada
10475    pragma Warnings (Off);
10476    function to_a2u is
10477      new Unchecked_Conversion (a1, a2);
10478    pragma Warnings (On);
10479 @end smallexample
10480
10481 @noindent
10482 Of course that approach is not appropriate for this particular
10483 example, since indeed there is a problematic reference. In this
10484 case we can take one of two other approaches.
10485
10486 The first possibility is to move the instantiation of unchecked
10487 conversion to the unit in which the type is declared. In
10488 this example, we would move the instantiation of
10489 @code{Unchecked_Conversion} from the body of package
10490 @code{p2} to the spec of package @code{p1}. Now the
10491 warning disappears. That's because any use of the
10492 access type knows there is a suspicious unchecked
10493 conversion, and the strict aliasing optimization
10494 is automatically suppressed for the type.
10495
10496 If it is not practical to move the unchecked conversion to the same unit
10497 in which the destination access type is declared (perhaps because the
10498 source type is not visible in that unit), you may use pragma
10499 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10500 same declarative sequence as the declaration of the access type:
10501
10502 @smallexample @c ada
10503    type a2 is access int2;
10504    pragma No_Strict_Aliasing (a2);
10505 @end smallexample
10506
10507 @noindent
10508 Here again, the compiler now knows that the strict aliasing optimization
10509 should be suppressed for any reference to type @code{a2} and the
10510 expected behavior is obtained.
10511
10512 Finally, note that although the compiler can generate warnings for
10513 simple cases of unchecked conversions, there are tricker and more
10514 indirect ways of creating type incorrect aliases which the compiler
10515 cannot detect. Examples are the use of address overlays and unchecked
10516 conversions involving composite types containing access types as
10517 components. In such cases, no warnings are generated, but there can
10518 still be aliasing problems. One safe coding practice is to forbid the
10519 use of address clauses for type overlaying, and to allow unchecked
10520 conversion only for primitive types. This is not really a significant
10521 restriction since any possible desired effect can be achieved by
10522 unchecked conversion of access values.
10523
10524 The aliasing analysis done in strict aliasing mode can certainly
10525 have significant benefits. We have seen cases of large scale
10526 application code where the time is increased by up to 5% by turning
10527 this optimization off. If you have code that includes significant
10528 usage of unchecked conversion, you might want to just stick with
10529 @option{-O1} and avoid the entire issue. If you get adequate
10530 performance at this level of optimization level, that's probably
10531 the safest approach. If tests show that you really need higher
10532 levels of optimization, then you can experiment with @option{-O2}
10533 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10534 has on size and speed of the code. If you really need to use
10535 @option{-O2} with strict aliasing in effect, then you should
10536 review any uses of unchecked conversion of access types,
10537 particularly if you are getting the warnings described above.
10538
10539 @ifset vms
10540 @node Coverage Analysis
10541 @subsection Coverage Analysis
10542
10543 @noindent
10544 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10545 the user to determine the distribution of execution time across a program,
10546 @pxref{Profiling} for details of usage.
10547 @end ifset
10548
10549
10550 @node Text_IO Suggestions
10551 @section @code{Text_IO} Suggestions
10552 @cindex @code{Text_IO} and performance
10553
10554 @noindent
10555 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10556 the requirement of maintaining page and line counts. If performance
10557 is critical, a recommendation is to use @code{Stream_IO} instead of
10558 @code{Text_IO} for volume output, since this package has less overhead.
10559
10560 If @code{Text_IO} must be used, note that by default output to the standard
10561 output and standard error files is unbuffered (this provides better
10562 behavior when output statements are used for debugging, or if the
10563 progress of a program is observed by tracking the output, e.g. by
10564 using the Unix @command{tail -f} command to watch redirected output.
10565
10566 If you are generating large volumes of output with @code{Text_IO} and
10567 performance is an important factor, use a designated file instead
10568 of the standard output file, or change the standard output file to
10569 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10570
10571
10572
10573 @node Reducing Size of Ada Executables with gnatelim
10574 @section Reducing Size of Ada Executables with @code{gnatelim}
10575 @findex gnatelim
10576
10577 @noindent
10578 This section describes @command{gnatelim}, a tool which detects unused
10579 subprograms and helps the compiler to create a smaller executable for your
10580 program.
10581
10582 @menu
10583 * About gnatelim::
10584 * Running gnatelim::
10585 * Correcting the List of Eliminate Pragmas::
10586 * Making Your Executables Smaller::
10587 * Summary of the gnatelim Usage Cycle::
10588 @end menu
10589
10590 @node About gnatelim
10591 @subsection About @code{gnatelim}
10592
10593 @noindent
10594 When a program shares a set of Ada
10595 packages with other programs, it may happen that this program uses
10596 only a fraction of the subprograms defined in these packages. The code
10597 created for these unused subprograms increases the size of the executable.
10598
10599 @code{gnatelim} tracks unused subprograms in an Ada program and
10600 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10601 subprograms that are declared but never called. By placing the list of
10602 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10603 recompiling your program, you may decrease the size of its executable,
10604 because the compiler will not generate the code for 'eliminated' subprograms.
10605 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10606 information about this pragma.
10607
10608 @code{gnatelim} needs as its input data the name of the main subprogram
10609 and a bind file for a main subprogram.
10610
10611 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10612 the main subprogram. @code{gnatelim} can work with both Ada and C
10613 bind files; when both are present, it uses the Ada bind file.
10614 The following commands will build the program and create the bind file:
10615
10616 @smallexample
10617 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10618 $ gnatbind main_prog
10619 @end smallexample
10620
10621 Note that @code{gnatelim} needs neither object nor ALI files.
10622
10623 @node Running gnatelim
10624 @subsection Running @code{gnatelim}
10625
10626 @noindent
10627 @code{gnatelim} has the following command-line interface:
10628
10629 @smallexample
10630 $ gnatelim @ovar{options} name
10631 @end smallexample
10632
10633 @noindent
10634 @code{name} should be a name of a source file that contains the main subprogram
10635 of a program (partition).
10636
10637 @code{gnatelim} has the following switches:
10638
10639 @table @option
10640 @c !sort!
10641 @item ^-q^/QUIET^
10642 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10643 Quiet mode: by default @code{gnatelim} outputs to the standard error
10644 stream the number of program units left to be processed. This option turns
10645 this trace off.
10646
10647 @item ^-v^/VERBOSE^
10648 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10649 Verbose mode: @code{gnatelim} version information is printed as Ada
10650 comments to the standard output stream. Also, in addition to the number of
10651 program units left @code{gnatelim} will output the name of the current unit
10652 being processed.
10653
10654 @item ^-a^/ALL^
10655 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10656 Also look for subprograms from the GNAT run time that can be eliminated. Note
10657 that when @file{gnat.adc} is produced using this switch, the entire program
10658 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10659
10660 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10661 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10662 When looking for source files also look in directory @var{dir}. Specifying
10663 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10664 sources in the current directory.
10665
10666 @item ^-b^/BIND_FILE=^@var{bind_file}
10667 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10668 Specifies @var{bind_file} as the bind file to process. If not set, the name
10669 of the bind file is computed from the full expanded Ada name
10670 of a main subprogram.
10671
10672 @item ^-C^/CONFIG_FILE=^@var{config_file}
10673 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10674 Specifies a file @var{config_file} that contains configuration pragmas. The
10675 file must be specified with full path.
10676
10677 @item ^--GCC^/COMPILER^=@var{compiler_name}
10678 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10679 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10680 available on the path.
10681
10682 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10683 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10684 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10685 available on the path.
10686 @end table
10687
10688 @noindent
10689 @code{gnatelim} sends its output to the standard output stream, and all the
10690 tracing and debug information is sent to the standard error stream.
10691 In order to produce a proper GNAT configuration file
10692 @file{gnat.adc}, redirection must be used:
10693
10694 @smallexample
10695 @ifset vms
10696 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10697 @end ifset
10698 @ifclear vms
10699 $ gnatelim main_prog.adb > gnat.adc
10700 @end ifclear
10701 @end smallexample
10702
10703 @ifclear vms
10704 @noindent
10705 or
10706
10707 @smallexample
10708 $ gnatelim main_prog.adb >> gnat.adc
10709 @end smallexample
10710
10711 @noindent
10712 in order to append the @code{gnatelim} output to the existing contents of
10713 @file{gnat.adc}.
10714 @end ifclear
10715
10716 @node Correcting the List of Eliminate Pragmas
10717 @subsection Correcting the List of Eliminate Pragmas
10718
10719 @noindent
10720 In some rare cases @code{gnatelim} may try to eliminate
10721 subprograms that are actually called in the program. In this case, the
10722 compiler will generate an error message of the form:
10723
10724 @smallexample
10725 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10726 @end smallexample
10727
10728 @noindent
10729 You will need to manually remove the wrong @code{Eliminate} pragmas from
10730 the @file{gnat.adc} file. You should recompile your program
10731 from scratch after that, because you need a consistent @file{gnat.adc} file
10732 during the entire compilation.
10733
10734 @node Making Your Executables Smaller
10735 @subsection Making Your Executables Smaller
10736
10737 @noindent
10738 In order to get a smaller executable for your program you now have to
10739 recompile the program completely with the new @file{gnat.adc} file
10740 created by @code{gnatelim} in your current directory:
10741
10742 @smallexample
10743 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10744 @end smallexample
10745
10746 @noindent
10747 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10748 recompile everything
10749 with the set of pragmas @code{Eliminate} that you have obtained with
10750 @command{gnatelim}).
10751
10752 Be aware that the set of @code{Eliminate} pragmas is specific to each
10753 program. It is not recommended to merge sets of @code{Eliminate}
10754 pragmas created for different programs in one @file{gnat.adc} file.
10755
10756 @node Summary of the gnatelim Usage Cycle
10757 @subsection Summary of the gnatelim Usage Cycle
10758
10759 @noindent
10760 Here is a quick summary of the steps to be taken in order to reduce
10761 the size of your executables with @code{gnatelim}. You may use
10762 other GNAT options to control the optimization level,
10763 to produce the debugging information, to set search path, etc.
10764
10765 @enumerate
10766 @item
10767 Produce a bind file
10768
10769 @smallexample
10770 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10771 $ gnatbind main_prog
10772 @end smallexample
10773
10774 @item
10775 Generate a list of @code{Eliminate} pragmas
10776 @smallexample
10777 @ifset vms
10778 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10779 @end ifset
10780 @ifclear vms
10781 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10782 @end ifclear
10783 @end smallexample
10784
10785 @item
10786 Recompile the application
10787
10788 @smallexample
10789 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10790 @end smallexample
10791
10792 @end enumerate
10793
10794 @node Reducing Size of Executables with unused subprogram/data elimination
10795 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10796 @findex unused subprogram/data elimination
10797
10798 @noindent
10799 This section describes how you can eliminate unused subprograms and data from
10800 your executable just by setting options at compilation time.
10801
10802 @menu
10803 * About unused subprogram/data elimination::
10804 * Compilation options::
10805 * Example of unused subprogram/data elimination::
10806 @end menu
10807
10808 @node About unused subprogram/data elimination
10809 @subsection About unused subprogram/data elimination
10810
10811 @noindent
10812 By default, an executable contains all code and data of its composing objects
10813 (directly linked or coming from statically linked libraries), even data or code
10814 never used by this executable.
10815
10816 This feature will allow you to eliminate such unused code from your
10817 executable, making it smaller (in disk and in memory).
10818
10819 This functionality is available on all Linux platforms except for the IA-64
10820 architecture and on all cross platforms using the ELF binary file format.
10821 In both cases GNU binutils version 2.16 or later are required to enable it.
10822
10823 @node Compilation options
10824 @subsection Compilation options
10825
10826 @noindent
10827 The operation of eliminating the unused code and data from the final executable
10828 is directly performed by the linker.
10829
10830 In order to do this, it has to work with objects compiled with the
10831 following options:
10832 @option{-ffunction-sections} @option{-fdata-sections}.
10833 @cindex @option{-ffunction-sections} (@command{gcc})
10834 @cindex @option{-fdata-sections} (@command{gcc})
10835 These options are usable with C and Ada files.
10836 They will place respectively each
10837 function or data in a separate section in the resulting object file.
10838
10839 Once the objects and static libraries are created with these options, the
10840 linker can perform the dead code elimination. You can do this by setting
10841 the @option{-Wl,--gc-sections} option to gcc command or in the
10842 @option{-largs} section of @command{gnatmake}. This will perform a
10843 garbage collection of code and data never referenced.
10844
10845 If the linker performs a partial link (@option{-r} ld linker option), then you
10846 will need to provide one or several entry point using the
10847 @option{-e} / @option{--entry} ld option.
10848
10849 Note that objects compiled without the @option{-ffunction-sections} and
10850 @option{-fdata-sections} options can still be linked with the executable.
10851 However, no dead code elimination will be performed on those objects (they will
10852 be linked as is).
10853
10854 The GNAT static library is now compiled with -ffunction-sections and
10855 -fdata-sections on some platforms. This allows you to eliminate the unused code
10856 and data of the GNAT library from your executable.
10857
10858 @node Example of unused subprogram/data elimination
10859 @subsection Example of unused subprogram/data elimination
10860
10861 @noindent
10862 Here is a simple example:
10863
10864 @smallexample @c ada
10865 with Aux;
10866
10867 procedure Test is
10868 begin
10869    Aux.Used (10);
10870 end Test;
10871
10872 package Aux is
10873    Used_Data   : Integer;
10874    Unused_Data : Integer;
10875
10876    procedure Used   (Data : Integer);
10877    procedure Unused (Data : Integer);
10878 end Aux;
10879
10880 package body Aux is
10881    procedure Used (Data : Integer) is
10882    begin
10883       Used_Data := Data;
10884    end Used;
10885
10886    procedure Unused (Data : Integer) is
10887    begin
10888       Unused_Data := Data;
10889    end Unused;
10890 end Aux;
10891 @end smallexample
10892
10893 @noindent
10894 @code{Unused} and @code{Unused_Data} are never referenced in this code
10895 excerpt, and hence they may be safely removed from the final executable.
10896
10897 @smallexample
10898 $ gnatmake test
10899
10900 $ nm test | grep used
10901 020015f0 T aux__unused
10902 02005d88 B aux__unused_data
10903 020015cc T aux__used
10904 02005d84 B aux__used_data
10905
10906 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10907      -largs -Wl,--gc-sections
10908
10909 $ nm test | grep used
10910 02005350 T aux__used
10911 0201ffe0 B aux__used_data
10912 @end smallexample
10913
10914 @noindent
10915 It can be observed that the procedure @code{Unused} and the object
10916 @code{Unused_Data} are removed by the linker when using the
10917 appropriate options.
10918
10919 @c ********************************
10920 @node Renaming Files Using gnatchop
10921 @chapter Renaming Files Using @code{gnatchop}
10922 @findex gnatchop
10923
10924 @noindent
10925 This chapter discusses how to handle files with multiple units by using
10926 the @code{gnatchop} utility. This utility is also useful in renaming
10927 files to meet the standard GNAT default file naming conventions.
10928
10929 @menu
10930 * Handling Files with Multiple Units::
10931 * Operating gnatchop in Compilation Mode::
10932 * Command Line for gnatchop::
10933 * Switches for gnatchop::
10934 * Examples of gnatchop Usage::
10935 @end menu
10936
10937 @node Handling Files with Multiple Units
10938 @section Handling Files with Multiple Units
10939
10940 @noindent
10941 The basic compilation model of GNAT requires that a file submitted to the
10942 compiler have only one unit and there be a strict correspondence
10943 between the file name and the unit name.
10944
10945 The @code{gnatchop} utility allows both of these rules to be relaxed,
10946 allowing GNAT to process files which contain multiple compilation units
10947 and files with arbitrary file names. @code{gnatchop}
10948 reads the specified file and generates one or more output files,
10949 containing one unit per file. The unit and the file name correspond,
10950 as required by GNAT.
10951
10952 If you want to permanently restructure a set of ``foreign'' files so that
10953 they match the GNAT rules, and do the remaining development using the
10954 GNAT structure, you can simply use @command{gnatchop} once, generate the
10955 new set of files and work with them from that point on.
10956
10957 Alternatively, if you want to keep your files in the ``foreign'' format,
10958 perhaps to maintain compatibility with some other Ada compilation
10959 system, you can set up a procedure where you use @command{gnatchop} each
10960 time you compile, regarding the source files that it writes as temporary
10961 files that you throw away.
10962
10963 Note that if your file containing multiple units starts with a byte order
10964 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
10965 will each start with a copy of this BOM, meaning that they can be compiled
10966 automatically in UTF-8 mode without needing to specify an explicit encoding.
10967
10968 @node Operating gnatchop in Compilation Mode
10969 @section Operating gnatchop in Compilation Mode
10970
10971 @noindent
10972 The basic function of @code{gnatchop} is to take a file with multiple units
10973 and split it into separate files. The boundary between files is reasonably
10974 clear, except for the issue of comments and pragmas. In default mode, the
10975 rule is that any pragmas between units belong to the previous unit, except
10976 that configuration pragmas always belong to the following unit. Any comments
10977 belong to the following unit. These rules
10978 almost always result in the right choice of
10979 the split point without needing to mark it explicitly and most users will
10980 find this default to be what they want. In this default mode it is incorrect to
10981 submit a file containing only configuration pragmas, or one that ends in
10982 configuration pragmas, to @code{gnatchop}.
10983
10984 However, using a special option to activate ``compilation mode'',
10985 @code{gnatchop}
10986 can perform another function, which is to provide exactly the semantics
10987 required by the RM for handling of configuration pragmas in a compilation.
10988 In the absence of configuration pragmas (at the main file level), this
10989 option has no effect, but it causes such configuration pragmas to be handled
10990 in a quite different manner.
10991
10992 First, in compilation mode, if @code{gnatchop} is given a file that consists of
10993 only configuration pragmas, then this file is appended to the
10994 @file{gnat.adc} file in the current directory. This behavior provides
10995 the required behavior described in the RM for the actions to be taken
10996 on submitting such a file to the compiler, namely that these pragmas
10997 should apply to all subsequent compilations in the same compilation
10998 environment. Using GNAT, the current directory, possibly containing a
10999 @file{gnat.adc} file is the representation
11000 of a compilation environment. For more information on the
11001 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11002
11003 Second, in compilation mode, if @code{gnatchop}
11004 is given a file that starts with
11005 configuration pragmas, and contains one or more units, then these
11006 configuration pragmas are prepended to each of the chopped files. This
11007 behavior provides the required behavior described in the RM for the
11008 actions to be taken on compiling such a file, namely that the pragmas
11009 apply to all units in the compilation, but not to subsequently compiled
11010 units.
11011
11012 Finally, if configuration pragmas appear between units, they are appended
11013 to the previous unit. This results in the previous unit being illegal,
11014 since the compiler does not accept configuration pragmas that follow
11015 a unit. This provides the required RM behavior that forbids configuration
11016 pragmas other than those preceding the first compilation unit of a
11017 compilation.
11018
11019 For most purposes, @code{gnatchop} will be used in default mode. The
11020 compilation mode described above is used only if you need exactly
11021 accurate behavior with respect to compilations, and you have files
11022 that contain multiple units and configuration pragmas. In this
11023 circumstance the use of @code{gnatchop} with the compilation mode
11024 switch provides the required behavior, and is for example the mode
11025 in which GNAT processes the ACVC tests.
11026
11027 @node Command Line for gnatchop
11028 @section Command Line for @code{gnatchop}
11029
11030 @noindent
11031 The @code{gnatchop} command has the form:
11032
11033 @smallexample
11034 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11035       @ovar{directory}
11036 @end smallexample
11037
11038 @noindent
11039 The only required argument is the file name of the file to be chopped.
11040 There are no restrictions on the form of this file name. The file itself
11041 contains one or more Ada units, in normal GNAT format, concatenated
11042 together. As shown, more than one file may be presented to be chopped.
11043
11044 When run in default mode, @code{gnatchop} generates one output file in
11045 the current directory for each unit in each of the files.
11046
11047 @var{directory}, if specified, gives the name of the directory to which
11048 the output files will be written. If it is not specified, all files are
11049 written to the current directory.
11050
11051 For example, given a
11052 file called @file{hellofiles} containing
11053
11054 @smallexample @c ada
11055 @group
11056 @cartouche
11057 procedure hello;
11058
11059 with Text_IO; use Text_IO;
11060 procedure hello is
11061 begin
11062    Put_Line ("Hello");
11063 end hello;
11064 @end cartouche
11065 @end group
11066 @end smallexample
11067
11068 @noindent
11069 the command
11070
11071 @smallexample
11072 $ gnatchop ^hellofiles^HELLOFILES.^
11073 @end smallexample
11074
11075 @noindent
11076 generates two files in the current directory, one called
11077 @file{hello.ads} containing the single line that is the procedure spec,
11078 and the other called @file{hello.adb} containing the remaining text. The
11079 original file is not affected. The generated files can be compiled in
11080 the normal manner.
11081
11082 @noindent
11083 When gnatchop is invoked on a file that is empty or that contains only empty
11084 lines and/or comments, gnatchop will not fail, but will not produce any
11085 new sources.
11086
11087 For example, given a
11088 file called @file{toto.txt} containing
11089
11090 @smallexample @c ada
11091 @group
11092 @cartouche
11093 --  Just a comment
11094 @end cartouche
11095 @end group
11096 @end smallexample
11097
11098 @noindent
11099 the command
11100
11101 @smallexample
11102 $ gnatchop ^toto.txt^TOT.TXT^
11103 @end smallexample
11104
11105 @noindent
11106 will not produce any new file and will result in the following warnings:
11107
11108 @smallexample
11109 toto.txt:1:01: warning: empty file, contains no compilation units
11110 no compilation units found
11111 no source files written
11112 @end smallexample
11113
11114 @node Switches for gnatchop
11115 @section Switches for @code{gnatchop}
11116
11117 @noindent
11118 @command{gnatchop} recognizes the following switches:
11119
11120 @table @option
11121 @c !sort!
11122
11123 @item --version
11124 @cindex @option{--version} @command{gnatchop}
11125 Display Copyright and version, then exit disregarding all other options.
11126
11127 @item --help
11128 @cindex @option{--help} @command{gnatchop}
11129 If @option{--version} was not used, display usage, then exit disregarding
11130 all other options.
11131
11132 @item ^-c^/COMPILATION^
11133 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11134 Causes @code{gnatchop} to operate in compilation mode, in which
11135 configuration pragmas are handled according to strict RM rules. See
11136 previous section for a full description of this mode.
11137
11138 @ifclear vms
11139 @item -gnat@var{xxx}
11140 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11141 used to parse the given file. Not all @var{xxx} options make sense,
11142 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11143 process a source file that uses Latin-2 coding for identifiers.
11144 @end ifclear
11145
11146 @item ^-h^/HELP^
11147 Causes @code{gnatchop} to generate a brief help summary to the standard
11148 output file showing usage information.
11149
11150 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11151 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11152 Limit generated file names to the specified number @code{mm}
11153 of characters.
11154 This is useful if the
11155 resulting set of files is required to be interoperable with systems
11156 which limit the length of file names.
11157 @ifset vms
11158 If no value is given, or
11159 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11160 a default of 39, suitable for OpenVMS Alpha
11161 Systems, is assumed
11162 @end ifset
11163 @ifclear vms
11164 No space is allowed between the @option{-k} and the numeric value. The numeric
11165 value may be omitted in which case a default of @option{-k8},
11166 suitable for use
11167 with DOS-like file systems, is used. If no @option{-k} switch
11168 is present then
11169 there is no limit on the length of file names.
11170 @end ifclear
11171
11172 @item ^-p^/PRESERVE^
11173 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11174 Causes the file ^modification^creation^ time stamp of the input file to be
11175 preserved and used for the time stamp of the output file(s). This may be
11176 useful for preserving coherency of time stamps in an environment where
11177 @code{gnatchop} is used as part of a standard build process.
11178
11179 @item ^-q^/QUIET^
11180 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11181 Causes output of informational messages indicating the set of generated
11182 files to be suppressed. Warnings and error messages are unaffected.
11183
11184 @item ^-r^/REFERENCE^
11185 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11186 @findex Source_Reference
11187 Generate @code{Source_Reference} pragmas. Use this switch if the output
11188 files are regarded as temporary and development is to be done in terms
11189 of the original unchopped file. This switch causes
11190 @code{Source_Reference} pragmas to be inserted into each of the
11191 generated files to refers back to the original file name and line number.
11192 The result is that all error messages refer back to the original
11193 unchopped file.
11194 In addition, the debugging information placed into the object file (when
11195 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11196 specified)
11197 also refers back to this original file so that tools like profilers and
11198 debuggers will give information in terms of the original unchopped file.
11199
11200 If the original file to be chopped itself contains
11201 a @code{Source_Reference}
11202 pragma referencing a third file, then gnatchop respects
11203 this pragma, and the generated @code{Source_Reference} pragmas
11204 in the chopped file refer to the original file, with appropriate
11205 line numbers. This is particularly useful when @code{gnatchop}
11206 is used in conjunction with @code{gnatprep} to compile files that
11207 contain preprocessing statements and multiple units.
11208
11209 @item ^-v^/VERBOSE^
11210 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11211 Causes @code{gnatchop} to operate in verbose mode. The version
11212 number and copyright notice are output, as well as exact copies of
11213 the gnat1 commands spawned to obtain the chop control information.
11214
11215 @item ^-w^/OVERWRITE^
11216 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11217 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11218 fatal error if there is already a file with the same name as a
11219 file it would otherwise output, in other words if the files to be
11220 chopped contain duplicated units. This switch bypasses this
11221 check, and causes all but the last instance of such duplicated
11222 units to be skipped.
11223
11224 @ifclear vms
11225 @item --GCC=@var{xxxx}
11226 @cindex @option{--GCC=} (@code{gnatchop})
11227 Specify the path of the GNAT parser to be used. When this switch is used,
11228 no attempt is made to add the prefix to the GNAT parser executable.
11229 @end ifclear
11230 @end table
11231
11232 @node Examples of gnatchop Usage
11233 @section Examples of @code{gnatchop} Usage
11234
11235 @table @code
11236 @ifset vms
11237 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11238 @end ifset
11239 @ifclear vms
11240 @item gnatchop -w hello_s.ada prerelease/files
11241 @end ifclear
11242
11243 Chops the source file @file{hello_s.ada}. The output files will be
11244 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11245 overwriting any
11246 files with matching names in that directory (no files in the current
11247 directory are modified).
11248
11249 @item gnatchop ^archive^ARCHIVE.^
11250 Chops the source file @file{^archive^ARCHIVE.^}
11251 into the current directory. One
11252 useful application of @code{gnatchop} is in sending sets of sources
11253 around, for example in email messages. The required sources are simply
11254 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11255 command), and then
11256 @command{gnatchop} is used at the other end to reconstitute the original
11257 file names.
11258
11259 @item gnatchop file1 file2 file3 direc
11260 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11261 the resulting files in the directory @file{direc}. Note that if any units
11262 occur more than once anywhere within this set of files, an error message
11263 is generated, and no files are written. To override this check, use the
11264 @option{^-w^/OVERWRITE^} switch,
11265 in which case the last occurrence in the last file will
11266 be the one that is output, and earlier duplicate occurrences for a given
11267 unit will be skipped.
11268 @end table
11269
11270 @node Configuration Pragmas
11271 @chapter Configuration Pragmas
11272 @cindex Configuration pragmas
11273 @cindex Pragmas, configuration
11274
11275 @noindent
11276 Configuration pragmas include those pragmas described as
11277 such in the Ada Reference Manual, as well as
11278 implementation-dependent pragmas that are configuration pragmas.
11279 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11280 for details on these additional GNAT-specific configuration pragmas.
11281 Most notably, the pragma @code{Source_File_Name}, which allows
11282 specifying non-default names for source files, is a configuration
11283 pragma. The following is a complete list of configuration pragmas
11284 recognized by GNAT:
11285
11286 @smallexample
11287    Ada_83
11288    Ada_95
11289    Ada_05
11290    Ada_2005
11291    Assertion_Policy
11292    C_Pass_By_Copy
11293    Check_Name
11294    Check_Policy
11295    Compile_Time_Error
11296    Compile_Time_Warning
11297    Compiler_Unit
11298    Component_Alignment
11299    Debug_Policy
11300    Detect_Blocking
11301    Discard_Names
11302    Elaboration_Checks
11303    Eliminate
11304    Extend_System
11305    External_Name_Casing
11306    Fast_Math
11307    Favor_Top_Level
11308    Float_Representation
11309    Implicit_Packing
11310    Initialize_Scalars
11311    Interrupt_State
11312    License
11313    Locking_Policy
11314    Long_Float
11315    No_Run_Time
11316    No_Strict_Aliasing
11317    Normalize_Scalars
11318    Optimize_Alignment
11319    Persistent_BSS
11320    Polling
11321    Priority_Specific_Dispatching
11322    Profile
11323    Profile_Warnings
11324    Propagate_Exceptions
11325    Queuing_Policy
11326    Ravenscar
11327    Restricted_Run_Time
11328    Restrictions
11329    Restrictions_Warnings
11330    Reviewable
11331    Source_File_Name
11332    Source_File_Name_Project
11333    Style_Checks
11334    Suppress
11335    Suppress_Exception_Locations
11336    Task_Dispatching_Policy
11337    Universal_Data
11338    Unsuppress
11339    Use_VADS_Size
11340    Validity_Checks
11341    Warnings
11342    Wide_Character_Encoding
11343
11344 @end smallexample
11345
11346 @menu
11347 * Handling of Configuration Pragmas::
11348 * The Configuration Pragmas Files::
11349 @end menu
11350
11351 @node Handling of Configuration Pragmas
11352 @section Handling of Configuration Pragmas
11353
11354 Configuration pragmas may either appear at the start of a compilation
11355 unit, in which case they apply only to that unit, or they may apply to
11356 all compilations performed in a given compilation environment.
11357
11358 GNAT also provides the @code{gnatchop} utility to provide an automatic
11359 way to handle configuration pragmas following the semantics for
11360 compilations (that is, files with multiple units), described in the RM.
11361 See @ref{Operating gnatchop in Compilation Mode} for details.
11362 However, for most purposes, it will be more convenient to edit the
11363 @file{gnat.adc} file that contains configuration pragmas directly,
11364 as described in the following section.
11365
11366 @node The Configuration Pragmas Files
11367 @section The Configuration Pragmas Files
11368 @cindex @file{gnat.adc}
11369
11370 @noindent
11371 In GNAT a compilation environment is defined by the current
11372 directory at the time that a compile command is given. This current
11373 directory is searched for a file whose name is @file{gnat.adc}. If
11374 this file is present, it is expected to contain one or more
11375 configuration pragmas that will be applied to the current compilation.
11376 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11377 considered.
11378
11379 Configuration pragmas may be entered into the @file{gnat.adc} file
11380 either by running @code{gnatchop} on a source file that consists only of
11381 configuration pragmas, or more conveniently  by
11382 direct editing of the @file{gnat.adc} file, which is a standard format
11383 source file.
11384
11385 In addition to @file{gnat.adc}, additional files containing configuration
11386 pragmas may be applied to the current compilation using the switch
11387 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11388 contains only configuration pragmas. These configuration pragmas are
11389 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11390 is present and switch @option{-gnatA} is not used).
11391
11392 It is allowed to specify several switches @option{-gnatec}, all of which
11393 will be taken into account.
11394
11395 If you are using project file, a separate mechanism is provided using
11396 project attributes, see @ref{Specifying Configuration Pragmas} for more
11397 details.
11398
11399 @ifset vms
11400 Of special interest to GNAT OpenVMS Alpha is the following
11401 configuration pragma:
11402
11403 @smallexample @c ada
11404 @cartouche
11405 pragma Extend_System (Aux_DEC);
11406 @end cartouche
11407 @end smallexample
11408
11409 @noindent
11410 In the presence of this pragma, GNAT adds to the definition of the
11411 predefined package SYSTEM all the additional types and subprograms that are
11412 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11413 @end ifset
11414
11415 @node Handling Arbitrary File Naming Conventions Using gnatname
11416 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11417 @cindex Arbitrary File Naming Conventions
11418
11419 @menu
11420 * Arbitrary File Naming Conventions::
11421 * Running gnatname::
11422 * Switches for gnatname::
11423 * Examples of gnatname Usage::
11424 @end menu
11425
11426 @node Arbitrary File Naming Conventions
11427 @section Arbitrary File Naming Conventions
11428
11429 @noindent
11430 The GNAT compiler must be able to know the source file name of a compilation
11431 unit.  When using the standard GNAT default file naming conventions
11432 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11433 does not need additional information.
11434
11435 @noindent
11436 When the source file names do not follow the standard GNAT default file naming
11437 conventions, the GNAT compiler must be given additional information through
11438 a configuration pragmas file (@pxref{Configuration Pragmas})
11439 or a project file.
11440 When the non-standard file naming conventions are well-defined,
11441 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11442 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11443 if the file naming conventions are irregular or arbitrary, a number
11444 of pragma @code{Source_File_Name} for individual compilation units
11445 must be defined.
11446 To help maintain the correspondence between compilation unit names and
11447 source file names within the compiler,
11448 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11449 set of files.
11450
11451 @node Running gnatname
11452 @section Running @code{gnatname}
11453
11454 @noindent
11455 The usual form of the @code{gnatname} command is
11456
11457 @smallexample
11458 $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11459       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11460 @end smallexample
11461
11462 @noindent
11463 All of the arguments are optional. If invoked without any argument,
11464 @code{gnatname} will display its usage.
11465
11466 @noindent
11467 When used with at least one naming pattern, @code{gnatname} will attempt to
11468 find all the compilation units in files that follow at least one of the
11469 naming patterns. To find these compilation units,
11470 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11471 regular files.
11472
11473 @noindent
11474 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11475 Each Naming Pattern is enclosed between double quotes.
11476 A Naming Pattern is a regular expression similar to the wildcard patterns
11477 used in file names by the Unix shells or the DOS prompt.
11478
11479 @noindent
11480 @code{gnatname} may be called with several sections of directories/patterns.
11481 Sections are separated by switch @code{--and}. In each section, there must be
11482 at least one pattern. If no directory is specified in a section, the current
11483 directory (or the project directory is @code{-P} is used) is implied.
11484 The options other that the directory switches and the patterns apply globally
11485 even if they are in different sections.
11486
11487 @noindent
11488 Examples of Naming Patterns are
11489
11490 @smallexample
11491    "*.[12].ada"
11492    "*.ad[sb]*"
11493    "body_*"    "spec_*"
11494 @end smallexample
11495
11496 @noindent
11497 For a more complete description of the syntax of Naming Patterns,
11498 see the second kind of regular expressions described in @file{g-regexp.ads}
11499 (the ``Glob'' regular expressions).
11500
11501 @noindent
11502 When invoked with no switch @code{-P}, @code{gnatname} will create a
11503 configuration pragmas file @file{gnat.adc} in the current working directory,
11504 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11505 unit.
11506
11507 @node Switches for gnatname
11508 @section Switches for @code{gnatname}
11509
11510 @noindent
11511 Switches for @code{gnatname} must precede any specified Naming Pattern.
11512
11513 @noindent
11514 You may specify any of the following switches to @code{gnatname}:
11515
11516 @table @option
11517 @c !sort!
11518
11519 @item --version
11520 @cindex @option{--version} @command{gnatname}
11521 Display Copyright and version, then exit disregarding all other options.
11522
11523 @item --help
11524 @cindex @option{--help} @command{gnatname}
11525 If @option{--version} was not used, display usage, then exit disregarding
11526 all other options.
11527
11528 @item --and
11529 Start another section of directories/patterns.
11530
11531 @item ^-c^/CONFIG_FILE=^@file{file}
11532 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11533 Create a configuration pragmas file @file{file} (instead of the default
11534 @file{gnat.adc}).
11535 @ifclear vms
11536 There may be zero, one or more space between @option{-c} and
11537 @file{file}.
11538 @end ifclear
11539 @file{file} may include directory information. @file{file} must be
11540 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11541 When a switch @option{^-c^/CONFIG_FILE^} is
11542 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11543
11544 @item ^-d^/SOURCE_DIRS=^@file{dir}
11545 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11546 Look for source files in directory @file{dir}. There may be zero, one or more
11547 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11548 When a switch @option{^-d^/SOURCE_DIRS^}
11549 is specified, the current working directory will not be searched for source
11550 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11551 or @option{^-D^/DIR_FILES^} switch.
11552 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11553 If @file{dir} is a relative path, it is relative to the directory of
11554 the configuration pragmas file specified with switch
11555 @option{^-c^/CONFIG_FILE^},
11556 or to the directory of the project file specified with switch
11557 @option{^-P^/PROJECT_FILE^} or,
11558 if neither switch @option{^-c^/CONFIG_FILE^}
11559 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11560 current working directory. The directory
11561 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11562
11563 @item ^-D^/DIRS_FILE=^@file{file}
11564 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11565 Look for source files in all directories listed in text file @file{file}.
11566 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11567 and @file{file}.
11568 @file{file} must be an existing, readable text file.
11569 Each nonempty line in @file{file} must be a directory.
11570 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11571 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11572 @file{file}.
11573
11574 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11575 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11576 Foreign patterns. Using this switch, it is possible to add sources of languages
11577 other than Ada to the list of sources of a project file.
11578 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11579 For example,
11580 @smallexample
11581 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11582 @end smallexample
11583 @noindent
11584 will look for Ada units in all files with the @file{.ada} extension,
11585 and will add to the list of file for project @file{prj.gpr} the C files
11586 with extension @file{.^c^C^}.
11587
11588 @item ^-h^/HELP^
11589 @cindex @option{^-h^/HELP^} (@code{gnatname})
11590 Output usage (help) information. The output is written to @file{stdout}.
11591
11592 @item ^-P^/PROJECT_FILE=^@file{proj}
11593 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11594 Create or update project file @file{proj}. There may be zero, one or more space
11595 between @option{-P} and @file{proj}. @file{proj} may include directory
11596 information. @file{proj} must be writable.
11597 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11598 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11599 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11600
11601 @item ^-v^/VERBOSE^
11602 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11603 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11604 This includes name of the file written, the name of the directories to search
11605 and, for each file in those directories whose name matches at least one of
11606 the Naming Patterns, an indication of whether the file contains a unit,
11607 and if so the name of the unit.
11608
11609 @item ^-v -v^/VERBOSE /VERBOSE^
11610 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11611 Very Verbose mode. In addition to the output produced in verbose mode,
11612 for each file in the searched directories whose name matches none of
11613 the Naming Patterns, an indication is given that there is no match.
11614
11615 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11616 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11617 Excluded patterns. Using this switch, it is possible to exclude some files
11618 that would match the name patterns. For example,
11619 @smallexample
11620 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11621 @end smallexample
11622 @noindent
11623 will look for Ada units in all files with the @file{.ada} extension,
11624 except those whose names end with @file{_nt.ada}.
11625
11626 @end table
11627
11628 @node Examples of gnatname Usage
11629 @section Examples of @code{gnatname} Usage
11630
11631 @ifset vms
11632 @smallexample
11633 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11634 @end smallexample
11635 @end ifset
11636
11637 @ifclear vms
11638 @smallexample
11639 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11640 @end smallexample
11641 @end ifclear
11642
11643 @noindent
11644 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11645 and be writable. In addition, the directory
11646 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11647 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11648
11649 @ifclear vms
11650 Note the optional spaces after @option{-c} and @option{-d}.
11651 @end ifclear
11652
11653 @smallexample
11654 @ifclear vms
11655 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11656   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11657 @end ifclear
11658 @ifset vms
11659 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11660   /EXCLUDED_PATTERN=*_nt_body.ada
11661   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11662   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11663 @end ifset
11664 @end smallexample
11665
11666 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11667 even in conjunction with one or several switches
11668 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11669 are used in this example.
11670
11671 @c *****************************************
11672 @c * G N A T  P r o j e c t  M a n a g e r *
11673 @c *****************************************
11674 @node GNAT Project Manager
11675 @chapter GNAT Project Manager
11676
11677 @menu
11678 * Introduction::
11679 * Examples of Project Files::
11680 * Project File Syntax::
11681 * Objects and Sources in Project Files::
11682 * Importing Projects::
11683 * Project Extension::
11684 * Project Hierarchy Extension::
11685 * External References in Project Files::
11686 * Packages in Project Files::
11687 * Variables from Imported Projects::
11688 * Naming Schemes::
11689 * Library Projects::
11690 * Stand-alone Library Projects::
11691 * Switches Related to Project Files::
11692 * Tools Supporting Project Files::
11693 * An Extended Example::
11694 * Project File Complete Syntax::
11695 @end menu
11696
11697 @c ****************
11698 @c * Introduction *
11699 @c ****************
11700
11701 @node Introduction
11702 @section Introduction
11703
11704 @noindent
11705 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11706 you to manage complex builds involving a number of source files, directories,
11707 and compilation options for different system configurations. In particular,
11708 project files allow you to specify:
11709 @itemize @bullet
11710 @item
11711 The directory or set of directories containing the source files, and/or the
11712 names of the specific source files themselves
11713 @item
11714 The directory in which the compiler's output
11715 (@file{ALI} files, object files, tree files) is to be placed
11716 @item
11717 The directory in which the executable programs is to be placed
11718 @item
11719 ^Switch^Switch^ settings for any of the project-enabled tools
11720 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11721 @code{gnatfind}); you can apply these settings either globally or to individual
11722 compilation units.
11723 @item
11724 The source files containing the main subprogram(s) to be built
11725 @item
11726 The source programming language(s) (currently Ada and/or C)
11727 @item
11728 Source file naming conventions; you can specify these either globally or for
11729 individual compilation units
11730 @end itemize
11731
11732 @menu
11733 * Project Files::
11734 @end menu
11735
11736 @node Project Files
11737 @subsection Project Files
11738
11739 @noindent
11740 Project files are written in a syntax close to that of Ada, using  familiar
11741 notions such as packages, context clauses, declarations, default values,
11742 assignments, and inheritance. Finally, project files can be built
11743 hierarchically from other project files, simplifying complex system
11744 integration and project reuse.
11745
11746 A @dfn{project} is a specific set of values for various compilation properties.
11747 The settings for a given project are described by means of
11748 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11749 Property values in project files are either strings or lists of strings.
11750 Properties that are not explicitly set receive default values.  A project
11751 file may interrogate the values of @dfn{external variables} (user-defined
11752 command-line switches or environment variables), and it may specify property
11753 settings conditionally, based on the value of such variables.
11754
11755 In simple cases, a project's source files depend only on other source files
11756 in the same project, or on the predefined libraries.  (@emph{Dependence} is
11757 used in
11758 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
11759 the Project Manager also allows more sophisticated arrangements,
11760 where the source files in one project depend on source files in other
11761 projects:
11762 @itemize @bullet
11763 @item
11764 One project can @emph{import} other projects containing needed source files.
11765 @item
11766 You can organize GNAT projects in a hierarchy: a @emph{child} project
11767 can extend a @emph{parent} project, inheriting the parent's source files and
11768 optionally overriding any of them with alternative versions
11769 @end itemize
11770
11771 @noindent
11772 More generally, the Project Manager lets you structure large development
11773 efforts into hierarchical subsystems, where build decisions are delegated
11774 to the subsystem level, and thus different compilation environments
11775 (^switch^switch^ settings) used for different subsystems.
11776
11777 The Project Manager is invoked through the
11778 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11779 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11780 @ifclear vms
11781 There may be zero, one or more spaces between @option{-P} and
11782 @option{@emph{projectfile}}.
11783 @end ifclear
11784 If you want to define (on the command line) an external variable that is
11785 queried by the project file, you must use the
11786 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11787 The Project Manager parses and interprets the project file, and drives the
11788 invoked tool based on the project settings.
11789
11790 The Project Manager supports a wide range of development strategies,
11791 for systems of all sizes.  Here are some typical practices that are
11792 easily handled:
11793 @itemize @bullet
11794 @item
11795 Using a common set of source files, but generating object files in different
11796 directories via different ^switch^switch^ settings
11797 @item
11798 Using a mostly-shared set of source files, but with different versions of
11799 some unit or units
11800 @end itemize
11801
11802 @noindent
11803 The destination of an executable can be controlled inside a project file
11804 using the @option{^-o^-o^}
11805 ^switch^switch^.
11806 In the absence of such a ^switch^switch^ either inside
11807 the project file or on the command line, any executable files generated by
11808 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11809 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11810 in the object directory of the project.
11811
11812 You can use project files to achieve some of the effects of a source
11813 versioning system (for example, defining separate projects for
11814 the different sets of sources that comprise different releases) but the
11815 Project Manager is independent of any source configuration management tools
11816 that might be used by the developers.
11817
11818 The next section introduces the main features of GNAT's project facility
11819 through a sequence of examples; subsequent sections will present the syntax
11820 and semantics in more detail. A more formal description of the project
11821 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11822 Reference Manual}.
11823
11824 @c *****************************
11825 @c * Examples of Project Files *
11826 @c *****************************
11827
11828 @node Examples of Project Files
11829 @section Examples of Project Files
11830 @noindent
11831 This section illustrates some of the typical uses of project files and
11832 explains their basic structure and behavior.
11833
11834 @menu
11835 * Common Sources with Different ^Switches^Switches^ and Directories::
11836 * Using External Variables::
11837 * Importing Other Projects::
11838 * Extending a Project::
11839 @end menu
11840
11841 @node Common Sources with Different ^Switches^Switches^ and Directories
11842 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11843
11844 @menu
11845 * Source Files::
11846 * Specifying the Object Directory::
11847 * Specifying the Exec Directory::
11848 * Project File Packages::
11849 * Specifying ^Switch^Switch^ Settings::
11850 * Main Subprograms::
11851 * Executable File Names::
11852 * Source File Naming Conventions::
11853 * Source Language(s)::
11854 @end menu
11855
11856 @noindent
11857 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11858 @file{proc.adb} are in the @file{/common} directory.  The file
11859 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11860 package @code{Pack}.  We want to compile these source files under two sets
11861 of ^switches^switches^:
11862 @itemize @bullet
11863 @item
11864 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11865 and the @option{^-gnata^-gnata^},
11866 @option{^-gnato^-gnato^},
11867 and @option{^-gnatE^-gnatE^} switches to the
11868 compiler; the compiler's output is to appear in @file{/common/debug}
11869 @item
11870 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11871 to the compiler; the compiler's output is to appear in @file{/common/release}
11872 @end itemize
11873
11874 @noindent
11875 The GNAT project files shown below, respectively @file{debug.gpr} and
11876 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11877
11878 Schematically:
11879 @smallexample
11880 @group
11881 ^/common^[COMMON]^
11882   debug.gpr
11883   release.gpr
11884   pack.ads
11885   pack.adb
11886   proc.adb
11887 @end group
11888 @group
11889 ^/common/debug^[COMMON.DEBUG]^
11890   proc.ali, proc.o
11891   pack.ali, pack.o
11892 @end group
11893 @group
11894 ^/common/release^[COMMON.RELEASE]^
11895   proc.ali, proc.o
11896   pack.ali, pack.o
11897 @end group
11898 @end smallexample
11899 Here are the corresponding project files:
11900
11901 @smallexample @c projectfile
11902 @group
11903 project Debug is
11904   for Object_Dir use "debug";
11905   for Main use ("proc");
11906
11907   package Builder is
11908     for ^Default_Switches^Default_Switches^ ("Ada")
11909         use ("^-g^-g^");
11910     for Executable ("proc.adb") use "proc1";
11911   end Builder;
11912 @end group
11913
11914 @group
11915   package Compiler is
11916     for ^Default_Switches^Default_Switches^ ("Ada")
11917        use ("-fstack-check",
11918             "^-gnata^-gnata^",
11919             "^-gnato^-gnato^",
11920             "^-gnatE^-gnatE^");
11921   end Compiler;
11922 end Debug;
11923 @end group
11924 @end smallexample
11925
11926 @smallexample @c projectfile
11927 @group
11928 project Release is
11929   for Object_Dir use "release";
11930   for Exec_Dir use ".";
11931   for Main use ("proc");
11932
11933   package Compiler is
11934     for ^Default_Switches^Default_Switches^ ("Ada")
11935         use ("^-O2^-O2^");
11936   end Compiler;
11937 end Release;
11938 @end group
11939 @end smallexample
11940
11941 @noindent
11942 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11943 insensitive), and analogously the project defined by @file{release.gpr} is
11944 @code{"Release"}.  For consistency the file should have the same name as the
11945 project, and the project file's extension should be @code{"gpr"}. These
11946 conventions are not required, but a warning is issued if they are not followed.
11947
11948 If the current directory is @file{^/temp^[TEMP]^}, then the command
11949 @smallexample
11950 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11951 @end smallexample
11952
11953 @noindent
11954 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11955 as well as the @code{^proc1^PROC1.EXE^} executable,
11956 using the ^switch^switch^ settings defined in the project file.
11957
11958 Likewise, the command
11959 @smallexample
11960 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11961 @end smallexample
11962
11963 @noindent
11964 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11965 and the @code{^proc^PROC.EXE^}
11966 executable in @file{^/common^[COMMON]^},
11967 using the ^switch^switch^ settings from the project file.
11968
11969 @node Source Files
11970 @unnumberedsubsubsec Source Files
11971
11972 @noindent
11973 If a project file does not explicitly specify a set of source directories or
11974 a set of source files, then by default the project's source files are the
11975 Ada source files in the project file directory.  Thus @file{pack.ads},
11976 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11977
11978 @node Specifying the Object Directory
11979 @unnumberedsubsubsec Specifying the Object Directory
11980
11981 @noindent
11982 Several project properties are modeled by Ada-style @emph{attributes};
11983 a property is defined by supplying the equivalent of an Ada attribute
11984 definition clause in the project file.
11985 A project's object directory is another such a property; the corresponding
11986 attribute is @code{Object_Dir}, and its value is also a string expression,
11987 specified either as absolute or relative. In the later case,
11988 it is relative to the project file directory. Thus the compiler's
11989 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
11990 (for the @code{Debug} project)
11991 and to @file{^/common/release^[COMMON.RELEASE]^}
11992 (for the @code{Release} project).
11993 If @code{Object_Dir} is not specified, then the default is the project file
11994 directory itself.
11995
11996 @node Specifying the Exec Directory
11997 @unnumberedsubsubsec Specifying the Exec Directory
11998
11999 @noindent
12000 A project's exec directory is another property; the corresponding
12001 attribute is @code{Exec_Dir}, and its value is also a string expression,
12002 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
12003 then the default is the object directory (which may also be the project file
12004 directory if attribute @code{Object_Dir} is not specified). Thus the executable
12005 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
12006 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
12007 and in @file{^/common^[COMMON]^} for the @code{Release} project.
12008
12009 @node Project File Packages
12010 @unnumberedsubsubsec Project File Packages
12011
12012 @noindent
12013 A GNAT tool that is integrated with the Project Manager is modeled by a
12014 corresponding package in the project file. In the example above,
12015 The @code{Debug} project defines the packages @code{Builder}
12016 (for @command{gnatmake}) and @code{Compiler};
12017 the @code{Release} project defines only the @code{Compiler} package.
12018
12019 The Ada-like package syntax is not to be taken literally.  Although packages in
12020 project files bear a surface resemblance to packages in Ada source code, the
12021 notation is simply a way to convey a grouping of properties for a named
12022 entity.  Indeed, the package names permitted in project files are restricted
12023 to a predefined set, corresponding to the project-aware tools, and the contents
12024 of packages are limited to a small set of constructs.
12025 The packages in the example above contain attribute definitions.
12026
12027 @node Specifying ^Switch^Switch^ Settings
12028 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
12029
12030 @noindent
12031 ^Switch^Switch^ settings for a project-aware tool can be specified through
12032 attributes in the package that corresponds to the tool.
12033 The example above illustrates one of the relevant attributes,
12034 @code{^Default_Switches^Default_Switches^}, which is defined in packages
12035 in both project files.
12036 Unlike simple attributes like @code{Source_Dirs},
12037 @code{^Default_Switches^Default_Switches^} is
12038 known as an @emph{associative array}.  When you define this attribute, you must
12039 supply an ``index'' (a literal string), and the effect of the attribute
12040 definition is to set the value of the array at the specified index.
12041 For the @code{^Default_Switches^Default_Switches^} attribute,
12042 the index is a programming language (in our case, Ada),
12043 and the value specified (after @code{use}) must be a list
12044 of string expressions.
12045
12046 The attributes permitted in project files are restricted to a predefined set.
12047 Some may appear at project level, others in packages.
12048 For any attribute that is an associative array, the index must always be a
12049 literal string, but the restrictions on this string (e.g., a file name or a
12050 language name) depend on the individual attribute.
12051 Also depending on the attribute, its specified value will need to be either a
12052 string or a string list.
12053
12054 In the @code{Debug} project, we set the switches for two tools,
12055 @command{gnatmake} and the compiler, and thus we include the two corresponding
12056 packages; each package defines the @code{^Default_Switches^Default_Switches^}
12057 attribute with index @code{"Ada"}.
12058 Note that the package corresponding to
12059 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
12060 similar, but only includes the @code{Compiler} package.
12061
12062 In project @code{Debug} above, the ^switches^switches^ starting with
12063 @option{-gnat} that are specified in package @code{Compiler}
12064 could have been placed in package @code{Builder}, since @command{gnatmake}
12065 transmits all such ^switches^switches^ to the compiler.
12066
12067 @node Main Subprograms
12068 @unnumberedsubsubsec Main Subprograms
12069
12070 @noindent
12071 One of the specifiable properties of a project is a list of files that contain
12072 main subprograms.  This property is captured in the @code{Main} attribute,
12073 whose value is a list of strings.  If a project defines the @code{Main}
12074 attribute, it is not necessary to identify the main subprogram(s) when
12075 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
12076
12077 @node Executable File Names
12078 @unnumberedsubsubsec Executable File Names
12079
12080 @noindent
12081 By default, the executable file name corresponding to a main source is
12082 deduced from the main source file name. Through the attributes
12083 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
12084 it is possible to change this default.
12085 In project @code{Debug} above, the executable file name
12086 for main source @file{^proc.adb^PROC.ADB^} is
12087 @file{^proc1^PROC1.EXE^}.
12088 Attribute @code{Executable_Suffix}, when specified, may change the suffix
12089 of the executable files, when no attribute @code{Executable} applies:
12090 its value replace the platform-specific executable suffix.
12091 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
12092 specify a non-default executable file name when several mains are built at once
12093 in a single @command{gnatmake} command.
12094
12095 @node Source File Naming Conventions
12096 @unnumberedsubsubsec Source File Naming Conventions
12097
12098 @noindent
12099 Since the project files above do not specify any source file naming
12100 conventions, the GNAT defaults are used.  The mechanism for defining source
12101 file naming conventions -- a package named @code{Naming} --
12102 is described below (@pxref{Naming Schemes}).
12103
12104 @node Source Language(s)
12105 @unnumberedsubsubsec Source Language(s)
12106
12107 @noindent
12108 Since the project files do not specify a @code{Languages} attribute, by
12109 default the GNAT tools assume that the language of the project file is Ada.
12110 More generally, a project can comprise source files
12111 in Ada, C, and/or other languages.
12112
12113 @node Using External Variables
12114 @subsection Using External Variables
12115
12116 @noindent
12117 Instead of supplying different project files for debug and release, we can
12118 define a single project file that queries an external variable (set either
12119 on the command line or via an ^environment variable^logical name^) in order to
12120 conditionally define the appropriate settings.  Again, assume that the
12121 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
12122 located in directory @file{^/common^[COMMON]^}.  The following project file,
12123 @file{build.gpr}, queries the external variable named @code{STYLE} and
12124 defines an object directory and ^switch^switch^ settings based on whether
12125 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
12126 the default is @code{"deb"}.
12127
12128 @smallexample @c projectfile
12129 @group
12130 project Build is
12131   for Main use ("proc");
12132
12133   type Style_Type is ("deb", "rel");
12134   Style : Style_Type := external ("STYLE", "deb");
12135
12136   case Style is
12137     when "deb" =>
12138       for Object_Dir use "debug";
12139
12140     when "rel" =>
12141       for Object_Dir use "release";
12142       for Exec_Dir use ".";
12143   end case;
12144 @end group
12145
12146 @group
12147   package Builder is
12148
12149     case Style is
12150       when "deb" =>
12151         for ^Default_Switches^Default_Switches^ ("Ada")
12152             use ("^-g^-g^");
12153         for Executable ("proc") use "proc1";
12154       when others =>
12155         null;
12156     end case;
12157
12158   end Builder;
12159 @end group
12160
12161 @group
12162   package Compiler is
12163
12164     case Style is
12165       when "deb" =>
12166         for ^Default_Switches^Default_Switches^ ("Ada")
12167             use ("^-gnata^-gnata^",
12168                  "^-gnato^-gnato^",
12169                  "^-gnatE^-gnatE^");
12170
12171       when "rel" =>
12172         for ^Default_Switches^Default_Switches^ ("Ada")
12173             use ("^-O2^-O2^");
12174     end case;
12175
12176   end Compiler;
12177
12178 end Build;
12179 @end group
12180 @end smallexample
12181
12182 @noindent
12183 @code{Style_Type} is an example of a @emph{string type}, which is the project
12184 file analog of an Ada enumeration type but whose components are string literals
12185 rather than identifiers.  @code{Style} is declared as a variable of this type.
12186
12187 The form @code{external("STYLE", "deb")} is known as an
12188 @emph{external reference}; its first argument is the name of an
12189 @emph{external variable}, and the second argument is a default value to be
12190 used if the external variable doesn't exist.  You can define an external
12191 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
12192 or you can use ^an environment variable^a logical name^
12193 as an external variable.
12194
12195 Each @code{case} construct is expanded by the Project Manager based on the
12196 value of @code{Style}. Thus the command
12197 @ifclear vms
12198 @smallexample
12199 gnatmake -P/common/build.gpr -XSTYLE=deb
12200 @end smallexample
12201 @end ifclear
12202
12203 @ifset vms
12204 @smallexample
12205 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
12206 @end smallexample
12207 @end ifset
12208
12209 @noindent
12210 is equivalent to the @command{gnatmake} invocation using the project file
12211 @file{debug.gpr} in the earlier example.  So is the command
12212 @smallexample
12213 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
12214 @end smallexample
12215
12216 @noindent
12217 since @code{"deb"} is the default for @code{STYLE}.
12218
12219 Analogously,
12220
12221 @ifclear vms
12222 @smallexample
12223 gnatmake -P/common/build.gpr -XSTYLE=rel
12224 @end smallexample
12225 @end ifclear
12226
12227 @ifset vms
12228 @smallexample
12229 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
12230 @end smallexample
12231 @end ifset
12232
12233 @noindent
12234 is equivalent to the @command{gnatmake} invocation using the project file
12235 @file{release.gpr} in the earlier example.
12236
12237 @node Importing Other Projects
12238 @subsection Importing Other Projects
12239 @cindex @code{ADA_PROJECT_PATH}
12240
12241 @noindent
12242 A compilation unit in a source file in one project may depend on compilation
12243 units in source files in other projects.  To compile this unit under
12244 control of a project file, the
12245 dependent project must @emph{import} the projects containing the needed source
12246 files.
12247 This effect is obtained using syntax similar to an Ada @code{with} clause,
12248 but where @code{with}ed entities are strings that denote project files.
12249
12250 As an example, suppose that the two projects @code{GUI_Proj} and
12251 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
12252 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
12253 and @file{^/comm^[COMM]^}, respectively.
12254 Suppose that the source files for @code{GUI_Proj} are
12255 @file{gui.ads} and @file{gui.adb}, and that the source files for
12256 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
12257 files is located in its respective project file directory.  Schematically:
12258
12259 @smallexample
12260 @group
12261 ^/gui^[GUI]^
12262   gui_proj.gpr
12263   gui.ads
12264   gui.adb
12265 @end group
12266
12267 @group
12268 ^/comm^[COMM]^
12269   comm_proj.gpr
12270   comm.ads
12271   comm.adb
12272 @end group
12273 @end smallexample
12274
12275 @noindent
12276 We want to develop an application in directory @file{^/app^[APP]^} that
12277 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12278 the corresponding project files (e.g.@: the ^switch^switch^ settings
12279 and object directory).
12280 Skeletal code for a main procedure might be something like the following:
12281
12282 @smallexample @c ada
12283 @group
12284 with GUI, Comm;
12285 procedure App_Main is
12286    @dots{}
12287 begin
12288    @dots{}
12289 end App_Main;
12290 @end group
12291 @end smallexample
12292
12293 @noindent
12294 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12295 effect:
12296
12297 @smallexample @c projectfile
12298 @group
12299 with "/gui/gui_proj", "/comm/comm_proj";
12300 project App_Proj is
12301    for Main use ("app_main");
12302 end App_Proj;
12303 @end group
12304 @end smallexample
12305
12306 @noindent
12307 Building an executable is achieved through the command:
12308 @smallexample
12309 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12310 @end smallexample
12311 @noindent
12312 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12313 in the directory where @file{app_proj.gpr} resides.
12314
12315 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12316 (as illustrated above) the @code{with} clause can omit the extension.
12317
12318 Our example specified an absolute path for each imported project file.
12319 Alternatively, the directory name of an imported object can be omitted
12320 if either
12321 @itemize @bullet
12322 @item
12323 The imported project file is in the same directory as the importing project
12324 file, or
12325 @item
12326 You have defined ^an environment variable^a logical name^
12327 that includes the directory containing
12328 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
12329 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12330 directory names separated by colons (semicolons on Windows).
12331 @end itemize
12332
12333 @noindent
12334 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
12335 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12336 as follows:
12337
12338 @smallexample @c projectfile
12339 @group
12340 with "gui_proj", "comm_proj";
12341 project App_Proj is
12342    for Main use ("app_main");
12343 end App_Proj;
12344 @end group
12345 @end smallexample
12346
12347 @noindent
12348 Importing other projects can create ambiguities.
12349 For example, the same unit might be present in different imported projects, or
12350 it might be present in both the importing project and in an imported project.
12351 Both of these conditions are errors.  Note that in the current version of
12352 the Project Manager, it is illegal to have an ambiguous unit even if the
12353 unit is never referenced by the importing project.  This restriction may be
12354 relaxed in a future release.
12355
12356 @node Extending a Project
12357 @subsection Extending a Project
12358
12359 @noindent
12360 In large software systems it is common to have multiple
12361 implementations of a common interface; in Ada terms, multiple versions of a
12362 package body for the same spec.  For example, one implementation
12363 might be safe for use in tasking programs, while another might only be used
12364 in sequential applications.  This can be modeled in GNAT using the concept
12365 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
12366 another project (the ``parent'') then by default all source files of the
12367 parent project are inherited by the child, but the child project can
12368 override any of the parent's source files with new versions, and can also
12369 add new files.  This facility is the project analog of a type extension in
12370 Object-Oriented Programming.  Project hierarchies are permitted (a child
12371 project may be the parent of yet another project), and a project that
12372 inherits one project can also import other projects.
12373
12374 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12375 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12376 @file{pack.adb}, and @file{proc.adb}:
12377
12378 @smallexample
12379 @group
12380 ^/seq^[SEQ]^
12381   pack.ads
12382   pack.adb
12383   proc.adb
12384   seq_proj.gpr
12385 @end group
12386 @end smallexample
12387
12388 @noindent
12389 Note that the project file can simply be empty (that is, no attribute or
12390 package is defined):
12391
12392 @smallexample @c projectfile
12393 @group
12394 project Seq_Proj is
12395 end Seq_Proj;
12396 @end group
12397 @end smallexample
12398
12399 @noindent
12400 implying that its source files are all the Ada source files in the project
12401 directory.
12402
12403 Suppose we want to supply an alternate version of @file{pack.adb}, in
12404 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12405 @file{pack.ads} and @file{proc.adb}.  We can define a project
12406 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12407
12408 @smallexample
12409 @group
12410 ^/tasking^[TASKING]^
12411   pack.adb
12412   tasking_proj.gpr
12413 @end group
12414
12415 @group
12416 project Tasking_Proj extends "/seq/seq_proj" is
12417 end Tasking_Proj;
12418 @end group
12419 @end smallexample
12420
12421 @noindent
12422 The version of @file{pack.adb} used in a build depends on which project file
12423 is specified.
12424
12425 Note that we could have obtained the desired behavior using project import
12426 rather than project inheritance; a @code{base} project would contain the
12427 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12428 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12429 would import @code{base} and add a different version of @file{pack.adb}.  The
12430 choice depends on whether other sources in the original project need to be
12431 overridden.  If they do, then project extension is necessary, otherwise,
12432 importing is sufficient.
12433
12434 @noindent
12435 In a project file that extends another project file, it is possible to
12436 indicate that an inherited source is not part of the sources of the extending
12437 project. This is necessary sometimes when a package spec has been overloaded
12438 and no longer requires a body: in this case, it is necessary to indicate that
12439 the inherited body is not part of the sources of the project, otherwise there
12440 will be a compilation error when compiling the spec.
12441
12442 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12443 Its value is a string list: a list of file names. It is also possible to use
12444 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12445 the file name of a text file containing a list of file names, one per line.
12446
12447 @smallexample @c @projectfile
12448 project B extends "a" is
12449    for Source_Files use ("pkg.ads");
12450    --  New spec of Pkg does not need a completion
12451    for Excluded_Source_Files use ("pkg.adb");
12452 end B;
12453 @end smallexample
12454
12455 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12456 is still needed: if it is possible to build using @command{gnatmake} when such
12457 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12458 it is possible to remove the source completely from a system that includes
12459 project P.
12460
12461 @c ***********************
12462 @c * Project File Syntax *
12463 @c ***********************
12464
12465 @node Project File Syntax
12466 @section Project File Syntax
12467
12468 @menu
12469 * Basic Syntax::
12470 * Qualified Projects::
12471 * Packages::
12472 * Expressions::
12473 * String Types::
12474 * Variables::
12475 * Attributes::
12476 * Associative Array Attributes::
12477 * case Constructions::
12478 @end menu
12479
12480 @noindent
12481 This section describes the structure of project files.
12482
12483 A project may be an @emph{independent project}, entirely defined by a single
12484 project file. Any Ada source file in an independent project depends only
12485 on the predefined library and other Ada source files in the same project.
12486
12487 @noindent
12488 A project may also @dfn{depend on} other projects, in either or both of
12489 the following ways:
12490 @itemize @bullet
12491 @item It may import any number of projects
12492 @item It may extend at most one other project
12493 @end itemize
12494
12495 @noindent
12496 The dependence relation is a directed acyclic graph (the subgraph reflecting
12497 the ``extends'' relation is a tree).
12498
12499 A project's @dfn{immediate sources} are the source files directly defined by
12500 that project, either implicitly by residing in the project file's directory,
12501 or explicitly through any of the source-related attributes described below.
12502 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12503 of @var{proj} together with the immediate sources (unless overridden) of any
12504 project on which @var{proj} depends (either directly or indirectly).
12505
12506 @node Basic Syntax
12507 @subsection Basic Syntax
12508
12509 @noindent
12510 As seen in the earlier examples, project files have an Ada-like syntax.
12511 The minimal project file is:
12512 @smallexample @c projectfile
12513 @group
12514 project Empty is
12515
12516 end Empty;
12517 @end group
12518 @end smallexample
12519
12520 @noindent
12521 The identifier @code{Empty} is the name of the project.
12522 This project name must be present after the reserved
12523 word @code{end} at the end of the project file, followed by a semi-colon.
12524
12525 Any name in a project file, such as the project name or a variable name,
12526 has the same syntax as an Ada identifier.
12527
12528 The reserved words of project files are the Ada 95 reserved words plus
12529 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
12530 reserved words currently used in project file syntax are:
12531
12532 @itemize @bullet
12533 @item
12534 @code{all}
12535 @item
12536 @code{at}
12537 @item
12538 @code{case}
12539 @item
12540 @code{end}
12541 @item
12542 @code{for}
12543 @item
12544 @code{is}
12545 @item
12546 @code{limited}
12547 @item
12548 @code{null}
12549 @item
12550 @code{others}
12551 @item
12552 @code{package}
12553 @item
12554 @code{renames}
12555 @item
12556 @code{type}
12557 @item
12558 @code{use}
12559 @item
12560 @code{when}
12561 @item
12562 @code{with}
12563 @end itemize
12564
12565 @noindent
12566 Comments in project files have the same syntax as in Ada, two consecutive
12567 hyphens through the end of the line.
12568
12569 @node Qualified Projects
12570 @subsection Qualified Projects
12571
12572 @noindent
12573 Before the reserved @code{project}, there may be one or two "qualifiers", that
12574 is identifiers or other reserved words, to qualify the project.
12575
12576 The current list of qualifiers is:
12577
12578 @itemize @bullet
12579 @item
12580 @code{abstract}: qualify a project with no sources. A qualified abstract
12581 project must either have no declaration of attributes @code{Source_Dirs},
12582 @code{Source_Files}, @code{Languages} or @code{Source_List_File}, or one of
12583 @code{Source_Dirs}, @code{Source_Files}, or @code{Languages} must be declared
12584 as empty. If it extends another project, the project it extends must also be a
12585 qualified abstract project.
12586
12587 @item
12588 @code{standard}: a standard project is a non library project with sources.
12589
12590 @item
12591 @code{aggregate}: for future extension
12592
12593 @item
12594 @code{aggregate library}: for future extension
12595
12596 @item
12597 @code{library}: a library project must declare both attributes
12598 @code{Library_Name} and @code{Library_Dir}.
12599
12600 @item
12601 @code{configuration}: a configuration project cannot be in a project tree.
12602 @end itemize
12603
12604 @node Packages
12605 @subsection Packages
12606
12607 @noindent
12608 A project file may contain @emph{packages}. The name of a package must be one
12609 of the identifiers from the following list. A package
12610 with a given name may only appear once in a project file. Package names are
12611 case insensitive. The following package names are legal:
12612
12613 @itemize @bullet
12614 @item
12615 @code{Naming}
12616 @item
12617 @code{Builder}
12618 @item
12619 @code{Compiler}
12620 @item
12621 @code{Binder}
12622 @item
12623 @code{Linker}
12624 @item
12625 @code{Finder}
12626 @item
12627 @code{Cross_Reference}
12628 @item
12629 @code{Eliminate}
12630 @item
12631 @code{Pretty_Printer}
12632 @item
12633 @code{Metrics}
12634 @item
12635 @code{gnatls}
12636 @item
12637 @code{gnatstub}
12638 @item
12639 @code{IDE}
12640 @item
12641 @code{Language_Processing}
12642 @end itemize
12643
12644 @noindent
12645 In its simplest form, a package may be empty:
12646
12647 @smallexample @c projectfile
12648 @group
12649 project Simple is
12650   package Builder is
12651   end Builder;
12652 end Simple;
12653 @end group
12654 @end smallexample
12655
12656 @noindent
12657 A package may contain @emph{attribute declarations},
12658 @emph{variable declarations} and @emph{case constructions}, as will be
12659 described below.
12660
12661 When there is ambiguity between a project name and a package name,
12662 the name always designates the project. To avoid possible confusion, it is
12663 always a good idea to avoid naming a project with one of the
12664 names allowed for packages or any name that starts with @code{gnat}.
12665
12666 @node Expressions
12667 @subsection Expressions
12668
12669 @noindent
12670 An @emph{expression} is either a @emph{string expression} or a
12671 @emph{string list expression}.
12672
12673 A @emph{string expression} is either a @emph{simple string expression} or a
12674 @emph{compound string expression}.
12675
12676 A @emph{simple string expression} is one of the following:
12677 @itemize @bullet
12678 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12679 @item A string-valued variable reference (@pxref{Variables})
12680 @item A string-valued attribute reference (@pxref{Attributes})
12681 @item An external reference (@pxref{External References in Project Files})
12682 @end itemize
12683
12684 @noindent
12685 A @emph{compound string expression} is a concatenation of string expressions,
12686 using the operator @code{"&"}
12687 @smallexample
12688        Path & "/" & File_Name & ".ads"
12689 @end smallexample
12690
12691 @noindent
12692 A @emph{string list expression} is either a
12693 @emph{simple string list expression} or a
12694 @emph{compound string list expression}.
12695
12696 A @emph{simple string list expression} is one of the following:
12697 @itemize @bullet
12698 @item A parenthesized list of zero or more string expressions,
12699 separated by commas
12700 @smallexample
12701    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12702    Empty_List := ();
12703 @end smallexample
12704 @item A string list-valued variable reference
12705 @item A string list-valued attribute reference
12706 @end itemize
12707
12708 @noindent
12709 A @emph{compound string list expression} is the concatenation (using
12710 @code{"&"}) of a simple string list expression and an expression.  Note that
12711 each term in a compound string list expression, except the first, may be
12712 either a string expression or a string list expression.
12713
12714 @smallexample @c projectfile
12715 @group
12716    File_Name_List := () & File_Name; --  One string in this list
12717    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12718    --  Two strings
12719    Big_List := File_Name_List & Extended_File_Name_List;
12720    --  Concatenation of two string lists: three strings
12721    Illegal_List := "gnat.adc" & Extended_File_Name_List;
12722    --  Illegal: must start with a string list
12723 @end group
12724 @end smallexample
12725
12726 @node String Types
12727 @subsection String Types
12728
12729 @noindent
12730 A @emph{string type declaration} introduces a discrete set of string literals.
12731 If a string variable is declared to have this type, its value
12732 is restricted to the given set of literals.
12733
12734 Here is an example of a string type declaration:
12735
12736 @smallexample @c projectfile
12737    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12738 @end smallexample
12739
12740 @noindent
12741 Variables of a string type are called @emph{typed variables}; all other
12742 variables are called @emph{untyped variables}. Typed variables are
12743 particularly useful in @code{case} constructions, to support conditional
12744 attribute declarations.
12745 (@pxref{case Constructions}).
12746
12747 The string literals in the list are case sensitive and must all be different.
12748 They may include any graphic characters allowed in Ada, including spaces.
12749
12750 A string type may only be declared at the project level, not inside a package.
12751
12752 A string type may be referenced by its name if it has been declared in the same
12753 project file, or by an expanded name whose prefix is the name of the project
12754 in which it is declared.
12755
12756 @node Variables
12757 @subsection Variables
12758
12759 @noindent
12760 A variable may be declared at the project file level, or within a package.
12761 Here are some examples of variable declarations:
12762
12763 @smallexample @c projectfile
12764 @group
12765    This_OS : OS := external ("OS"); --  a typed variable declaration
12766    That_OS := "GNU/Linux";          --  an untyped variable declaration
12767 @end group
12768 @end smallexample
12769
12770 @noindent
12771 The syntax of a @emph{typed variable declaration} is identical to the Ada
12772 syntax for an object declaration. By contrast, the syntax of an untyped
12773 variable declaration is identical to an Ada assignment statement. In fact,
12774 variable declarations in project files have some of the characteristics of
12775 an assignment, in that successive declarations for the same variable are
12776 allowed. Untyped variable declarations do establish the expected kind of the
12777 variable (string or string list), and successive declarations for it must
12778 respect the initial kind.
12779
12780 @noindent
12781 A string variable declaration (typed or untyped) declares a variable
12782 whose value is a string. This variable may be used as a string expression.
12783 @smallexample @c projectfile
12784    File_Name       := "readme.txt";
12785    Saved_File_Name := File_Name & ".saved";
12786 @end smallexample
12787
12788 @noindent
12789 A string list variable declaration declares a variable whose value is a list
12790 of strings. The list may contain any number (zero or more) of strings.
12791
12792 @smallexample @c projectfile
12793    Empty_List := ();
12794    List_With_One_Element := ("^-gnaty^-gnaty^");
12795    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12796    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12797                  "pack2.ada", "util_.ada", "util.ada");
12798 @end smallexample
12799
12800 @noindent
12801 The same typed variable may not be declared more than once at project level,
12802 and it may not be declared more than once in any package; it is in effect
12803 a constant.
12804
12805 The same untyped variable may be declared several times. Declarations are
12806 elaborated in the order in which they appear, so  the new value replaces
12807 the old one, and any subsequent reference to the variable uses the new value.
12808 However, as noted above, if a variable has been declared as a string, all
12809 subsequent
12810 declarations must give it a string value. Similarly, if a variable has
12811 been declared as a string list, all subsequent declarations
12812 must give it a string list value.
12813
12814 A @emph{variable reference} may take several forms:
12815
12816 @itemize @bullet
12817 @item The simple variable name, for a variable in the current package (if any)
12818 or in the current project
12819 @item An expanded name, whose prefix is a context name.
12820 @end itemize
12821
12822 @noindent
12823 A @emph{context} may be one of the following:
12824
12825 @itemize @bullet
12826 @item The name of an existing package in the current project
12827 @item The name of an imported project of the current project
12828 @item The name of an ancestor project (i.e., a project extended by the current
12829 project, either directly or indirectly)
12830 @item An expanded name whose prefix is an imported/parent project name, and
12831 whose selector is a package name in that project.
12832 @end itemize
12833
12834 @noindent
12835 A variable reference may be used in an expression.
12836
12837 @node Attributes
12838 @subsection Attributes
12839
12840 @noindent
12841 A project (and its packages) may have @emph{attributes} that define
12842 the project's properties.  Some attributes have values that are strings;
12843 others have values that are string lists.
12844
12845 There are two categories of attributes: @emph{simple attributes}
12846 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12847
12848 Legal project attribute names, and attribute names for each legal package are
12849 listed below. Attributes names are case-insensitive.
12850
12851 The following attributes are defined on projects (all are simple attributes):
12852
12853 @multitable @columnfractions .4 .3
12854 @item @emph{Attribute Name}
12855 @tab @emph{Value}
12856 @item @code{Source_Files}
12857 @tab string list
12858 @item @code{Source_Dirs}
12859 @tab string list
12860 @item @code{Source_List_File}
12861 @tab string
12862 @item @code{Object_Dir}
12863 @tab string
12864 @item @code{Exec_Dir}
12865 @tab string
12866 @item @code{Excluded_Source_Dirs}
12867 @tab string list
12868 @item @code{Excluded_Source_Files}
12869 @tab string list
12870 @item @code{Excluded_Source_List_File}
12871 @tab string
12872 @item @code{Languages}
12873 @tab string list
12874 @item @code{Main}
12875 @tab string list
12876 @item @code{Library_Dir}
12877 @tab string
12878 @item @code{Library_Name}
12879 @tab string
12880 @item @code{Library_Kind}
12881 @tab string
12882 @item @code{Library_Version}
12883 @tab string
12884 @item @code{Library_Interface}
12885 @tab string
12886 @item @code{Library_Auto_Init}
12887 @tab string
12888 @item @code{Library_Options}
12889 @tab string list
12890 @item @code{Library_Src_Dir}
12891 @tab string
12892 @item @code{Library_ALI_Dir}
12893 @tab string
12894 @item @code{Library_GCC}
12895 @tab string
12896 @item @code{Library_Symbol_File}
12897 @tab string
12898 @item @code{Library_Symbol_Policy}
12899 @tab string
12900 @item @code{Library_Reference_Symbol_File}
12901 @tab string
12902 @item @code{Externally_Built}
12903 @tab string
12904 @end multitable
12905
12906 @noindent
12907 The following attributes are defined for package  @code{Naming}
12908 (@pxref{Naming Schemes}):
12909
12910 @multitable @columnfractions .4 .2 .2 .2
12911 @item Attribute Name @tab Category @tab Index @tab Value
12912 @item @code{Spec_Suffix}
12913 @tab associative array
12914 @tab language name
12915 @tab string
12916 @item @code{Body_Suffix}
12917 @tab associative array
12918 @tab language name
12919 @tab string
12920 @item @code{Separate_Suffix}
12921 @tab simple attribute
12922 @tab n/a
12923 @tab string
12924 @item @code{Casing}
12925 @tab simple attribute
12926 @tab n/a
12927 @tab string
12928 @item @code{Dot_Replacement}
12929 @tab simple attribute
12930 @tab n/a
12931 @tab string
12932 @item @code{Spec}
12933 @tab associative array
12934 @tab Ada unit name
12935 @tab string
12936 @item @code{Body}
12937 @tab associative array
12938 @tab Ada unit name
12939 @tab string
12940 @item @code{Specification_Exceptions}
12941 @tab associative array
12942 @tab language name
12943 @tab string list
12944 @item @code{Implementation_Exceptions}
12945 @tab associative array
12946 @tab language name
12947 @tab string list
12948 @end multitable
12949
12950 @noindent
12951 The following attributes are defined for packages @code{Builder},
12952 @code{Compiler}, @code{Binder},
12953 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12954 (@pxref{^Switches^Switches^ and Project Files}).
12955
12956 @multitable @columnfractions .4 .2 .2 .2
12957 @item Attribute Name @tab Category @tab Index @tab Value
12958 @item @code{^Default_Switches^Default_Switches^}
12959 @tab associative array
12960 @tab language name
12961 @tab string list
12962 @item @code{^Switches^Switches^}
12963 @tab associative array
12964 @tab file name
12965 @tab string list
12966 @end multitable
12967
12968 @noindent
12969 In addition, package @code{Compiler} has a single string attribute
12970 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12971 string attribute @code{Global_Configuration_Pragmas}.
12972
12973 @noindent
12974 Each simple attribute has a default value: the empty string (for string-valued
12975 attributes) and the empty list (for string list-valued attributes).
12976
12977 An attribute declaration defines a new value for an attribute.
12978
12979 Examples of simple attribute declarations:
12980
12981 @smallexample @c projectfile
12982    for Object_Dir use "objects";
12983    for Source_Dirs use ("units", "test/drivers");
12984 @end smallexample
12985
12986 @noindent
12987 The syntax of a @dfn{simple attribute declaration} is similar to that of an
12988 attribute definition clause in Ada.
12989
12990 Attributes references may be appear in expressions.
12991 The general form for such a reference is @code{<entity>'<attribute>}:
12992 Associative array attributes are functions. Associative
12993 array attribute references must have an argument that is a string literal.
12994
12995 Examples are:
12996
12997 @smallexample @c projectfile
12998   project'Object_Dir
12999   Naming'Dot_Replacement
13000   Imported_Project'Source_Dirs
13001   Imported_Project.Naming'Casing
13002   Builder'^Default_Switches^Default_Switches^("Ada")
13003 @end smallexample
13004
13005 @noindent
13006 The prefix of an attribute may be:
13007 @itemize @bullet
13008 @item @code{project} for an attribute of the current project
13009 @item The name of an existing package of the current project
13010 @item The name of an imported project
13011 @item The name of a parent project that is extended by the current project
13012 @item An expanded name whose prefix is imported/parent project name,
13013 and whose selector is a package name
13014 @end itemize
13015
13016 @noindent
13017 Example:
13018 @smallexample @c projectfile
13019 @group
13020    project Prj is
13021      for Source_Dirs use project'Source_Dirs & "units";
13022      for Source_Dirs use project'Source_Dirs & "test/drivers"
13023    end Prj;
13024 @end group
13025 @end smallexample
13026
13027 @noindent
13028 In the first attribute declaration, initially the attribute @code{Source_Dirs}
13029 has the default value: an empty string list. After this declaration,
13030 @code{Source_Dirs} is a string list of one element: @code{"units"}.
13031 After the second attribute declaration @code{Source_Dirs} is a string list of
13032 two elements: @code{"units"} and @code{"test/drivers"}.
13033
13034 Note: this example is for illustration only. In practice,
13035 the project file would contain only one attribute declaration:
13036
13037 @smallexample @c projectfile
13038    for Source_Dirs use ("units", "test/drivers");
13039 @end smallexample
13040
13041 @node Associative Array Attributes
13042 @subsection Associative Array Attributes
13043
13044 @noindent
13045 Some attributes are defined as @emph{associative arrays}. An associative
13046 array may be regarded as a function that takes a string as a parameter
13047 and delivers a string or string list value as its result.
13048
13049 Here are some examples of single associative array attribute associations:
13050
13051 @smallexample @c projectfile
13052    for Body ("main") use "Main.ada";
13053    for ^Switches^Switches^ ("main.ada")
13054        use ("^-v^-v^",
13055             "^-gnatv^-gnatv^");
13056    for ^Switches^Switches^ ("main.ada")
13057             use Builder'^Switches^Switches^ ("main.ada")
13058               & "^-g^-g^";
13059 @end smallexample
13060
13061 @noindent
13062 Like untyped variables and simple attributes, associative array attributes
13063 may be declared several times. Each declaration supplies a new value for the
13064 attribute, and replaces the previous setting.
13065
13066 @noindent
13067 An associative array attribute may be declared as a full associative array
13068 declaration, with the value of the same attribute in an imported or extended
13069 project.
13070
13071 @smallexample @c projectfile
13072    package Builder is
13073       for Default_Switches use Default.Builder'Default_Switches;
13074    end Builder;
13075 @end smallexample
13076
13077 @noindent
13078 In this example, @code{Default} must be either a project imported by the
13079 current project, or the project that the current project extends. If the
13080 attribute is in a package (in this case, in package @code{Builder}), the same
13081 package needs to be specified.
13082
13083 @noindent
13084 A full associative array declaration replaces any other declaration for the
13085 attribute, including other full associative array declaration. Single
13086 associative array associations may be declare after a full associative
13087 declaration, modifying the value for a single association of the attribute.
13088
13089 @node case Constructions
13090 @subsection @code{case} Constructions
13091
13092 @noindent
13093 A @code{case} construction is used in a project file to effect conditional
13094 behavior.
13095 Here is a typical example:
13096
13097 @smallexample @c projectfile
13098 @group
13099 project MyProj is
13100    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
13101
13102    OS : OS_Type := external ("OS", "GNU/Linux");
13103 @end group
13104
13105 @group
13106    package Compiler is
13107      case OS is
13108        when "GNU/Linux" | "Unix" =>
13109          for ^Default_Switches^Default_Switches^ ("Ada")
13110              use ("^-gnath^-gnath^");
13111        when "NT" =>
13112          for ^Default_Switches^Default_Switches^ ("Ada")
13113              use ("^-gnatP^-gnatP^");
13114        when others =>
13115      end case;
13116    end Compiler;
13117 end MyProj;
13118 @end group
13119 @end smallexample
13120
13121 @noindent
13122 The syntax of a @code{case} construction is based on the Ada case statement
13123 (although there is no @code{null} construction for empty alternatives).
13124
13125 The case expression must be a typed string variable.
13126 Each alternative comprises the reserved word @code{when}, either a list of
13127 literal strings separated by the @code{"|"} character or the reserved word
13128 @code{others},  and the @code{"=>"} token.
13129 Each literal string must belong to the string type that is the type of the
13130 case variable.
13131 An @code{others} alternative, if present, must occur last.
13132
13133 After each @code{=>}, there are zero or more constructions.  The only
13134 constructions allowed in a case construction are other case constructions,
13135 attribute declarations and variable declarations. String type declarations and
13136 package declarations are not allowed. Variable declarations are restricted to
13137 variables that have already been declared before the case construction.
13138
13139 The value of the case variable is often given by an external reference
13140 (@pxref{External References in Project Files}).
13141
13142 @c ****************************************
13143 @c * Objects and Sources in Project Files *
13144 @c ****************************************
13145
13146 @node Objects and Sources in Project Files
13147 @section Objects and Sources in Project Files
13148
13149 @menu
13150 * Object Directory::
13151 * Exec Directory::
13152 * Source Directories::
13153 * Source File Names::
13154 @end menu
13155
13156 @noindent
13157 Each project has exactly one object directory and one or more source
13158 directories. The source directories must contain at least one source file,
13159 unless  the project file explicitly specifies that no source files are present
13160 (@pxref{Source File Names}).
13161
13162 @node Object Directory
13163 @subsection Object Directory
13164
13165 @noindent
13166 The object directory for a project is the directory containing the compiler's
13167 output (such as @file{ALI} files and object files) for the project's immediate
13168 sources.
13169
13170 The object directory is given by the value of the attribute @code{Object_Dir}
13171 in the project file.
13172
13173 @smallexample @c projectfile
13174    for Object_Dir use "objects";
13175 @end smallexample
13176
13177 @noindent
13178 The attribute @code{Object_Dir} has a string value, the path name of the object
13179 directory. The path name may be absolute or relative to the directory of the
13180 project file. This directory must already exist, and be readable and writable.
13181
13182 By default, when the attribute @code{Object_Dir} is not given an explicit value
13183 or when its value is the empty string, the object directory is the same as the
13184 directory containing the project file.
13185
13186 @node Exec Directory
13187 @subsection Exec Directory
13188
13189 @noindent
13190 The exec directory for a project is the directory containing the executables
13191 for the project's main subprograms.
13192
13193 The exec directory is given by the value of the attribute @code{Exec_Dir}
13194 in the project file.
13195
13196 @smallexample @c projectfile
13197    for Exec_Dir use "executables";
13198 @end smallexample
13199
13200 @noindent
13201 The attribute @code{Exec_Dir} has a string value, the path name of the exec
13202 directory. The path name may be absolute or relative to the directory of the
13203 project file. This directory must already exist, and be writable.
13204
13205 By default, when the attribute @code{Exec_Dir} is not given an explicit value
13206 or when its value is the empty string, the exec directory is the same as the
13207 object directory of the project file.
13208
13209 @node Source Directories
13210 @subsection Source Directories
13211
13212 @noindent
13213 The source directories of a project are specified by the project file
13214 attribute @code{Source_Dirs}.
13215
13216 This attribute's value is a string list. If the attribute is not given an
13217 explicit value, then there is only one source directory, the one where the
13218 project file resides.
13219
13220 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
13221 as in
13222
13223 @smallexample @c projectfile
13224     for Source_Dirs use ();
13225 @end smallexample
13226
13227 @noindent
13228 indicates that the project contains no source files.
13229
13230 Otherwise, each string in the string list designates one or more
13231 source directories.
13232
13233 @smallexample @c projectfile
13234    for Source_Dirs use ("sources", "test/drivers");
13235 @end smallexample
13236
13237 @noindent
13238 If a string in the list ends with @code{"/**"},  then the directory whose path
13239 name precedes the two asterisks, as well as all its subdirectories
13240 (recursively), are source directories.
13241
13242 @smallexample @c projectfile
13243    for Source_Dirs use ("/system/sources/**");
13244 @end smallexample
13245
13246 @noindent
13247 Here the directory @code{/system/sources} and all of its subdirectories
13248 (recursively) are source directories.
13249
13250 To specify that the source directories are the directory of the project file
13251 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
13252 @smallexample @c projectfile
13253    for Source_Dirs use ("./**");
13254 @end smallexample
13255
13256 @noindent
13257 Each of the source directories must exist and be readable.
13258
13259 @node Source File Names
13260 @subsection Source File Names
13261
13262 @noindent
13263 In a project that contains source files, their names may be specified by the
13264 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
13265 (a string). Source file names never include any directory information.
13266
13267 If the attribute @code{Source_Files} is given an explicit value, then each
13268 element of the list is a source file name.
13269
13270 @smallexample @c projectfile
13271    for Source_Files use ("main.adb");
13272    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
13273 @end smallexample
13274
13275 @noindent
13276 If the attribute @code{Source_Files} is not given an explicit value,
13277 but the attribute @code{Source_List_File} is given a string value,
13278 then the source file names are contained in the text file whose path name
13279 (absolute or relative to the directory of the project file) is the
13280 value of the attribute @code{Source_List_File}.
13281
13282 Each line in the file that is not empty or is not a comment
13283 contains a source file name.
13284
13285 @smallexample @c projectfile
13286    for Source_List_File use "source_list.txt";
13287 @end smallexample
13288
13289 @noindent
13290 By default, if neither the attribute @code{Source_Files} nor the attribute
13291 @code{Source_List_File} is given an explicit value, then each file in the
13292 source directories that conforms to the project's naming scheme
13293 (@pxref{Naming Schemes}) is an immediate source of the project.
13294
13295 A warning is issued if both attributes @code{Source_Files} and
13296 @code{Source_List_File} are given explicit values. In this case, the attribute
13297 @code{Source_Files} prevails.
13298
13299 Each source file name must be the name of one existing source file
13300 in one of the source directories.
13301
13302 A @code{Source_Files} attribute whose value is an empty list
13303 indicates that there are no source files in the project.
13304
13305 If the order of the source directories is known statically, that is if
13306 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13307 be several files with the same source file name. In this case, only the file
13308 in the first directory is considered as an immediate source of the project
13309 file. If the order of the source directories is not known statically, it is
13310 an error to have several files with the same source file name.
13311
13312 Projects can be specified to have no Ada source
13313 files: the value of @code{Source_Dirs} or @code{Source_Files} may be an empty
13314 list, or the @code{"Ada"} may be absent from @code{Languages}:
13315
13316 @smallexample @c projectfile
13317    for Source_Dirs use ();
13318    for Source_Files use ();
13319    for Languages use ("C", "C++");
13320 @end smallexample
13321
13322 @noindent
13323 Otherwise, a project must contain at least one immediate source.
13324
13325 Projects with no source files are useful as template packages
13326 (@pxref{Packages in Project Files}) for other projects; in particular to
13327 define a package @code{Naming} (@pxref{Naming Schemes}).
13328
13329 @c ****************************
13330 @c * Importing Projects *
13331 @c ****************************
13332
13333 @node  Importing Projects
13334 @section Importing Projects
13335 @cindex @code{ADA_PROJECT_PATH}
13336
13337 @noindent
13338 An immediate source of a project P may depend on source files that
13339 are neither immediate sources of P nor in the predefined library.
13340 To get this effect, P must @emph{import} the projects that contain the needed
13341 source files.
13342
13343 @smallexample @c projectfile
13344 @group
13345   with "project1", "utilities.gpr";
13346   with "/namings/apex.gpr";
13347   project Main is
13348     @dots{}
13349 @end group
13350 @end smallexample
13351
13352 @noindent
13353 As can be seen in this example, the syntax for importing projects is similar
13354 to the syntax for importing compilation units in Ada. However, project files
13355 use literal strings instead of names, and the @code{with} clause identifies
13356 project files rather than packages.
13357
13358 Each literal string is the file name or path name (absolute or relative) of a
13359 project file. If a string corresponds to a file name, with no path or a
13360 relative path, then its location is determined by the @emph{project path}. The
13361 latter can be queried using @code{gnatls -v}. It contains:
13362
13363 @itemize @bullet
13364 @item
13365 In first position, the directory containing the current project file.
13366 @item
13367 In last position, the default project directory. This default project directory
13368 is part of the GNAT installation and is the standard place to install project
13369 files giving access to standard support libraries.
13370 @ifclear vms
13371 @ref{Installing a library}
13372 @end ifclear
13373
13374 @item
13375 In between, all the directories referenced in the
13376 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
13377 @end itemize
13378
13379 @noindent
13380 If a relative pathname is used, as in
13381
13382 @smallexample @c projectfile
13383   with "tests/proj";
13384 @end smallexample
13385
13386 @noindent
13387 then the full path for the project is constructed by concatenating this
13388 relative path to those in the project path, in order, until a matching file is
13389 found. Any symbolic link will be fully resolved in the directory of the
13390 importing project file before the imported project file is examined.
13391
13392 If the @code{with}'ed project file name does not have an extension,
13393 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13394 then the file name as specified in the @code{with} clause (no extension) will
13395 be used. In the above example, if a file @code{project1.gpr} is found, then it
13396 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13397 then it will be used; if neither file exists, this is an error.
13398
13399 A warning is issued if the name of the project file does not match the
13400 name of the project; this check is case insensitive.
13401
13402 Any source file that is an immediate source of the imported project can be
13403 used by the immediate sources of the importing project, transitively. Thus
13404 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13405 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13406 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13407 because if and when @code{B} ceases to import @code{C}, some sources in
13408 @code{A} will no longer compile.
13409
13410 A side effect of this capability is that normally cyclic dependencies are not
13411 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13412 is not allowed to import @code{A}. However, there are cases when cyclic
13413 dependencies would be beneficial. For these cases, another form of import
13414 between projects exists, the @code{limited with}: a project @code{A} that
13415 imports a project @code{B} with a straight @code{with} may also be imported,
13416 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13417 to @code{A} include at least one @code{limited with}.
13418
13419 @smallexample @c 0projectfile
13420 with "../b/b.gpr";
13421 with "../c/c.gpr";
13422 project A is
13423 end A;
13424
13425 limited with "../a/a.gpr";
13426 project B is
13427 end B;
13428
13429 with "../d/d.gpr";
13430 project C is
13431 end C;
13432
13433 limited with "../a/a.gpr";
13434 project D is
13435 end D;
13436 @end smallexample
13437
13438 @noindent
13439 In the above legal example, there are two project cycles:
13440 @itemize @bullet
13441 @item A-> B-> A
13442 @item A -> C -> D -> A
13443 @end itemize
13444
13445 @noindent
13446 In each of these cycle there is one @code{limited with}: import of @code{A}
13447 from @code{B} and import of @code{A} from @code{D}.
13448
13449 The difference between straight @code{with} and @code{limited with} is that
13450 the name of a project imported with a @code{limited with} cannot be used in the
13451 project that imports it. In particular, its packages cannot be renamed and
13452 its variables cannot be referred to.
13453
13454 An exception to the above rules for @code{limited with} is that for the main
13455 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13456 @code{limited with} is equivalent to a straight @code{with}. For example,
13457 in the example above, projects @code{B} and @code{D} could not be main
13458 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13459 each have a @code{limited with} that is the only one in a cycle of importing
13460 projects.
13461
13462 @c *********************
13463 @c * Project Extension *
13464 @c *********************
13465
13466 @node Project Extension
13467 @section Project Extension
13468
13469 @noindent
13470 During development of a large system, it is sometimes necessary to use
13471 modified versions of some of the source files, without changing the original
13472 sources. This can be achieved through the @emph{project extension} facility.
13473
13474 @smallexample @c projectfile
13475    project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13476 @end smallexample
13477
13478 @noindent
13479 A project extension declaration introduces an extending project
13480 (the @emph{child}) and a project being extended (the @emph{parent}).
13481
13482 By default, a child project inherits all the sources of its parent.
13483 However, inherited sources can be overridden: a unit in a parent is hidden
13484 by a unit of the same name in the child.
13485
13486 Inherited sources are considered to be sources (but not immediate sources)
13487 of the child project; see @ref{Project File Syntax}.
13488
13489 An inherited source file retains any switches specified in the parent project.
13490
13491 For example if the project @code{Utilities} contains the spec and the
13492 body of an Ada package @code{Util_IO}, then the project
13493 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13494 The original body of @code{Util_IO} will not be considered in program builds.
13495 However, the package spec will still be found in the project
13496 @code{Utilities}.
13497
13498 A child project can have only one parent, except when it is qualified as
13499 abstract. But it may import any number of other projects.
13500
13501 A project is not allowed to import directly or indirectly at the same time a
13502 child project and any of its ancestors.
13503
13504 @c *******************************
13505 @c * Project Hierarchy Extension *
13506 @c *******************************
13507
13508 @node Project Hierarchy Extension
13509 @section Project Hierarchy Extension
13510
13511 @noindent
13512 When extending a large system spanning multiple projects, it is often
13513 inconvenient to extend every project in the hierarchy that is impacted by a
13514 small change introduced. In such cases, it is possible to create a virtual
13515 extension of entire hierarchy using @code{extends all} relationship.
13516
13517 When the project is extended using @code{extends all} inheritance, all projects
13518 that are imported by it, both directly and indirectly, are considered virtually
13519 extended. That is, the Project Manager creates "virtual projects"
13520 that extend every project in the hierarchy; all these virtual projects have
13521 no sources of their own and have as object directory the object directory of
13522 the root of "extending all" project.
13523
13524 It is possible to explicitly extend one or more projects in the hierarchy
13525 in order to modify the sources. These extending projects must be imported by
13526 the "extending all" project, which will replace the corresponding virtual
13527 projects with the explicit ones.
13528
13529 When building such a project hierarchy extension, the Project Manager will
13530 ensure that both modified sources and sources in virtual extending projects
13531 that depend on them, are recompiled.
13532
13533 By means of example, consider the following hierarchy of projects.
13534
13535 @enumerate
13536 @item
13537 project A, containing package P1
13538 @item
13539 project B importing A and containing package P2 which depends on P1
13540 @item
13541 project C importing B and containing package P3 which depends on P2
13542 @end enumerate
13543
13544 @noindent
13545 We want to modify packages P1 and P3.
13546
13547 This project hierarchy will need to be extended as follows:
13548
13549 @enumerate
13550 @item
13551 Create project A1 that extends A, placing modified P1 there:
13552
13553 @smallexample @c 0projectfile
13554 project A1 extends "(@dots{})/A" is
13555 end A1;
13556 @end smallexample
13557
13558 @item
13559 Create project C1 that "extends all" C and imports A1, placing modified
13560 P3 there:
13561
13562 @smallexample @c 0projectfile
13563 with "(@dots{})/A1";
13564 project C1 extends all "(@dots{})/C" is
13565 end C1;
13566 @end smallexample
13567 @end enumerate
13568
13569 When you build project C1, your entire modified project space will be
13570 recompiled, including the virtual project B1 that has been impacted by the
13571 "extending all" inheritance of project C.
13572
13573 Note that if a Library Project in the hierarchy is virtually extended,
13574 the virtual project that extends the Library Project is not a Library Project.
13575
13576 @c ****************************************
13577 @c * External References in Project Files *
13578 @c ****************************************
13579
13580 @node  External References in Project Files
13581 @section External References in Project Files
13582
13583 @noindent
13584 A project file may contain references to external variables; such references
13585 are called @emph{external references}.
13586
13587 An external variable is either defined as part of the environment (an
13588 environment variable in Unix, for example) or else specified on the command
13589 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13590 If both, then the command line value is used.
13591
13592 The value of an external reference is obtained by means of the built-in
13593 function @code{external}, which returns a string value.
13594 This function has two forms:
13595 @itemize @bullet
13596 @item @code{external (external_variable_name)}
13597 @item @code{external (external_variable_name, default_value)}
13598 @end itemize
13599
13600 @noindent
13601 Each parameter must be a string literal.  For example:
13602
13603 @smallexample @c projectfile
13604    external ("USER")
13605    external ("OS", "GNU/Linux")
13606 @end smallexample
13607
13608 @noindent
13609 In the form with one parameter, the function returns the value of
13610 the external variable given as parameter. If this name is not present in the
13611 environment, the function returns an empty string.
13612
13613 In the form with two string parameters, the second argument is
13614 the value returned when the variable given as the first argument is not
13615 present in the environment. In the example above, if @code{"OS"} is not
13616 the name of ^an environment variable^a logical name^ and is not passed on
13617 the command line, then the returned value is @code{"GNU/Linux"}.
13618
13619 An external reference may be part of a string expression or of a string
13620 list expression, and can therefore appear in a variable declaration or
13621 an attribute declaration.
13622
13623 @smallexample @c projectfile
13624 @group
13625    type Mode_Type is ("Debug", "Release");
13626    Mode : Mode_Type := external ("MODE");
13627    case Mode is
13628      when "Debug" =>
13629         @dots{}
13630 @end group
13631 @end smallexample
13632
13633 @c *****************************
13634 @c * Packages in Project Files *
13635 @c *****************************
13636
13637 @node  Packages in Project Files
13638 @section Packages in Project Files
13639
13640 @noindent
13641 A @emph{package} defines the settings for project-aware tools within a
13642 project.
13643 For each such tool one can declare a package; the names for these
13644 packages are preset (@pxref{Packages}).
13645 A package may contain variable declarations, attribute declarations, and case
13646 constructions.
13647
13648 @smallexample @c projectfile
13649 @group
13650    project Proj is
13651       package Builder is  -- used by gnatmake
13652          for ^Default_Switches^Default_Switches^ ("Ada")
13653              use ("^-v^-v^",
13654                   "^-g^-g^");
13655       end Builder;
13656    end Proj;
13657 @end group
13658 @end smallexample
13659
13660 @noindent
13661 The syntax of package declarations mimics that of package in Ada.
13662
13663 Most of the packages have an attribute
13664 @code{^Default_Switches^Default_Switches^}.
13665 This attribute is an associative array, and its value is a string list.
13666 The index of the associative array is the name of a programming language (case
13667 insensitive). This attribute indicates the ^switch^switch^
13668 or ^switches^switches^ to be used
13669 with the corresponding tool.
13670
13671 Some packages also have another attribute, @code{^Switches^Switches^},
13672 an associative array whose value is a string list.
13673 The index is the name of a source file.
13674 This attribute indicates the ^switch^switch^
13675 or ^switches^switches^ to be used by the corresponding
13676 tool when dealing with this specific file.
13677
13678 Further information on these ^switch^switch^-related attributes is found in
13679 @ref{^Switches^Switches^ and Project Files}.
13680
13681 A package may be declared as a @emph{renaming} of another package; e.g., from
13682 the project file for an imported project.
13683
13684 @smallexample @c projectfile
13685 @group
13686   with "/global/apex.gpr";
13687   project Example is
13688     package Naming renames Apex.Naming;
13689     @dots{}
13690   end Example;
13691 @end group
13692 @end smallexample
13693
13694 @noindent
13695 Packages that are renamed in other project files often come from project files
13696 that have no sources: they are just used as templates. Any modification in the
13697 template will be reflected automatically in all the project files that rename
13698 a package from the template.
13699
13700 In addition to the tool-oriented packages, you can also declare a package
13701 named @code{Naming} to establish specialized source file naming conventions
13702 (@pxref{Naming Schemes}).
13703
13704 @c ************************************
13705 @c * Variables from Imported Projects *
13706 @c ************************************
13707
13708 @node Variables from Imported Projects
13709 @section Variables from Imported Projects
13710
13711 @noindent
13712 An attribute or variable defined in an imported or parent project can
13713 be used in expressions in the importing / extending project.
13714 Such an attribute or variable is denoted by an expanded name whose prefix
13715 is either the name of the project or the expanded name of a package within
13716 a project.
13717
13718 @smallexample @c projectfile
13719 @group
13720   with "imported";
13721   project Main extends "base" is
13722      Var1 := Imported.Var;
13723      Var2 := Base.Var & ".new";
13724 @end group
13725
13726 @group
13727      package Builder is
13728         for ^Default_Switches^Default_Switches^ ("Ada")
13729             use Imported.Builder'Ada_^Switches^Switches^ &
13730                 "^-gnatg^-gnatg^" &
13731                 "^-v^-v^";
13732      end Builder;
13733 @end group
13734
13735 @group
13736      package Compiler is
13737         for ^Default_Switches^Default_Switches^ ("Ada")
13738             use Base.Compiler'Ada_^Switches^Switches^;
13739      end Compiler;
13740   end Main;
13741 @end group
13742 @end smallexample
13743
13744 @noindent
13745 In this example:
13746
13747 @itemize @bullet
13748 @item
13749 The value of @code{Var1} is a copy of the variable @code{Var} defined
13750 in the project file @file{"imported.gpr"}
13751 @item
13752 the value of @code{Var2} is a copy of the value of variable @code{Var}
13753 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13754 @item
13755 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13756 @code{Builder} is a string list that includes in its value a copy of the value
13757 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13758 in project file @file{imported.gpr} plus two new elements:
13759 @option{"^-gnatg^-gnatg^"}
13760 and @option{"^-v^-v^"};
13761 @item
13762 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13763 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13764 defined in the @code{Compiler} package in project file @file{base.gpr},
13765 the project being extended.
13766 @end itemize
13767
13768 @c ******************
13769 @c * Naming Schemes *
13770 @c ******************
13771
13772 @node  Naming Schemes
13773 @section Naming Schemes
13774
13775 @noindent
13776 Sometimes an Ada software system is ported from a foreign compilation
13777 environment to GNAT, and the file names do not use the default GNAT
13778 conventions. Instead of changing all the file names (which for a variety
13779 of reasons might not be possible), you can define the relevant file
13780 naming scheme in the @code{Naming} package in your project file.
13781
13782 @noindent
13783 Note that the use of pragmas described in
13784 @ref{Alternative File Naming Schemes} by mean of a configuration
13785 pragmas file is not supported when using project files. You must use
13786 the features described in this paragraph. You can however use specify
13787 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13788
13789 @ifclear vms
13790 For example, the following
13791 package models the Apex file naming rules:
13792
13793 @smallexample @c projectfile
13794 @group
13795   package Naming is
13796     for Casing               use "lowercase";
13797     for Dot_Replacement      use ".";
13798     for Spec_Suffix ("Ada")  use ".1.ada";
13799     for Body_Suffix ("Ada")  use ".2.ada";
13800   end Naming;
13801 @end group
13802 @end smallexample
13803 @end ifclear
13804
13805 @ifset vms
13806 For example, the following package models the HP Ada file naming rules:
13807
13808 @smallexample @c projectfile
13809 @group
13810   package Naming is
13811     for Casing               use "lowercase";
13812     for Dot_Replacement      use "__";
13813     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
13814     for Body_Suffix ("Ada")  use ".^ada^ada^";
13815   end Naming;
13816 @end group
13817 @end smallexample
13818
13819 @noindent
13820 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13821 names in lower case)
13822 @end ifset
13823
13824 @noindent
13825 You can define the following attributes in package @code{Naming}:
13826
13827 @table @code
13828
13829 @item @code{Casing}
13830 This must be a string with one of the three values @code{"lowercase"},
13831 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13832
13833 @noindent
13834 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13835
13836 @item @code{Dot_Replacement}
13837 This must be a string whose value satisfies the following conditions:
13838
13839 @itemize @bullet
13840 @item It must not be empty
13841 @item It cannot start or end with an alphanumeric character
13842 @item It cannot be a single underscore
13843 @item It cannot start with an underscore followed by an alphanumeric
13844 @item It cannot contain a dot @code{'.'} except if the entire string
13845 is @code{"."}
13846 @end itemize
13847
13848 @noindent
13849 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13850
13851 @item @code{Spec_Suffix}
13852 This is an associative array (indexed by the programming language name, case
13853 insensitive) whose value is a string that must satisfy the following
13854 conditions:
13855
13856 @itemize @bullet
13857 @item It must not be empty
13858 @item It must include at least one dot
13859 @end itemize
13860 @noindent
13861 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13862 @code{"^.ads^.ADS^"}.
13863
13864 @item @code{Body_Suffix}
13865 This is an associative array (indexed by the programming language name, case
13866 insensitive) whose value is a string that must satisfy the following
13867 conditions:
13868
13869 @itemize @bullet
13870 @item It must not be empty
13871 @item It must include at least one dot
13872 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13873 @end itemize
13874 @noindent
13875 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13876 same string, then a file name that ends with the longest of these two suffixes
13877 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13878 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13879
13880 If the suffix does not start with a '.', a file with a name exactly equal
13881 to the suffix will also be part of the project (for instance if you define
13882 the suffix as @code{Makefile}, a file called @file{Makefile} will be part
13883 of the project. This is not interesting in general when using projects to
13884 compile. However, it might become useful when a project is also used to
13885 find the list of source files in an editor, like the GNAT Programming System
13886 (GPS).
13887
13888 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13889 @code{"^.adb^.ADB^"}.
13890
13891 @item @code{Separate_Suffix}
13892 This must be a string whose value satisfies the same conditions as
13893 @code{Body_Suffix}. The same "longest suffix" rules apply.
13894
13895 @noindent
13896 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13897 value as @code{Body_Suffix ("Ada")}.
13898
13899 @item @code{Spec}
13900 @noindent
13901 You can use the associative array attribute @code{Spec}  to define
13902 the source file name for an individual Ada compilation unit's spec. The array
13903 index must be a string literal that identifies the Ada unit (case insensitive).
13904 The value of this attribute must be a string that identifies the file that
13905 contains this unit's spec (case sensitive or insensitive depending on the
13906 operating system).
13907
13908 @smallexample @c projectfile
13909    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13910 @end smallexample
13911
13912 When the source file contains several units, you can indicate at what
13913 position the unit occurs in the file, with the following. The first unit
13914 in the file has index 1
13915
13916 @smallexample @c projectfile
13917   for Body ("top") use "foo.a" at 1;
13918   for Body ("foo") use "foo.a" at 2;
13919 @end smallexample
13920
13921 @item @code{Body}
13922
13923 You can use the associative array attribute @code{Body} to
13924 define the source file name for an individual Ada compilation unit's body
13925 (possibly a subunit).  The array index must be a string literal that identifies
13926 the Ada unit (case insensitive).  The value of this attribute must be a string
13927 that identifies the file that contains this unit's body or subunit (case
13928 sensitive or insensitive depending on the operating system).
13929
13930 @smallexample @c projectfile
13931    for Body ("MyPack.MyChild") use "mypack.mychild.body";
13932 @end smallexample
13933 @end table
13934
13935 @c ********************
13936 @c * Library Projects *
13937 @c ********************
13938
13939 @node Library Projects
13940 @section Library Projects
13941
13942 @noindent
13943 @emph{Library projects} are projects whose object code is placed in a library.
13944 (Note that this facility is not yet supported on all platforms).
13945
13946 @code{gnatmake} or @code{gprbuild} will collect all object files into a
13947 single archive, which might either be a shared or a static library. This
13948 library can later on be linked with multiple executables, potentially
13949 reducing their sizes.
13950
13951 If your project file specifies languages other than Ada, but you are still
13952 using @code{gnatmake} to compile and link, the latter will not try to
13953 compile your sources other than Ada (you should use @code{gprbuild} if that
13954 is your intent). However, @code{gnatmake} will automatically link all object
13955 files found in the object directory, whether or not they were compiled from
13956 an Ada source file. This specific behavior only applies when multiple
13957 languages are specified.
13958
13959 To create a library project, you need to define in its project file
13960 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
13961 Additionally, you may define other library-related attributes such as
13962 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
13963 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
13964
13965 The @code{Library_Name} attribute has a string value. There is no restriction
13966 on the name of a library. It is the responsibility of the developer to
13967 choose a name that will be accepted by the platform. It is recommended to
13968 choose names that could be Ada identifiers; such names are almost guaranteed
13969 to be acceptable on all platforms.
13970
13971 The @code{Library_Dir} attribute has a string value that designates the path
13972 (absolute or relative) of the directory where the library will reside.
13973 It must designate an existing directory, and this directory must be writable,
13974 different from the project's object directory and from any source directory
13975 in the project tree.
13976
13977 If both @code{Library_Name} and @code{Library_Dir} are specified and
13978 are legal, then the project file defines a library project.  The optional
13979 library-related attributes are checked only for such project files.
13980
13981 The @code{Library_Kind} attribute has a string value that must be one of the
13982 following (case insensitive): @code{"static"}, @code{"dynamic"} or
13983 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
13984 attribute is not specified, the library is a static library, that is
13985 an archive of object files that can be potentially linked into a
13986 static executable. Otherwise, the library may be dynamic or
13987 relocatable, that is a library that is loaded only at the start of execution.
13988
13989 If you need to build both a static and a dynamic library, you should use two
13990 different object directories, since in some cases some extra code needs to
13991 be generated for the latter. For such cases, it is recommended to either use
13992 two different project files, or a single one which uses external variables
13993 to indicate what kind of library should be build.
13994
13995 The @code{Library_ALI_Dir} attribute may be specified to indicate the
13996 directory where the ALI files of the library will be copied. When it is
13997 not specified, the ALI files are copied to the directory specified in
13998 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
13999 must be writable and different from the project's object directory and from
14000 any source directory in the project tree.
14001
14002 The @code{Library_Version} attribute has a string value whose interpretation
14003 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
14004 used only for dynamic/relocatable libraries as the internal name of the
14005 library (the @code{"soname"}). If the library file name (built from the
14006 @code{Library_Name}) is different from the @code{Library_Version}, then the
14007 library file will be a symbolic link to the actual file whose name will be
14008 @code{Library_Version}.
14009
14010 Example (on Unix):
14011
14012 @smallexample @c projectfile
14013 @group
14014 project Plib is
14015
14016    Version := "1";
14017
14018    for Library_Dir use "lib_dir";
14019    for Library_Name use "dummy";
14020    for Library_Kind use "relocatable";
14021    for Library_Version use "libdummy.so." & Version;
14022
14023 end Plib;
14024 @end group
14025 @end smallexample
14026
14027 @noindent
14028 Directory @file{lib_dir} will contain the internal library file whose name
14029 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
14030 @file{libdummy.so.1}.
14031
14032 When @command{gnatmake} detects that a project file
14033 is a library project file, it will check all immediate sources of the project
14034 and rebuild the library if any of the sources have been recompiled.
14035
14036 Standard project files can import library project files. In such cases,
14037 the libraries will only be rebuilt if some of its sources are recompiled
14038 because they are in the closure of some other source in an importing project.
14039 Sources of the library project files that are not in such a closure will
14040 not be checked, unless the full library is checked, because one of its sources
14041 needs to be recompiled.
14042
14043 For instance, assume the project file @code{A} imports the library project file
14044 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
14045 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
14046 @file{l2.ads}, @file{l2.adb}.
14047
14048 If @file{l1.adb} has been modified, then the library associated with @code{L}
14049 will be rebuilt when compiling all the immediate sources of @code{A} only
14050 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
14051 @code{"with L1;"}.
14052
14053 To be sure that all the sources in the library associated with @code{L} are
14054 up to date, and that all the sources of project @code{A} are also up to date,
14055 the following two commands needs to be used:
14056
14057 @smallexample
14058 gnatmake -Pl.gpr
14059 gnatmake -Pa.gpr
14060 @end smallexample
14061
14062 When a library is built or rebuilt, an attempt is made first to delete all
14063 files in the library directory.
14064 All @file{ALI} files will also be copied from the object directory to the
14065 library directory. To build executables, @command{gnatmake} will use the
14066 library rather than the individual object files.
14067
14068 @ifclear vms
14069 It is also possible to create library project files for third-party libraries
14070 that are precompiled and cannot be compiled locally thanks to the
14071 @code{externally_built} attribute. (See @ref{Installing a library}).
14072 @end ifclear
14073
14074 @c *******************************
14075 @c * Stand-alone Library Projects *
14076 @c *******************************
14077
14078 @node Stand-alone Library Projects
14079 @section Stand-alone Library Projects
14080
14081 @noindent
14082 A Stand-alone Library is a library that contains the necessary code to
14083 elaborate the Ada units that are included in the library. A Stand-alone
14084 Library is suitable to be used in an executable when the main is not
14085 in Ada. However, Stand-alone Libraries may also be used with an Ada main
14086 subprogram.
14087
14088 A Stand-alone Library Project is a Library Project where the library is
14089 a Stand-alone Library.
14090
14091 To be a Stand-alone Library Project, in addition to the two attributes
14092 that make a project a Library Project (@code{Library_Name} and
14093 @code{Library_Dir}, see @ref{Library Projects}), the attribute
14094 @code{Library_Interface} must be defined.
14095
14096 @smallexample @c projectfile
14097 @group
14098    for Library_Dir use "lib_dir";
14099    for Library_Name use "dummy";
14100    for Library_Interface use ("int1", "int1.child");
14101 @end group
14102 @end smallexample
14103
14104 Attribute @code{Library_Interface} has a nonempty string list value,
14105 each string in the list designating a unit contained in an immediate source
14106 of the project file.
14107
14108 When a Stand-alone Library is built, first the binder is invoked to build
14109 a package whose name depends on the library name
14110 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
14111 This binder-generated package includes initialization and
14112 finalization procedures whose
14113 names depend on the library name (dummyinit and dummyfinal in the example
14114 above). The object corresponding to this package is included in the library.
14115
14116 A dynamic or relocatable Stand-alone Library is automatically initialized
14117 if automatic initialization of Stand-alone Libraries is supported on the
14118 platform and if attribute @code{Library_Auto_Init} is not specified or
14119 is specified with the value "true". A static Stand-alone Library is never
14120 automatically initialized.
14121
14122 Single string attribute @code{Library_Auto_Init} may be specified with only
14123 two possible values: "false" or "true" (case-insensitive). Specifying
14124 "false" for attribute @code{Library_Auto_Init} will prevent automatic
14125 initialization of dynamic or relocatable libraries.
14126
14127 When a non-automatically initialized Stand-alone Library is used
14128 in an executable, its initialization procedure must be called before
14129 any service of the library is used.
14130 When the main subprogram is in Ada, it may mean that the initialization
14131 procedure has to be called during elaboration of another package.
14132
14133 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
14134 (those that are listed in attribute @code{Library_Interface}) are copied to
14135 the Library Directory. As a consequence, only the Interface Units may be
14136 imported from Ada units outside of the library. If other units are imported,
14137 the binding phase will fail.
14138
14139 When a Stand-Alone Library is bound, the switches that are specified in
14140 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
14141 used in the call to @command{gnatbind}.
14142
14143 The string list attribute @code{Library_Options} may be used to specified
14144 additional switches to the call to @command{gcc} to link the library.
14145
14146 The attribute @code{Library_Src_Dir}, may be specified for a
14147 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
14148 single string value. Its value must be the path (absolute or relative to the
14149 project directory) of an existing directory. This directory cannot be the
14150 object directory or one of the source directories, but it can be the same as
14151 the library directory. The sources of the Interface
14152 Units of the library, necessary to an Ada client of the library, will be
14153 copied to the designated directory, called Interface Copy directory.
14154 These sources includes the specs of the Interface Units, but they may also
14155 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
14156 are used, or when there is a generic units in the spec. Before the sources
14157 are copied to the Interface Copy directory, an attempt is made to delete all
14158 files in the Interface Copy directory.
14159
14160 @c *************************************
14161 @c * Switches Related to Project Files *
14162 @c *************************************
14163 @node Switches Related to Project Files
14164 @section Switches Related to Project Files
14165
14166 @noindent
14167 The following switches are used by GNAT tools that support project files:
14168
14169 @table @option
14170
14171 @item ^-P^/PROJECT_FILE=^@var{project}
14172 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
14173 Indicates the name of a project file. This project file will be parsed with
14174 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
14175 if any, and using the external references indicated
14176 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
14177 @ifclear vms
14178 There may zero, one or more spaces between @option{-P} and @var{project}.
14179 @end ifclear
14180
14181 @noindent
14182 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
14183
14184 @noindent
14185 Since the Project Manager parses the project file only after all the switches
14186 on the command line are checked, the order of the switches
14187 @option{^-P^/PROJECT_FILE^},
14188 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
14189 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
14190
14191 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
14192 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
14193 Indicates that external variable @var{name} has the value @var{value}.
14194 The Project Manager will use this value for occurrences of
14195 @code{external(name)} when parsing the project file.
14196
14197 @ifclear vms
14198 @noindent
14199 If @var{name} or @var{value} includes a space, then @var{name=value} should be
14200 put between quotes.
14201 @smallexample
14202   -XOS=NT
14203   -X"user=John Doe"
14204 @end smallexample
14205 @end ifclear
14206
14207 @noindent
14208 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
14209 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
14210 @var{name}, only the last one is used.
14211
14212 @noindent
14213 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
14214 takes precedence over the value of the same name in the environment.
14215
14216 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
14217 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
14218 Indicates the verbosity of the parsing of GNAT project files.
14219
14220 @ifclear vms
14221 @option{-vP0} means Default;
14222 @option{-vP1} means Medium;
14223 @option{-vP2} means High.
14224 @end ifclear
14225
14226 @ifset vms
14227 There are three possible options for this qualifier: DEFAULT, MEDIUM and
14228 HIGH.
14229 @end ifset
14230
14231 @noindent
14232 The default is ^Default^DEFAULT^: no output for syntactically correct
14233 project files.
14234 @noindent
14235 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
14236 only the last one is used.
14237
14238 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
14239 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
14240 Add directory <dir> at the beginning of the project search path, in order,
14241 after the current working directory.
14242
14243 @ifclear vms
14244 @item -eL
14245 @cindex @option{-eL} (any project-aware tool)
14246 Follow all symbolic links when processing project files.
14247 @end ifclear
14248
14249 @item ^--subdirs^/SUBDIRS^=<subdir>
14250 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
14251 This switch is recognized by gnatmake and gnatclean. It indicate that the real
14252 directories (except the source directories) are the subdirectories <subdir>
14253 of the directories specified in the project files. This applies in particular
14254 to object directories, library directories and exec directories. If the
14255 subdirectories do not exist, they are created automatically.
14256
14257 @end table
14258
14259 @c **********************************
14260 @c * Tools Supporting Project Files *
14261 @c **********************************
14262
14263 @node  Tools Supporting Project Files
14264 @section Tools Supporting Project Files
14265
14266 @menu
14267 * gnatmake and Project Files::
14268 * The GNAT Driver and Project Files::
14269 @end menu
14270
14271 @node gnatmake and Project Files
14272 @subsection gnatmake and Project Files
14273
14274 @noindent
14275 This section covers several topics related to @command{gnatmake} and
14276 project files: defining ^switches^switches^ for @command{gnatmake}
14277 and for the tools that it invokes; specifying configuration pragmas;
14278 the use of the @code{Main} attribute; building and rebuilding library project
14279 files.
14280
14281 @menu
14282 * ^Switches^Switches^ and Project Files::
14283 * Specifying Configuration Pragmas::
14284 * Project Files and Main Subprograms::
14285 * Library Project Files::
14286 @end menu
14287
14288 @node ^Switches^Switches^ and Project Files
14289 @subsubsection ^Switches^Switches^ and Project Files
14290
14291 @ifset vms
14292 It is not currently possible to specify VMS style qualifiers in the project
14293 files; only Unix style ^switches^switches^ may be specified.
14294 @end ifset
14295
14296 @noindent
14297 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14298 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14299 attribute, a @code{^Switches^Switches^} attribute, or both;
14300 as their names imply, these ^switch^switch^-related
14301 attributes affect the ^switches^switches^ that are used for each of these GNAT
14302 components when
14303 @command{gnatmake} is invoked.  As will be explained below, these
14304 component-specific ^switches^switches^ precede
14305 the ^switches^switches^ provided on the @command{gnatmake} command line.
14306
14307 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14308 array indexed by language name (case insensitive) whose value is a string list.
14309 For example:
14310
14311 @smallexample @c projectfile
14312 @group
14313 package Compiler is
14314   for ^Default_Switches^Default_Switches^ ("Ada")
14315       use ("^-gnaty^-gnaty^",
14316            "^-v^-v^");
14317 end Compiler;
14318 @end group
14319 @end smallexample
14320
14321 @noindent
14322 The @code{^Switches^Switches^} attribute is also an associative array,
14323 indexed by a file name (which may or may not be case sensitive, depending
14324 on the operating system) whose value is a string list.  For example:
14325
14326 @smallexample @c projectfile
14327 @group
14328 package Builder is
14329    for ^Switches^Switches^ ("main1.adb")
14330        use ("^-O2^-O2^");
14331    for ^Switches^Switches^ ("main2.adb")
14332        use ("^-g^-g^");
14333 end Builder;
14334 @end group
14335 @end smallexample
14336
14337 @noindent
14338 For the @code{Builder} package, the file names must designate source files
14339 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
14340 file names must designate @file{ALI} or source files for main subprograms.
14341 In each case just the file name without an explicit extension is acceptable.
14342
14343 For each tool used in a program build (@command{gnatmake}, the compiler, the
14344 binder, and the linker), the corresponding package @dfn{contributes} a set of
14345 ^switches^switches^ for each file on which the tool is invoked, based on the
14346 ^switch^switch^-related attributes defined in the package.
14347 In particular, the ^switches^switches^
14348 that each of these packages contributes for a given file @var{f} comprise:
14349
14350 @itemize @bullet
14351 @item
14352 the value of attribute @code{^Switches^Switches^ (@var{f})},
14353 if it is specified in the package for the given file,
14354 @item
14355 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14356 if it is specified in the package.
14357 @end itemize
14358
14359 @noindent
14360 If neither of these attributes is defined in the package, then the package does
14361 not contribute any ^switches^switches^ for the given file.
14362
14363 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14364 two sets, in the following order: those contributed for the file
14365 by the @code{Builder} package;
14366 and the switches passed on the command line.
14367
14368 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14369 the ^switches^switches^ passed to the tool comprise three sets,
14370 in the following order:
14371
14372 @enumerate
14373 @item
14374 the applicable ^switches^switches^ contributed for the file
14375 by the @code{Builder} package in the project file supplied on the command line;
14376
14377 @item
14378 those contributed for the file by the package (in the relevant project file --
14379 see below) corresponding to the tool; and
14380
14381 @item
14382 the applicable switches passed on the command line.
14383 @end enumerate
14384
14385 @noindent
14386 The term @emph{applicable ^switches^switches^} reflects the fact that
14387 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14388 tools, depending on the individual ^switch^switch^.
14389
14390 @command{gnatmake} may invoke the compiler on source files from different
14391 projects. The Project Manager will use the appropriate project file to
14392 determine the @code{Compiler} package for each source file being compiled.
14393 Likewise for the @code{Binder} and @code{Linker} packages.
14394
14395 As an example, consider the following package in a project file:
14396
14397 @smallexample @c projectfile
14398 @group
14399 project Proj1 is
14400    package Compiler is
14401       for ^Default_Switches^Default_Switches^ ("Ada")
14402           use ("^-g^-g^");
14403       for ^Switches^Switches^ ("a.adb")
14404           use ("^-O1^-O1^");
14405       for ^Switches^Switches^ ("b.adb")
14406           use ("^-O2^-O2^",
14407                "^-gnaty^-gnaty^");
14408    end Compiler;
14409 end Proj1;
14410 @end group
14411 @end smallexample
14412
14413 @noindent
14414 If @command{gnatmake} is invoked with this project file, and it needs to
14415 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14416 @file{a.adb} will be compiled with the ^switch^switch^
14417 @option{^-O1^-O1^},
14418 @file{b.adb} with ^switches^switches^
14419 @option{^-O2^-O2^}
14420 and @option{^-gnaty^-gnaty^},
14421 and @file{c.adb} with @option{^-g^-g^}.
14422
14423 The following example illustrates the ordering of the ^switches^switches^
14424 contributed by different packages:
14425
14426 @smallexample @c projectfile
14427 @group
14428 project Proj2 is
14429    package Builder is
14430       for ^Switches^Switches^ ("main.adb")
14431           use ("^-g^-g^",
14432                "^-O1^-)1^",
14433                "^-f^-f^");
14434    end Builder;
14435 @end group
14436
14437 @group
14438    package Compiler is
14439       for ^Switches^Switches^ ("main.adb")
14440           use ("^-O2^-O2^");
14441    end Compiler;
14442 end Proj2;
14443 @end group
14444 @end smallexample
14445
14446 @noindent
14447 If you issue the command:
14448
14449 @smallexample
14450     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14451 @end smallexample
14452
14453 @noindent
14454 then the compiler will be invoked on @file{main.adb} with the following
14455 sequence of ^switches^switches^
14456
14457 @smallexample
14458    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14459 @end smallexample
14460
14461 with the last @option{^-O^-O^}
14462 ^switch^switch^ having precedence over the earlier ones;
14463 several other ^switches^switches^
14464 (such as @option{^-c^-c^}) are added implicitly.
14465
14466 The ^switches^switches^
14467 @option{^-g^-g^}
14468 and @option{^-O1^-O1^} are contributed by package
14469 @code{Builder},  @option{^-O2^-O2^} is contributed
14470 by the package @code{Compiler}
14471 and @option{^-O0^-O0^} comes from the command line.
14472
14473 The @option{^-g^-g^}
14474 ^switch^switch^ will also be passed in the invocation of
14475 @command{Gnatlink.}
14476
14477 A final example illustrates switch contributions from packages in different
14478 project files:
14479
14480 @smallexample @c projectfile
14481 @group
14482 project Proj3 is
14483    for Source_Files use ("pack.ads", "pack.adb");
14484    package Compiler is
14485       for ^Default_Switches^Default_Switches^ ("Ada")
14486           use ("^-gnata^-gnata^");
14487    end Compiler;
14488 end Proj3;
14489 @end group
14490
14491 @group
14492 with "Proj3";
14493 project Proj4 is
14494    for Source_Files use ("foo_main.adb", "bar_main.adb");
14495    package Builder is
14496       for ^Switches^Switches^ ("foo_main.adb")
14497           use ("^-s^-s^",
14498                "^-g^-g^");
14499    end Builder;
14500 end Proj4;
14501 @end group
14502
14503 @group
14504 -- Ada source file:
14505 with Pack;
14506 procedure Foo_Main is
14507    @dots{}
14508 end Foo_Main;
14509 @end group
14510 @end smallexample
14511
14512 If the command is
14513 @smallexample
14514 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14515 @end smallexample
14516
14517 @noindent
14518 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14519 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14520 @option{^-gnato^-gnato^} (passed on the command line).
14521 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14522 are @option{^-g^-g^} from @code{Proj4.Builder},
14523 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14524 and @option{^-gnato^-gnato^} from the command line.
14525
14526 @noindent
14527 When using @command{gnatmake} with project files, some ^switches^switches^ or
14528 arguments may be expressed as relative paths. As the working directory where
14529 compilation occurs may change, these relative paths are converted to absolute
14530 paths. For the ^switches^switches^ found in a project file, the relative paths
14531 are relative to the project file directory, for the switches on the command
14532 line, they are relative to the directory where @command{gnatmake} is invoked.
14533 The ^switches^switches^ for which this occurs are:
14534 ^-I^-I^,
14535 ^-A^-A^,
14536 ^-L^-L^,
14537 ^-aO^-aO^,
14538 ^-aL^-aL^,
14539 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14540 ^switch^switch^
14541 ^-o^-o^, object files specified in package @code{Linker} or after
14542 -largs on the command line). The exception to this rule is the ^switch^switch^
14543 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14544
14545 @node Specifying Configuration Pragmas
14546 @subsubsection Specifying Configuration Pragmas
14547
14548 When using @command{gnatmake} with project files, if there exists a file
14549 @file{gnat.adc} that contains configuration pragmas, this file will be
14550 ignored.
14551
14552 Configuration pragmas can be defined by means of the following attributes in
14553 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14554 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14555
14556 Both these attributes are single string attributes. Their values is the path
14557 name of a file containing configuration pragmas. If a path name is relative,
14558 then it is relative to the project directory of the project file where the
14559 attribute is defined.
14560
14561 When compiling a source, the configuration pragmas used are, in order,
14562 those listed in the file designated by attribute
14563 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14564 project file, if it is specified, and those listed in the file designated by
14565 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14566 the project file of the source, if it exists.
14567
14568 @node Project Files and Main Subprograms
14569 @subsubsection Project Files and Main Subprograms
14570
14571 @noindent
14572 When using a project file, you can invoke @command{gnatmake}
14573 with one or several main subprograms, by specifying their source files on the
14574 command line.
14575
14576 @smallexample
14577     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14578 @end smallexample
14579
14580 @noindent
14581 Each of these needs to be a source file of the same project, except
14582 when the switch ^-u^/UNIQUE^ is used.
14583
14584 @noindent
14585 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14586 same project, one of the project in the tree rooted at the project specified
14587 on the command line. The package @code{Builder} of this common project, the
14588 "main project" is the one that is considered by @command{gnatmake}.
14589
14590 @noindent
14591 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14592 imported directly or indirectly by the project specified on the command line.
14593 Note that if such a source file is not part of the project specified on the
14594 command line, the ^switches^switches^ found in package @code{Builder} of the
14595 project specified on the command line, if any, that are transmitted
14596 to the compiler will still be used, not those found in the project file of
14597 the source file.
14598
14599 @noindent
14600 When using a project file, you can also invoke @command{gnatmake} without
14601 explicitly specifying any main, and the effect depends on whether you have
14602 defined the @code{Main} attribute.  This attribute has a string list value,
14603 where each element in the list is the name of a source file (the file
14604 extension is optional) that contains a unit that can be a main subprogram.
14605
14606 If the @code{Main} attribute is defined in a project file as a non-empty
14607 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14608 line, then invoking @command{gnatmake} with this project file but without any
14609 main on the command line is equivalent to invoking @command{gnatmake} with all
14610 the file names in the @code{Main} attribute on the command line.
14611
14612 Example:
14613 @smallexample @c projectfile
14614 @group
14615    project Prj is
14616       for Main use ("main1", "main2", "main3");
14617    end Prj;
14618 @end group
14619 @end smallexample
14620
14621 @noindent
14622 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14623 is equivalent to
14624 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14625
14626 When the project attribute @code{Main} is not specified, or is specified
14627 as an empty string list, or when the switch @option{-u} is used on the command
14628 line, then invoking @command{gnatmake} with no main on the command line will
14629 result in all immediate sources of the project file being checked, and
14630 potentially recompiled. Depending on the presence of the switch @option{-u},
14631 sources from other project files on which the immediate sources of the main
14632 project file depend are also checked and potentially recompiled. In other
14633 words, the @option{-u} switch is applied to all of the immediate sources of the
14634 main project file.
14635
14636 When no main is specified on the command line and attribute @code{Main} exists
14637 and includes several mains, or when several mains are specified on the
14638 command line, the default ^switches^switches^ in package @code{Builder} will
14639 be used for all mains, even if there are specific ^switches^switches^
14640 specified for one or several mains.
14641
14642 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14643 the specific ^switches^switches^ for each main, if they are specified.
14644
14645 @node Library Project Files
14646 @subsubsection Library Project Files
14647
14648 @noindent
14649 When @command{gnatmake} is invoked with a main project file that is a library
14650 project file, it is not allowed to specify one or more mains on the command
14651 line.
14652
14653 @noindent
14654 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14655 ^-l^/ACTION=LINK^ have special meanings.
14656
14657 @itemize @bullet
14658 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14659 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14660 library.
14661
14662 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14663 to @command{gnatmake} that the binder generated file should be compiled
14664 (in the case of a stand-alone library) and that the library should be built.
14665
14666 @end itemize
14667
14668 @node The GNAT Driver and Project Files
14669 @subsection The GNAT Driver and Project Files
14670
14671 @noindent
14672 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14673 can benefit from project files:
14674 @command{^gnatbind^gnatbind^},
14675 @command{^gnatcheck^gnatcheck^}),
14676 @command{^gnatclean^gnatclean^}),
14677 @command{^gnatelim^gnatelim^},
14678 @command{^gnatfind^gnatfind^},
14679 @command{^gnatlink^gnatlink^},
14680 @command{^gnatls^gnatls^},
14681 @command{^gnatmetric^gnatmetric^},
14682 @command{^gnatpp^gnatpp^},
14683 @command{^gnatstub^gnatstub^},
14684 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
14685 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14686 They must be invoked through the @command{gnat} driver.
14687
14688 The @command{gnat} driver is a wrapper that accepts a number of commands and
14689 calls the corresponding tool. It was designed initially for VMS platforms (to
14690 convert VMS qualifiers to Unix-style switches), but it is now available on all
14691 GNAT platforms.
14692
14693 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14694 (case insensitive):
14695
14696 @itemize @bullet
14697 @item
14698 BIND to invoke @command{^gnatbind^gnatbind^}
14699 @item
14700 CHOP to invoke @command{^gnatchop^gnatchop^}
14701 @item
14702 CLEAN to invoke @command{^gnatclean^gnatclean^}
14703 @item
14704 COMP or COMPILE to invoke the compiler
14705 @item
14706 ELIM to invoke @command{^gnatelim^gnatelim^}
14707 @item
14708 FIND to invoke @command{^gnatfind^gnatfind^}
14709 @item
14710 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14711 @item
14712 LINK to invoke @command{^gnatlink^gnatlink^}
14713 @item
14714 LS or LIST to invoke @command{^gnatls^gnatls^}
14715 @item
14716 MAKE to invoke @command{^gnatmake^gnatmake^}
14717 @item
14718 NAME to invoke @command{^gnatname^gnatname^}
14719 @item
14720 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14721 @item
14722 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14723 @item
14724 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14725 @item
14726 STUB to invoke @command{^gnatstub^gnatstub^}
14727 @item
14728 XREF to invoke @command{^gnatxref^gnatxref^}
14729 @end itemize
14730
14731 @noindent
14732 (note that the compiler is invoked using the command
14733 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14734
14735 @noindent
14736 On non-VMS platforms, between @command{gnat} and the command, two
14737 special switches may be used:
14738
14739 @itemize @bullet
14740 @item
14741 @command{-v} to display the invocation of the tool.
14742 @item
14743 @command{-dn} to prevent the @command{gnat} driver from removing
14744 the temporary files it has created. These temporary files are
14745 configuration files and temporary file list files.
14746 @end itemize
14747
14748 @noindent
14749 The command may be followed by switches and arguments for the invoked
14750 tool.
14751
14752 @smallexample
14753   gnat bind -C main.ali
14754   gnat ls -a main
14755   gnat chop foo.txt
14756 @end smallexample
14757
14758 @noindent
14759 Switches may also be put in text files, one switch per line, and the text
14760 files may be specified with their path name preceded by '@@'.
14761
14762 @smallexample
14763    gnat bind @@args.txt main.ali
14764 @end smallexample
14765
14766 @noindent
14767 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14768 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14769 (@option{^-P^/PROJECT_FILE^},
14770 @option{^-X^/EXTERNAL_REFERENCE^} and
14771 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14772 the switches of the invoking tool.
14773
14774 @noindent
14775 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14776 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14777 the immediate sources of the specified project file.
14778
14779 @noindent
14780 When GNAT METRIC is used with a project file, but with no source
14781 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14782 with all the immediate sources of the specified project file and with
14783 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14784 of the project.
14785
14786 @noindent
14787 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14788 a project file, no source is specified on the command line and
14789 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14790 the underlying tool (^gnatpp^gnatpp^ or
14791 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14792 not only for the immediate sources of the main project.
14793 @ifclear vms
14794 (-U stands for Universal or Union of the project files of the project tree)
14795 @end ifclear
14796
14797 @noindent
14798 For each of the following commands, there is optionally a corresponding
14799 package in the main project.
14800
14801 @itemize @bullet
14802 @item
14803 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14804
14805 @item
14806 package @code{Check} for command CHECK (invoking
14807 @code{^gnatcheck^gnatcheck^})
14808
14809 @item
14810 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14811
14812 @item
14813 package @code{Cross_Reference} for command XREF (invoking
14814 @code{^gnatxref^gnatxref^})
14815
14816 @item
14817 package @code{Eliminate} for command ELIM (invoking
14818 @code{^gnatelim^gnatelim^})
14819
14820 @item
14821 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14822
14823 @item
14824 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14825
14826 @item
14827 package @code{Gnatstub} for command STUB
14828 (invoking @code{^gnatstub^gnatstub^})
14829
14830 @item
14831 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14832
14833 @item
14834 package @code{Metrics} for command METRIC
14835 (invoking @code{^gnatmetric^gnatmetric^})
14836
14837 @item
14838 package @code{Pretty_Printer} for command PP or PRETTY
14839 (invoking @code{^gnatpp^gnatpp^})
14840
14841 @end itemize
14842
14843 @noindent
14844 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14845 a simple variable with a string list value. It contains ^switches^switches^
14846 for the invocation of @code{^gnatls^gnatls^}.
14847
14848 @smallexample @c projectfile
14849 @group
14850 project Proj1 is
14851    package gnatls is
14852       for ^Switches^Switches^
14853           use ("^-a^-a^",
14854                "^-v^-v^");
14855    end gnatls;
14856 end Proj1;
14857 @end group
14858 @end smallexample
14859
14860 @noindent
14861 All other packages have two attribute @code{^Switches^Switches^} and
14862 @code{^Default_Switches^Default_Switches^}.
14863
14864 @noindent
14865 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14866 source file name, that has a string list value: the ^switches^switches^ to be
14867 used when the tool corresponding to the package is invoked for the specific
14868 source file.
14869
14870 @noindent
14871 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14872 indexed by  the programming language that has a string list value.
14873 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14874 ^switches^switches^ for the invocation of the tool corresponding
14875 to the package, except if a specific @code{^Switches^Switches^} attribute
14876 is specified for the source file.
14877
14878 @smallexample @c projectfile
14879 @group
14880 project Proj is
14881
14882    for Source_Dirs use ("./**");
14883
14884    package gnatls is
14885       for ^Switches^Switches^ use
14886           ("^-a^-a^",
14887            "^-v^-v^");
14888    end gnatls;
14889 @end group
14890 @group
14891
14892    package Compiler is
14893       for ^Default_Switches^Default_Switches^ ("Ada")
14894           use ("^-gnatv^-gnatv^",
14895                "^-gnatwa^-gnatwa^");
14896    end Binder;
14897 @end group
14898 @group
14899
14900    package Binder is
14901       for ^Default_Switches^Default_Switches^ ("Ada")
14902           use ("^-C^-C^",
14903                "^-e^-e^");
14904    end Binder;
14905 @end group
14906 @group
14907
14908    package Linker is
14909       for ^Default_Switches^Default_Switches^ ("Ada")
14910           use ("^-C^-C^");
14911       for ^Switches^Switches^ ("main.adb")
14912           use ("^-C^-C^",
14913                "^-v^-v^",
14914                "^-v^-v^");
14915    end Linker;
14916 @end group
14917 @group
14918
14919    package Finder is
14920       for ^Default_Switches^Default_Switches^ ("Ada")
14921            use ("^-a^-a^",
14922                 "^-f^-f^");
14923    end Finder;
14924 @end group
14925 @group
14926
14927    package Cross_Reference is
14928       for ^Default_Switches^Default_Switches^ ("Ada")
14929           use ("^-a^-a^",
14930                "^-f^-f^",
14931                "^-d^-d^",
14932                "^-u^-u^");
14933    end Cross_Reference;
14934 end Proj;
14935 @end group
14936 @end smallexample
14937
14938 @noindent
14939 With the above project file, commands such as
14940
14941 @smallexample
14942    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
14943    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
14944    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
14945    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
14946    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
14947 @end smallexample
14948
14949 @noindent
14950 will set up the environment properly and invoke the tool with the switches
14951 found in the package corresponding to the tool:
14952 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
14953 except @code{^Switches^Switches^ ("main.adb")}
14954 for @code{^gnatlink^gnatlink^}.
14955 It is also possible to invoke some of the tools,
14956 @code{^gnatcheck^gnatcheck^}),
14957 @code{^gnatmetric^gnatmetric^}),
14958 and @code{^gnatpp^gnatpp^})
14959 on a set of project units thanks to the combination of the switches
14960 @option{-P}, @option{-U} and possibly the main unit when one is interested
14961 in its closure. For instance,
14962 @smallexample
14963 gnat metric -Pproj
14964 @end smallexample
14965 will compute the metrics for all the immediate units of project
14966 @code{proj}.
14967 @smallexample
14968 gnat metric -Pproj -U
14969 @end smallexample
14970 will compute the metrics for all the units of the closure of projects
14971 rooted at @code{proj}.
14972 @smallexample
14973 gnat metric -Pproj -U main_unit
14974 @end smallexample
14975 will compute the metrics for the closure of units rooted at
14976 @code{main_unit}. This last possibility relies implicitly
14977 on @command{gnatbind}'s option @option{-R}.
14978
14979 @c **********************
14980 @node An Extended Example
14981 @section An Extended Example
14982
14983 @noindent
14984 Suppose that we have two programs, @var{prog1} and @var{prog2},
14985 whose sources are in corresponding directories. We would like
14986 to build them with a single @command{gnatmake} command, and we want to place
14987 their object files into @file{build} subdirectories of the source directories.
14988 Furthermore, we want to have to have two separate subdirectories
14989 in @file{build}  -- @file{release} and @file{debug} -- which will contain
14990 the object files compiled with different set of compilation flags.
14991
14992 In other words, we have the following structure:
14993
14994 @smallexample
14995 @group
14996    main
14997      |- prog1
14998      |    |- build
14999      |         | debug
15000      |         | release
15001      |- prog2
15002           |- build
15003                | debug
15004                | release
15005 @end group
15006 @end smallexample
15007
15008 @noindent
15009 Here are the project files that we must place in a directory @file{main}
15010 to maintain this structure:
15011
15012 @enumerate
15013
15014 @item We create a @code{Common} project with a package @code{Compiler} that
15015 specifies the compilation ^switches^switches^:
15016
15017 @smallexample
15018 File "common.gpr":
15019 @group
15020 @b{project} Common @b{is}
15021
15022    @b{for} Source_Dirs @b{use} (); -- No source files
15023 @end group
15024
15025 @group
15026    @b{type} Build_Type @b{is} ("release", "debug");
15027    Build : Build_Type := External ("BUILD", "debug");
15028 @end group
15029 @group
15030    @b{package} Compiler @b{is}
15031       @b{case} Build @b{is}
15032          @b{when} "release" =>
15033            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15034                    @b{use} ("^-O2^-O2^");
15035          @b{when} "debug"   =>
15036            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15037                    @b{use} ("^-g^-g^");
15038       @b{end case};
15039    @b{end} Compiler;
15040
15041 @b{end} Common;
15042 @end group
15043 @end smallexample
15044
15045 @item We create separate projects for the two programs:
15046
15047 @smallexample
15048 @group
15049 File "prog1.gpr":
15050
15051 @b{with} "common";
15052 @b{project} Prog1 @b{is}
15053
15054     @b{for} Source_Dirs @b{use} ("prog1");
15055     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
15056
15057     @b{package} Compiler @b{renames} Common.Compiler;
15058
15059 @b{end} Prog1;
15060 @end group
15061 @end smallexample
15062
15063 @smallexample
15064 @group
15065 File "prog2.gpr":
15066
15067 @b{with} "common";
15068 @b{project} Prog2 @b{is}
15069
15070     @b{for} Source_Dirs @b{use} ("prog2");
15071     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
15072
15073     @b{package} Compiler @b{renames} Common.Compiler;
15074
15075 @end group
15076 @b{end} Prog2;
15077 @end smallexample
15078
15079 @item We create a wrapping project @code{Main}:
15080
15081 @smallexample
15082 @group
15083 File "main.gpr":
15084
15085 @b{with} "common";
15086 @b{with} "prog1";
15087 @b{with} "prog2";
15088 @b{project} Main @b{is}
15089
15090    @b{package} Compiler @b{renames} Common.Compiler;
15091
15092 @b{end} Main;
15093 @end group
15094 @end smallexample
15095
15096 @item Finally we need to create a dummy procedure that @code{with}s (either
15097 explicitly or implicitly) all the sources of our two programs.
15098
15099 @end enumerate
15100
15101 @noindent
15102 Now we can build the programs using the command
15103
15104 @smallexample
15105    gnatmake ^-P^/PROJECT_FILE=^main dummy
15106 @end smallexample
15107
15108 @noindent
15109 for the Debug mode, or
15110
15111 @ifclear vms
15112 @smallexample
15113    gnatmake -Pmain -XBUILD=release
15114 @end smallexample
15115 @end ifclear
15116
15117 @ifset vms
15118 @smallexample
15119    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
15120 @end smallexample
15121 @end ifset
15122
15123 @noindent
15124 for the Release mode.
15125
15126 @c ********************************
15127 @c * Project File Complete Syntax *
15128 @c ********************************
15129
15130 @node Project File Complete Syntax
15131 @section Project File Complete Syntax
15132
15133 @smallexample
15134 project ::=
15135   context_clause project_declaration
15136
15137 context_clause ::=
15138   @{with_clause@}
15139
15140 with_clause ::=
15141   @b{with} path_name @{ , path_name @} ;
15142
15143 path_name ::=
15144    string_literal
15145
15146 project_declaration ::=
15147   simple_project_declaration | project_extension
15148
15149 simple_project_declaration ::=
15150   @b{project} <project_>simple_name @b{is}
15151     @{declarative_item@}
15152   @b{end} <project_>simple_name;
15153
15154 project_extension ::=
15155   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
15156     @{declarative_item@}
15157   @b{end} <project_>simple_name;
15158
15159 declarative_item ::=
15160   package_declaration |
15161   typed_string_declaration |
15162   other_declarative_item
15163
15164 package_declaration ::=
15165   package_spec | package_renaming
15166
15167 package_spec ::=
15168   @b{package} package_identifier @b{is}
15169     @{simple_declarative_item@}
15170   @b{end} package_identifier ;
15171
15172 package_identifier ::=
15173   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
15174   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
15175   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
15176
15177 package_renaming ::==
15178   @b{package} package_identifier @b{renames}
15179        <project_>simple_name.package_identifier ;
15180
15181 typed_string_declaration ::=
15182   @b{type} <typed_string_>_simple_name @b{is}
15183    ( string_literal @{, string_literal@} );
15184
15185 other_declarative_item ::=
15186   attribute_declaration |
15187   typed_variable_declaration |
15188   variable_declaration |
15189   case_construction
15190
15191 attribute_declaration ::=
15192   full_associative_array_declaration |
15193   @b{for} attribute_designator @b{use} expression ;
15194
15195 full_associative_array_declaration ::=
15196   @b{for} <associative_array_attribute_>simple_name @b{use}
15197   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
15198
15199 attribute_designator ::=
15200   <simple_attribute_>simple_name |
15201   <associative_array_attribute_>simple_name ( string_literal )
15202
15203 typed_variable_declaration ::=
15204   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
15205
15206 variable_declaration ::=
15207   <variable_>simple_name := expression;
15208
15209 expression ::=
15210   term @{& term@}
15211
15212 term ::=
15213   literal_string |
15214   string_list |
15215   <variable_>name |
15216   external_value |
15217   attribute_reference
15218
15219 string_literal ::=
15220   (same as Ada)
15221
15222 string_list ::=
15223   ( <string_>expression @{ , <string_>expression @} )
15224
15225 external_value ::=
15226   @b{external} ( string_literal [, string_literal] )
15227
15228 attribute_reference ::=
15229   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
15230
15231 attribute_prefix ::=
15232   @b{project} |
15233   <project_>simple_name | package_identifier |
15234   <project_>simple_name . package_identifier
15235
15236 case_construction ::=
15237   @b{case} <typed_variable_>name @b{is}
15238     @{case_item@}
15239   @b{end case} ;
15240
15241 case_item ::=
15242   @b{when} discrete_choice_list =>
15243       @{case_construction | attribute_declaration@}
15244
15245 discrete_choice_list ::=
15246   string_literal @{| string_literal@} |
15247   @b{others}
15248
15249 name ::=
15250   simple_name @{. simple_name@}
15251
15252 simple_name ::=
15253   identifier (same as Ada)
15254
15255 @end smallexample
15256
15257 @node The Cross-Referencing Tools gnatxref and gnatfind
15258 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
15259 @findex gnatxref
15260 @findex gnatfind
15261
15262 @noindent
15263 The compiler generates cross-referencing information (unless
15264 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
15265 This information indicates where in the source each entity is declared and
15266 referenced. Note that entities in package Standard are not included, but
15267 entities in all other predefined units are included in the output.
15268
15269 Before using any of these two tools, you need to compile successfully your
15270 application, so that GNAT gets a chance to generate the cross-referencing
15271 information.
15272
15273 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
15274 information to provide the user with the capability to easily locate the
15275 declaration and references to an entity. These tools are quite similar,
15276 the difference being that @code{gnatfind} is intended for locating
15277 definitions and/or references to a specified entity or entities, whereas
15278 @code{gnatxref} is oriented to generating a full report of all
15279 cross-references.
15280
15281 To use these tools, you must not compile your application using the
15282 @option{-gnatx} switch on the @command{gnatmake} command line
15283 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
15284 information will not be generated.
15285
15286 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
15287 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15288
15289 @menu
15290 * gnatxref Switches::
15291 * gnatfind Switches::
15292 * Project Files for gnatxref and gnatfind::
15293 * Regular Expressions in gnatfind and gnatxref::
15294 * Examples of gnatxref Usage::
15295 * Examples of gnatfind Usage::
15296 @end menu
15297
15298 @node gnatxref Switches
15299 @section @code{gnatxref} Switches
15300
15301 @noindent
15302 The command invocation for @code{gnatxref} is:
15303 @smallexample
15304 $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15305 @end smallexample
15306
15307 @noindent
15308 where
15309
15310 @table @var
15311 @item sourcefile1
15312 @itemx sourcefile2
15313 identifies the source files for which a report is to be generated. The
15314 ``with''ed units will be processed too. You must provide at least one file.
15315
15316 These file names are considered to be regular expressions, so for instance
15317 specifying @file{source*.adb} is the same as giving every file in the current
15318 directory whose name starts with @file{source} and whose extension is
15319 @file{adb}.
15320
15321 You shouldn't specify any directory name, just base names. @command{gnatxref}
15322 and @command{gnatfind} will be able to locate these files by themselves using
15323 the source path. If you specify directories, no result is produced.
15324
15325 @end table
15326
15327 @noindent
15328 The switches can be:
15329 @table @option
15330 @c !sort!
15331 @item --version
15332 @cindex @option{--version} @command{gnatxref}
15333 Display Copyright and version, then exit disregarding all other options.
15334
15335 @item --help
15336 @cindex @option{--help} @command{gnatxref}
15337 If @option{--version} was not used, display usage, then exit disregarding
15338 all other options.
15339
15340 @item ^-a^/ALL_FILES^
15341 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15342 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15343 the read-only files found in the library search path. Otherwise, these files
15344 will be ignored. This option can be used to protect Gnat sources or your own
15345 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15346 much faster, and their output much smaller. Read-only here refers to access
15347 or permissions status in the file system for the current user.
15348
15349 @item -aIDIR
15350 @cindex @option{-aIDIR} (@command{gnatxref})
15351 When looking for source files also look in directory DIR. The order in which
15352 source file search is undertaken is the same as for @command{gnatmake}.
15353
15354 @item -aODIR
15355 @cindex @option{-aODIR} (@command{gnatxref})
15356 When searching for library and object files, look in directory
15357 DIR. The order in which library files are searched is the same as for
15358 @command{gnatmake}.
15359
15360 @item -nostdinc
15361 @cindex @option{-nostdinc} (@command{gnatxref})
15362 Do not look for sources in the system default directory.
15363
15364 @item -nostdlib
15365 @cindex @option{-nostdlib} (@command{gnatxref})
15366 Do not look for library files in the system default directory.
15367
15368 @item --RTS=@var{rts-path}
15369 @cindex @option{--RTS} (@command{gnatxref})
15370 Specifies the default location of the runtime library. Same meaning as the
15371 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15372
15373 @item ^-d^/DERIVED_TYPES^
15374 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15375 If this switch is set @code{gnatxref} will output the parent type
15376 reference for each matching derived types.
15377
15378 @item ^-f^/FULL_PATHNAME^
15379 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15380 If this switch is set, the output file names will be preceded by their
15381 directory (if the file was found in the search path). If this switch is
15382 not set, the directory will not be printed.
15383
15384 @item ^-g^/IGNORE_LOCALS^
15385 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15386 If this switch is set, information is output only for library-level
15387 entities, ignoring local entities. The use of this switch may accelerate
15388 @code{gnatfind} and @code{gnatxref}.
15389
15390 @item -IDIR
15391 @cindex @option{-IDIR} (@command{gnatxref})
15392 Equivalent to @samp{-aODIR -aIDIR}.
15393
15394 @item -pFILE
15395 @cindex @option{-pFILE} (@command{gnatxref})
15396 Specify a project file to use @xref{Project Files}.
15397 If you need to use the @file{.gpr}
15398 project files, you should use gnatxref through the GNAT driver
15399 (@command{gnat xref -Pproject}).
15400
15401 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15402 project file in the current directory.
15403
15404 If a project file is either specified or found by the tools, then the content
15405 of the source directory and object directory lines are added as if they
15406 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15407 and @samp{^-aO^OBJECT_SEARCH^}.
15408 @item ^-u^/UNUSED^
15409 Output only unused symbols. This may be really useful if you give your
15410 main compilation unit on the command line, as @code{gnatxref} will then
15411 display every unused entity and 'with'ed package.
15412
15413 @ifclear vms
15414 @item -v
15415 Instead of producing the default output, @code{gnatxref} will generate a
15416 @file{tags} file that can be used by vi. For examples how to use this
15417 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15418 to the standard output, thus you will have to redirect it to a file.
15419 @end ifclear
15420
15421 @end table
15422
15423 @noindent
15424 All these switches may be in any order on the command line, and may even
15425 appear after the file names. They need not be separated by spaces, thus
15426 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15427 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15428
15429 @node gnatfind Switches
15430 @section @code{gnatfind} Switches
15431
15432 @noindent
15433 The command line for @code{gnatfind} is:
15434
15435 @smallexample
15436 $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15437       @r{[}@var{file1} @var{file2} @dots{}]
15438 @end smallexample
15439
15440 @noindent
15441 where
15442
15443 @table @var
15444 @item pattern
15445 An entity will be output only if it matches the regular expression found
15446 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15447
15448 Omitting the pattern is equivalent to specifying @samp{*}, which
15449 will match any entity. Note that if you do not provide a pattern, you
15450 have to provide both a sourcefile and a line.
15451
15452 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15453 for matching purposes. At the current time there is no support for
15454 8-bit codes other than Latin-1, or for wide characters in identifiers.
15455
15456 @item sourcefile
15457 @code{gnatfind} will look for references, bodies or declarations
15458 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15459 and column @var{column}. See @ref{Examples of gnatfind Usage}
15460 for syntax examples.
15461
15462 @item line
15463 is a decimal integer identifying the line number containing
15464 the reference to the entity (or entities) to be located.
15465
15466 @item column
15467 is a decimal integer identifying the exact location on the
15468 line of the first character of the identifier for the
15469 entity reference. Columns are numbered from 1.
15470
15471 @item file1 file2 @dots{}
15472 The search will be restricted to these source files. If none are given, then
15473 the search will be done for every library file in the search path.
15474 These file must appear only after the pattern or sourcefile.
15475
15476 These file names are considered to be regular expressions, so for instance
15477 specifying @file{source*.adb} is the same as giving every file in the current
15478 directory whose name starts with @file{source} and whose extension is
15479 @file{adb}.
15480
15481 The location of the spec of the entity will always be displayed, even if it
15482 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
15483 occurrences of the entity in the separate units of the ones given on the
15484 command line will also be displayed.
15485
15486 Note that if you specify at least one file in this part, @code{gnatfind} may
15487 sometimes not be able to find the body of the subprograms.
15488
15489 @end table
15490
15491 @noindent
15492 At least one of 'sourcefile' or 'pattern' has to be present on
15493 the command line.
15494
15495 The following switches are available:
15496 @table @option
15497 @c !sort!
15498
15499 @cindex @option{--version} @command{gnatfind}
15500 Display Copyright and version, then exit disregarding all other options.
15501
15502 @item --help
15503 @cindex @option{--help} @command{gnatfind}
15504 If @option{--version} was not used, display usage, then exit disregarding
15505 all other options.
15506
15507 @item ^-a^/ALL_FILES^
15508 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15509 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15510 the read-only files found in the library search path. Otherwise, these files
15511 will be ignored. This option can be used to protect Gnat sources or your own
15512 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15513 much faster, and their output much smaller. Read-only here refers to access
15514 or permission status in the file system for the current user.
15515
15516 @item -aIDIR
15517 @cindex @option{-aIDIR} (@command{gnatfind})
15518 When looking for source files also look in directory DIR. The order in which
15519 source file search is undertaken is the same as for @command{gnatmake}.
15520
15521 @item -aODIR
15522 @cindex @option{-aODIR} (@command{gnatfind})
15523 When searching for library and object files, look in directory
15524 DIR. The order in which library files are searched is the same as for
15525 @command{gnatmake}.
15526
15527 @item -nostdinc
15528 @cindex @option{-nostdinc} (@command{gnatfind})
15529 Do not look for sources in the system default directory.
15530
15531 @item -nostdlib
15532 @cindex @option{-nostdlib} (@command{gnatfind})
15533 Do not look for library files in the system default directory.
15534
15535 @item --RTS=@var{rts-path}
15536 @cindex @option{--RTS} (@command{gnatfind})
15537 Specifies the default location of the runtime library. Same meaning as the
15538 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15539
15540 @item ^-d^/DERIVED_TYPE_INFORMATION^
15541 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15542 If this switch is set, then @code{gnatfind} will output the parent type
15543 reference for each matching derived types.
15544
15545 @item ^-e^/EXPRESSIONS^
15546 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15547 By default, @code{gnatfind} accept the simple regular expression set for
15548 @samp{pattern}. If this switch is set, then the pattern will be
15549 considered as full Unix-style regular expression.
15550
15551 @item ^-f^/FULL_PATHNAME^
15552 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15553 If this switch is set, the output file names will be preceded by their
15554 directory (if the file was found in the search path). If this switch is
15555 not set, the directory will not be printed.
15556
15557 @item ^-g^/IGNORE_LOCALS^
15558 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15559 If this switch is set, information is output only for library-level
15560 entities, ignoring local entities. The use of this switch may accelerate
15561 @code{gnatfind} and @code{gnatxref}.
15562
15563 @item -IDIR
15564 @cindex @option{-IDIR} (@command{gnatfind})
15565 Equivalent to @samp{-aODIR -aIDIR}.
15566
15567 @item -pFILE
15568 @cindex @option{-pFILE} (@command{gnatfind})
15569 Specify a project file (@pxref{Project Files}) to use.
15570 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15571 project file in the current directory.
15572
15573 If a project file is either specified or found by the tools, then the content
15574 of the source directory and object directory lines are added as if they
15575 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15576 @samp{^-aO^/OBJECT_SEARCH^}.
15577
15578 @item ^-r^/REFERENCES^
15579 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15580 By default, @code{gnatfind} will output only the information about the
15581 declaration, body or type completion of the entities. If this switch is
15582 set, the @code{gnatfind} will locate every reference to the entities in
15583 the files specified on the command line (or in every file in the search
15584 path if no file is given on the command line).
15585
15586 @item ^-s^/PRINT_LINES^
15587 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15588 If this switch is set, then @code{gnatfind} will output the content
15589 of the Ada source file lines were the entity was found.
15590
15591 @item ^-t^/TYPE_HIERARCHY^
15592 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15593 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15594 the specified type. It act like -d option but recursively from parent
15595 type to parent type. When this switch is set it is not possible to
15596 specify more than one file.
15597
15598 @end table
15599
15600 @noindent
15601 All these switches may be in any order on the command line, and may even
15602 appear after the file names. They need not be separated by spaces, thus
15603 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15604 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15605
15606 As stated previously, gnatfind will search in every directory in the
15607 search path. You can force it to look only in the current directory if
15608 you specify @code{*} at the end of the command line.
15609
15610 @node Project Files for gnatxref and gnatfind
15611 @section Project Files for @command{gnatxref} and @command{gnatfind}
15612
15613 @noindent
15614 Project files allow a programmer to specify how to compile its
15615 application, where to find sources, etc.  These files are used
15616 @ifclear vms
15617 primarily by GPS, but they can also be used
15618 @end ifclear
15619 by the two tools
15620 @code{gnatxref} and @code{gnatfind}.
15621
15622 A project file name must end with @file{.gpr}. If a single one is
15623 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15624 extract the information from it. If multiple project files are found, none of
15625 them is read, and you have to use the @samp{-p} switch to specify the one
15626 you want to use.
15627
15628 The following lines can be included, even though most of them have default
15629 values which can be used in most cases.
15630 The lines can be entered in any order in the file.
15631 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15632 each line. If you have multiple instances, only the last one is taken into
15633 account.
15634
15635 @table @code
15636 @item src_dir=DIR
15637 [default: @code{"^./^[]^"}]
15638 specifies a directory where to look for source files. Multiple @code{src_dir}
15639 lines can be specified and they will be searched in the order they
15640 are specified.
15641
15642 @item obj_dir=DIR
15643 [default: @code{"^./^[]^"}]
15644 specifies a directory where to look for object and library files. Multiple
15645 @code{obj_dir} lines can be specified, and they will be searched in the order
15646 they are specified
15647
15648 @item comp_opt=SWITCHES
15649 [default: @code{""}]
15650 creates a variable which can be referred to subsequently by using
15651 the @code{$@{comp_opt@}} notation. This is intended to store the default
15652 switches given to @command{gnatmake} and @command{gcc}.
15653
15654 @item bind_opt=SWITCHES
15655 [default: @code{""}]
15656 creates a variable which can be referred to subsequently by using
15657 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15658 switches given to @command{gnatbind}.
15659
15660 @item link_opt=SWITCHES
15661 [default: @code{""}]
15662 creates a variable which can be referred to subsequently by using
15663 the @samp{$@{link_opt@}} notation. This is intended to store the default
15664 switches given to @command{gnatlink}.
15665
15666 @item main=EXECUTABLE
15667 [default: @code{""}]
15668 specifies the name of the executable for the application. This variable can
15669 be referred to in the following lines by using the @samp{$@{main@}} notation.
15670
15671 @ifset vms
15672 @item comp_cmd=COMMAND
15673 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15674 @end ifset
15675 @ifclear vms
15676 @item comp_cmd=COMMAND
15677 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15678 @end ifclear
15679 specifies the command used to compile a single file in the application.
15680
15681 @ifset vms
15682 @item make_cmd=COMMAND
15683 [default: @code{"GNAT MAKE $@{main@}
15684 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15685 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15686 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15687 @end ifset
15688 @ifclear vms
15689 @item make_cmd=COMMAND
15690 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15691 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15692 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15693 @end ifclear
15694 specifies the command used to recompile the whole application.
15695
15696 @item run_cmd=COMMAND
15697 [default: @code{"$@{main@}"}]
15698 specifies the command used to run the application.
15699
15700 @item debug_cmd=COMMAND
15701 [default: @code{"gdb $@{main@}"}]
15702 specifies the command used to debug the application
15703
15704 @end table
15705
15706 @noindent
15707 @command{gnatxref} and @command{gnatfind} only take into account the
15708 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15709
15710 @node Regular Expressions in gnatfind and gnatxref
15711 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15712
15713 @noindent
15714 As specified in the section about @command{gnatfind}, the pattern can be a
15715 regular expression. Actually, there are to set of regular expressions
15716 which are recognized by the program:
15717
15718 @table @code
15719 @item globbing patterns
15720 These are the most usual regular expression. They are the same that you
15721 generally used in a Unix shell command line, or in a DOS session.
15722
15723 Here is a more formal grammar:
15724 @smallexample
15725 @group
15726 @iftex
15727 @leftskip=.5cm
15728 @end iftex
15729 regexp ::= term
15730 term   ::= elmt            -- matches elmt
15731 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15732 term   ::= *               -- any string of 0 or more characters
15733 term   ::= ?               -- matches any character
15734 term   ::= [char @{char@}]   -- matches any character listed
15735 term   ::= [char - char]   -- matches any character in range
15736 @end group
15737 @end smallexample
15738
15739 @item full regular expression
15740 The second set of regular expressions is much more powerful. This is the
15741 type of regular expressions recognized by utilities such a @file{grep}.
15742
15743 The following is the form of a regular expression, expressed in Ada
15744 reference manual style BNF is as follows
15745
15746 @smallexample
15747 @iftex
15748 @leftskip=.5cm
15749 @end iftex
15750 @group
15751 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
15752
15753 term ::= item @{item@}       -- concatenation (item then item)
15754
15755 item ::= elmt              -- match elmt
15756 item ::= elmt *            -- zero or more elmt's
15757 item ::= elmt +            -- one or more elmt's
15758 item ::= elmt ?            -- matches elmt or nothing
15759 @end group
15760 @group
15761 elmt ::= nschar            -- matches given character
15762 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15763 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15764 elmt ::= [char - char]     -- matches chars in given range
15765 elmt ::= \ char            -- matches given character
15766 elmt ::= .                 -- matches any single character
15767 elmt ::= ( regexp )        -- parens used for grouping
15768
15769 char ::= any character, including special characters
15770 nschar ::= any character except ()[].*+?^^^
15771 @end group
15772 @end smallexample
15773
15774 Following are a few examples:
15775
15776 @table @samp
15777 @item abcde|fghi
15778 will match any of the two strings @samp{abcde} and @samp{fghi},
15779
15780 @item abc*d
15781 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15782 @samp{abcccd}, and so on,
15783
15784 @item [a-z]+
15785 will match any string which has only lowercase characters in it (and at
15786 least one character.
15787
15788 @end table
15789 @end table
15790
15791 @node Examples of gnatxref Usage
15792 @section Examples of @code{gnatxref} Usage
15793
15794 @subsection General Usage
15795
15796 @noindent
15797 For the following examples, we will consider the following units:
15798
15799 @smallexample @c ada
15800 @group
15801 @cartouche
15802 main.ads:
15803 1: with Bar;
15804 2: package Main is
15805 3:     procedure Foo (B : in Integer);
15806 4:     C : Integer;
15807 5: private
15808 6:     D : Integer;
15809 7: end Main;
15810
15811 main.adb:
15812 1: package body Main is
15813 2:     procedure Foo (B : in Integer) is
15814 3:     begin
15815 4:        C := B;
15816 5:        D := B;
15817 6:        Bar.Print (B);
15818 7:        Bar.Print (C);
15819 8:     end Foo;
15820 9: end Main;
15821
15822 bar.ads:
15823 1: package Bar is
15824 2:     procedure Print (B : Integer);
15825 3: end bar;
15826 @end cartouche
15827 @end group
15828 @end smallexample
15829
15830 @table @code
15831
15832 @noindent
15833 The first thing to do is to recompile your application (for instance, in
15834 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15835 the cross-referencing information.
15836 You can then issue any of the following commands:
15837
15838 @item gnatxref main.adb
15839 @code{gnatxref} generates cross-reference information for main.adb
15840 and every unit 'with'ed by main.adb.
15841
15842 The output would be:
15843 @smallexample
15844 @iftex
15845 @leftskip=0cm
15846 @end iftex
15847 B                                                      Type: Integer
15848   Decl: bar.ads           2:22
15849 B                                                      Type: Integer
15850   Decl: main.ads          3:20
15851   Body: main.adb          2:20
15852   Ref:  main.adb          4:13     5:13     6:19
15853 Bar                                                    Type: Unit
15854   Decl: bar.ads           1:9
15855   Ref:  main.adb          6:8      7:8
15856        main.ads           1:6
15857 C                                                      Type: Integer
15858   Decl: main.ads          4:5
15859   Modi: main.adb          4:8
15860   Ref:  main.adb          7:19
15861 D                                                      Type: Integer
15862   Decl: main.ads          6:5
15863   Modi: main.adb          5:8
15864 Foo                                                    Type: Unit
15865   Decl: main.ads          3:15
15866   Body: main.adb          2:15
15867 Main                                                    Type: Unit
15868   Decl: main.ads          2:9
15869   Body: main.adb          1:14
15870 Print                                                   Type: Unit
15871   Decl: bar.ads           2:15
15872   Ref:  main.adb          6:12     7:12
15873 @end smallexample
15874
15875 @noindent
15876 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15877 its body is in main.adb, line 1, column 14 and is not referenced any where.
15878
15879 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15880 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15881
15882 @item gnatxref package1.adb package2.ads
15883 @code{gnatxref} will generates cross-reference information for
15884 package1.adb, package2.ads and any other package 'with'ed by any
15885 of these.
15886
15887 @end table
15888
15889 @ifclear vms
15890 @subsection Using gnatxref with vi
15891
15892 @code{gnatxref} can generate a tags file output, which can be used
15893 directly from @command{vi}. Note that the standard version of @command{vi}
15894 will not work properly with overloaded symbols. Consider using another
15895 free implementation of @command{vi}, such as @command{vim}.
15896
15897 @smallexample
15898 $ gnatxref -v gnatfind.adb > tags
15899 @end smallexample
15900
15901 @noindent
15902 will generate the tags file for @code{gnatfind} itself (if the sources
15903 are in the search path!).
15904
15905 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
15906 (replacing @var{entity} by whatever you are looking for), and vi will
15907 display a new file with the corresponding declaration of entity.
15908 @end ifclear
15909
15910 @node Examples of gnatfind Usage
15911 @section Examples of @code{gnatfind} Usage
15912
15913 @table @code
15914
15915 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15916 Find declarations for all entities xyz referenced at least once in
15917 main.adb. The references are search in every library file in the search
15918 path.
15919
15920 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15921 switch is set)
15922
15923 The output will look like:
15924 @smallexample
15925 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15926 ^directory/^[directory]^main.adb:24:10: xyz <= body
15927 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15928 @end smallexample
15929
15930 @noindent
15931 that is to say, one of the entities xyz found in main.adb is declared at
15932 line 12 of main.ads (and its body is in main.adb), and another one is
15933 declared at line 45 of foo.ads
15934
15935 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
15936 This is the same command as the previous one, instead @code{gnatfind} will
15937 display the content of the Ada source file lines.
15938
15939 The output will look like:
15940
15941 @smallexample
15942 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15943    procedure xyz;
15944 ^directory/^[directory]^main.adb:24:10: xyz <= body
15945    procedure xyz is
15946 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15947    xyz : Integer;
15948 @end smallexample
15949
15950 @noindent
15951 This can make it easier to find exactly the location your are looking
15952 for.
15953
15954 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
15955 Find references to all entities containing an x that are
15956 referenced on line 123 of main.ads.
15957 The references will be searched only in main.ads and foo.adb.
15958
15959 @item gnatfind main.ads:123
15960 Find declarations and bodies for all entities that are referenced on
15961 line 123 of main.ads.
15962
15963 This is the same as @code{gnatfind "*":main.adb:123}.
15964
15965 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
15966 Find the declaration for the entity referenced at column 45 in
15967 line 123 of file main.adb in directory mydir. Note that it
15968 is usual to omit the identifier name when the column is given,
15969 since the column position identifies a unique reference.
15970
15971 The column has to be the beginning of the identifier, and should not
15972 point to any character in the middle of the identifier.
15973
15974 @end table
15975
15976 @c *********************************
15977 @node The GNAT Pretty-Printer gnatpp
15978 @chapter The GNAT Pretty-Printer @command{gnatpp}
15979 @findex gnatpp
15980 @cindex Pretty-Printer
15981
15982 @noindent
15983 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
15984 for source reformatting / pretty-printing.
15985 It takes an Ada source file as input and generates a reformatted
15986 version as output.
15987 You can specify various style directives via switches; e.g.,
15988 identifier case conventions, rules of indentation, and comment layout.
15989
15990 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
15991 tree for the input source and thus requires the input to be syntactically and
15992 semantically legal.
15993 If this condition is not met, @command{gnatpp} will terminate with an
15994 error message; no output file will be generated.
15995
15996 If the source files presented to @command{gnatpp} contain
15997 preprocessing directives, then the output file will
15998 correspond to the generated source after all
15999 preprocessing is carried out. There is no way
16000 using @command{gnatpp} to obtain pretty printed files that
16001 include the preprocessing directives.
16002
16003 If the compilation unit
16004 contained in the input source depends semantically upon units located
16005 outside the current directory, you have to provide the source search path
16006 when invoking @command{gnatpp}, if these units are contained in files with
16007 names that do not follow the GNAT file naming rules, you have to provide
16008 the configuration file describing the corresponding naming scheme;
16009 see the description of the @command{gnatpp}
16010 switches below. Another possibility is to use a project file and to
16011 call @command{gnatpp} through the @command{gnat} driver
16012
16013 The @command{gnatpp} command has the form
16014
16015 @smallexample
16016 $ gnatpp @ovar{switches} @var{filename}
16017 @end smallexample
16018
16019 @noindent
16020 where
16021 @itemize @bullet
16022 @item
16023 @var{switches} is an optional sequence of switches defining such properties as
16024 the formatting rules, the source search path, and the destination for the
16025 output source file
16026
16027 @item
16028 @var{filename} is the name (including the extension) of the source file to
16029 reformat; ``wildcards'' or several file names on the same gnatpp command are
16030 allowed.  The file name may contain path information; it does not have to
16031 follow the GNAT file naming rules
16032 @end itemize
16033
16034 @menu
16035 * Switches for gnatpp::
16036 * Formatting Rules::
16037 @end menu
16038
16039 @node Switches for gnatpp
16040 @section Switches for @command{gnatpp}
16041
16042 @noindent
16043 The following subsections describe the various switches accepted by
16044 @command{gnatpp}, organized by category.
16045
16046 @ifclear vms
16047 You specify a switch by supplying a name and generally also a value.
16048 In many cases the values for a switch with a given name are incompatible with
16049 each other
16050 (for example the switch that controls the casing of a reserved word may have
16051 exactly one value: upper case, lower case, or
16052 mixed case) and thus exactly one such switch can be in effect for an
16053 invocation of @command{gnatpp}.
16054 If more than one is supplied, the last one is used.
16055 However, some values for the same switch are mutually compatible.
16056 You may supply several such switches to @command{gnatpp}, but then
16057 each must be specified in full, with both the name and the value.
16058 Abbreviated forms (the name appearing once, followed by each value) are
16059 not permitted.
16060 For example, to set
16061 the alignment of the assignment delimiter both in declarations and in
16062 assignment statements, you must write @option{-A2A3}
16063 (or @option{-A2 -A3}), but not @option{-A23}.
16064 @end ifclear
16065
16066 @ifset vms
16067 In many cases the set of options for a given qualifier are incompatible with
16068 each other (for example the qualifier that controls the casing of a reserved
16069 word may have exactly one option, which specifies either upper case, lower
16070 case, or mixed case), and thus exactly one such option can be in effect for
16071 an invocation of @command{gnatpp}.
16072 If more than one is supplied, the last one is used.
16073 However, some qualifiers have options that are mutually compatible,
16074 and then you may then supply several such options when invoking
16075 @command{gnatpp}.
16076 @end ifset
16077
16078 In most cases, it is obvious whether or not the
16079 ^values for a switch with a given name^options for a given qualifier^
16080 are compatible with each other.
16081 When the semantics might not be evident, the summaries below explicitly
16082 indicate the effect.
16083
16084 @menu
16085 * Alignment Control::
16086 * Casing Control::
16087 * Construct Layout Control::
16088 * General Text Layout Control::
16089 * Other Formatting Options::
16090 * Setting the Source Search Path::
16091 * Output File Control::
16092 * Other gnatpp Switches::
16093 @end menu
16094
16095 @node Alignment Control
16096 @subsection Alignment Control
16097 @cindex Alignment control in @command{gnatpp}
16098
16099 @noindent
16100 Programs can be easier to read if certain constructs are vertically aligned.
16101 By default all alignments are set ON.
16102 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
16103 OFF, and then use one or more of the other
16104 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
16105 to activate alignment for specific constructs.
16106
16107 @table @option
16108 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
16109
16110 @ifset vms
16111 @item /ALIGN=ON
16112 Set all alignments to ON
16113 @end ifset
16114
16115 @item ^-A0^/ALIGN=OFF^
16116 Set all alignments to OFF
16117
16118 @item ^-A1^/ALIGN=COLONS^
16119 Align @code{:} in declarations
16120
16121 @item ^-A2^/ALIGN=DECLARATIONS^
16122 Align @code{:=} in initializations in declarations
16123
16124 @item ^-A3^/ALIGN=STATEMENTS^
16125 Align @code{:=} in assignment statements
16126
16127 @item ^-A4^/ALIGN=ARROWS^
16128 Align @code{=>} in associations
16129
16130 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
16131 Align @code{at} keywords in the component clauses in record
16132 representation clauses
16133 @end table
16134
16135 @noindent
16136 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
16137 is allowed.
16138
16139 @node Casing Control
16140 @subsection Casing Control
16141 @cindex Casing control in @command{gnatpp}
16142
16143 @noindent
16144 @command{gnatpp} allows you to specify the casing for reserved words,
16145 pragma names, attribute designators and identifiers.
16146 For identifiers you may define a
16147 general rule for name casing but also override this rule
16148 via a set of dictionary files.
16149
16150 Three types of casing are supported: lower case, upper case, and mixed case.
16151 Lower and upper case are self-explanatory (but since some letters in
16152 Latin1 and other GNAT-supported character sets
16153 exist only in lower-case form, an upper case conversion will have no
16154 effect on them.)
16155 ``Mixed case'' means that the first letter, and also each letter immediately
16156 following an underscore, are converted to their uppercase forms;
16157 all the other letters are converted to their lowercase forms.
16158
16159 @table @option
16160 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
16161 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
16162 Attribute designators are lower case
16163
16164 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
16165 Attribute designators are upper case
16166
16167 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
16168 Attribute designators are mixed case (this is the default)
16169
16170 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
16171 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
16172 Keywords (technically, these are known in Ada as @emph{reserved words}) are
16173 lower case (this is the default)
16174
16175 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
16176 Keywords are upper case
16177
16178 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
16179 @item ^-nD^/NAME_CASING=AS_DECLARED^
16180 Name casing for defining occurrences are as they appear in the source file
16181 (this is the default)
16182
16183 @item ^-nU^/NAME_CASING=UPPER_CASE^
16184 Names are in upper case
16185
16186 @item ^-nL^/NAME_CASING=LOWER_CASE^
16187 Names are in lower case
16188
16189 @item ^-nM^/NAME_CASING=MIXED_CASE^
16190 Names are in mixed case
16191
16192 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
16193 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
16194 Pragma names are lower case
16195
16196 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
16197 Pragma names are upper case
16198
16199 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
16200 Pragma names are mixed case (this is the default)
16201
16202 @item ^-D@var{file}^/DICTIONARY=@var{file}^
16203 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
16204 Use @var{file} as a @emph{dictionary file} that defines
16205 the casing for a set of specified names,
16206 thereby overriding the effect on these names by
16207 any explicit or implicit
16208 ^-n^/NAME_CASING^ switch.
16209 To supply more than one dictionary file,
16210 use ^several @option{-D} switches^a list of files as options^.
16211
16212 @noindent
16213 @option{gnatpp} implicitly uses a @emph{default dictionary file}
16214 to define the casing for the Ada predefined names and
16215 the names declared in the GNAT libraries.
16216
16217 @item ^-D-^/SPECIFIC_CASING^
16218 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
16219 Do not use the default dictionary file;
16220 instead, use the casing
16221 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
16222 dictionary file(s)
16223 @end table
16224
16225 @noindent
16226 The structure of a dictionary file, and details on the conventions
16227 used in the default dictionary file, are defined in @ref{Name Casing}.
16228
16229 The @option{^-D-^/SPECIFIC_CASING^} and
16230 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
16231 compatible.
16232
16233 @node Construct Layout Control
16234 @subsection Construct Layout Control
16235 @cindex Layout control in @command{gnatpp}
16236
16237 @noindent
16238 This group of @command{gnatpp} switches controls the layout of comments and
16239 complex syntactic constructs.  See @ref{Formatting Comments} for details
16240 on their effect.
16241
16242 @table @option
16243 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
16244 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
16245 All the comments remain unchanged
16246
16247 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
16248 GNAT-style comment line indentation (this is the default).
16249
16250 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
16251 Reference-manual comment line indentation.
16252
16253 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
16254 GNAT-style comment beginning
16255
16256 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
16257 Reformat comment blocks
16258
16259 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
16260 Keep unchanged special form comments
16261
16262 Reformat comment blocks
16263
16264 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
16265 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
16266 GNAT-style layout (this is the default)
16267
16268 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
16269 Compact layout
16270
16271 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
16272 Uncompact layout
16273
16274 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
16275 @item ^-N^/NOTABS^
16276 All the VT characters are removed from the comment text. All the HT characters
16277 are expanded with the sequences of space characters to get to the next tab
16278 stops.
16279
16280 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
16281 @item ^--no-separate-is^/NO_SEPARATE_IS^
16282 Do not place the keyword @code{is} on a separate line in a subprogram body in
16283 case if the spec occupies more then one line.
16284
16285 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
16286 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
16287 Place the keyword @code{loop} in FOR and WHILE loop statements and the
16288 keyword @code{then} in IF statements on a separate line.
16289
16290 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
16291 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
16292 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
16293 keyword @code{then} in IF statements on a separate line. This option is
16294 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16295
16296 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16297 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16298 Start each USE clause in a context clause from a separate line.
16299
16300 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16301 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16302 Use a separate line for a loop or block statement name, but do not use an extra
16303 indentation level for the statement itself.
16304
16305 @end table
16306
16307 @ifclear vms
16308 @noindent
16309 The @option{-c1} and @option{-c2} switches are incompatible.
16310 The @option{-c3} and @option{-c4} switches are compatible with each other and
16311 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16312 the other comment formatting switches.
16313
16314 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16315 @end ifclear
16316
16317 @ifset vms
16318 @noindent
16319 For the @option{/COMMENTS_LAYOUT} qualifier:
16320 @itemize @bullet
16321 @item
16322 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16323 @item
16324 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16325 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16326 @end itemize
16327
16328 @noindent
16329 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16330 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16331 @end ifset
16332
16333 @node General Text Layout Control
16334 @subsection General Text Layout Control
16335
16336 @noindent
16337 These switches allow control over line length and indentation.
16338
16339 @table @option
16340 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16341 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16342 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16343
16344 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16345 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16346 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16347
16348 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16349 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16350 Indentation level for continuation lines (relative to the line being
16351 continued), @var{nnn} from 1@dots{}9.
16352 The default
16353 value is one less then the (normal) indentation level, unless the
16354 indentation is set to 1 (in which case the default value for continuation
16355 line indentation is also 1)
16356 @end table
16357
16358 @node Other Formatting Options
16359 @subsection Other Formatting Options
16360
16361 @noindent
16362 These switches control the inclusion of missing end/exit labels, and
16363 the indentation level in @b{case} statements.
16364
16365 @table @option
16366 @item ^-e^/NO_MISSED_LABELS^
16367 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16368 Do not insert missing end/exit labels. An end label is the name of
16369 a construct that may optionally be repeated at the end of the
16370 construct's declaration;
16371 e.g., the names of packages, subprograms, and tasks.
16372 An exit label is the name of a loop that may appear as target
16373 of an exit statement within the loop.
16374 By default, @command{gnatpp} inserts these end/exit labels when
16375 they are absent from the original source. This option suppresses such
16376 insertion, so that the formatted source reflects the original.
16377
16378 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16379 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16380 Insert a Form Feed character after a pragma Page.
16381
16382 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16383 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16384 Do not use an additional indentation level for @b{case} alternatives
16385 and variants if there are @var{nnn} or more (the default
16386 value is 10).
16387 If @var{nnn} is 0, an additional indentation level is
16388 used for @b{case} alternatives and variants regardless of their number.
16389 @end table
16390
16391 @node Setting the Source Search Path
16392 @subsection Setting the Source Search Path
16393
16394 @noindent
16395 To define the search path for the input source file, @command{gnatpp}
16396 uses the same switches as the GNAT compiler, with the same effects.
16397
16398 @table @option
16399 @item ^-I^/SEARCH=^@var{dir}
16400 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16401 The same as the corresponding gcc switch
16402
16403 @item ^-I-^/NOCURRENT_DIRECTORY^
16404 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16405 The same as the corresponding gcc switch
16406
16407 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16408 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16409 The same as the corresponding gcc switch
16410
16411 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16412 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16413 The same as the corresponding gcc switch
16414
16415 @end table
16416
16417 @node Output File Control
16418 @subsection Output File Control
16419
16420 @noindent
16421 By default the output is sent to the file whose name is obtained by appending
16422 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16423 (if the file with this name already exists, it is unconditionally overwritten).
16424 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16425 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16426 as output file.
16427 The output may be redirected by the following switches:
16428
16429 @table @option
16430 @item ^-pipe^/STANDARD_OUTPUT^
16431 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16432 Send the output to @code{Standard_Output}
16433
16434 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16435 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16436 Write the output into @var{output_file}.
16437 If @var{output_file} already exists, @command{gnatpp} terminates without
16438 reading or processing the input file.
16439
16440 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16441 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16442 Write the output into @var{output_file}, overwriting the existing file
16443 (if one is present).
16444
16445 @item ^-r^/REPLACE^
16446 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16447 Replace the input source file with the reformatted output, and copy the
16448 original input source into the file whose name is obtained by appending the
16449 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16450 If a file with this name already exists, @command{gnatpp} terminates without
16451 reading or processing the input file.
16452
16453 @item ^-rf^/OVERRIDING_REPLACE^
16454 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16455 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16456 already exists, it is overwritten.
16457
16458 @item ^-rnb^/REPLACE_NO_BACKUP^
16459 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16460 Replace the input source file with the reformatted output without
16461 creating any backup copy of the input source.
16462
16463 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16464 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16465 Specifies the format of the reformatted output file. The @var{xxx}
16466 ^string specified with the switch^option^ may be either
16467 @itemize @bullet
16468 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16469 @item ``@option{^crlf^CRLF^}''
16470 the same as @option{^crlf^CRLF^}
16471 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16472 @item ``@option{^lf^LF^}''
16473 the same as @option{^unix^UNIX^}
16474 @end itemize
16475
16476 @item ^-W^/RESULT_ENCODING=^@var{e}
16477 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16478 Specify the wide character encoding method used to write the code in the
16479 result file
16480 @var{e} is one of the following:
16481
16482 @itemize @bullet
16483
16484 @item ^h^HEX^
16485 Hex encoding
16486
16487 @item ^u^UPPER^
16488 Upper half encoding
16489
16490 @item ^s^SHIFT_JIS^
16491 Shift/JIS encoding
16492
16493 @item ^e^EUC^
16494 EUC encoding
16495
16496 @item ^8^UTF8^
16497 UTF-8 encoding
16498
16499 @item ^b^BRACKETS^
16500 Brackets encoding (default value)
16501 @end itemize
16502
16503 @end table
16504
16505 @noindent
16506 Options @option{^-pipe^/STANDARD_OUTPUT^},
16507 @option{^-o^/OUTPUT^} and
16508 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16509 contains only one file to reformat.
16510 Option
16511 @option{^--eol^/END_OF_LINE^}
16512 and
16513 @option{^-W^/RESULT_ENCODING^}
16514 cannot be used together
16515 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16516
16517 @node Other gnatpp Switches
16518 @subsection Other @code{gnatpp} Switches
16519
16520 @noindent
16521 The additional @command{gnatpp} switches are defined in this subsection.
16522
16523 @table @option
16524 @item ^-files @var{filename}^/FILES=@var{output_file}^
16525 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16526 Take the argument source files from the specified file. This file should be an
16527 ordinary textual file containing file names separated by spaces or
16528 line breaks. You can use this switch more then once in the same call to
16529 @command{gnatpp}. You also can combine this switch with explicit list of
16530 files.
16531
16532 @item ^-v^/VERBOSE^
16533 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16534 Verbose mode;
16535 @command{gnatpp} generates version information and then
16536 a trace of the actions it takes to produce or obtain the ASIS tree.
16537
16538 @item ^-w^/WARNINGS^
16539 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16540 Warning mode;
16541 @command{gnatpp} generates a warning whenever it cannot provide
16542 a required layout in the result source.
16543 @end table
16544
16545 @node Formatting Rules
16546 @section Formatting Rules
16547
16548 @noindent
16549 The following subsections show how @command{gnatpp} treats ``white space'',
16550 comments, program layout, and name casing.
16551 They provide the detailed descriptions of the switches shown above.
16552
16553 @menu
16554 * White Space and Empty Lines::
16555 * Formatting Comments::
16556 * Construct Layout::
16557 * Name Casing::
16558 @end menu
16559
16560 @node White Space and Empty Lines
16561 @subsection White Space and Empty Lines
16562
16563 @noindent
16564 @command{gnatpp} does not have an option to control space characters.
16565 It will add or remove spaces according to the style illustrated by the
16566 examples in the @cite{Ada Reference Manual}.
16567
16568 The only format effectors
16569 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16570 that will appear in the output file are platform-specific line breaks,
16571 and also format effectors within (but not at the end of) comments.
16572 In particular, each horizontal tab character that is not inside
16573 a comment will be treated as a space and thus will appear in the
16574 output file as zero or more spaces depending on
16575 the reformatting of the line in which it appears.
16576 The only exception is a Form Feed character, which is inserted after a
16577 pragma @code{Page} when @option{-ff} is set.
16578
16579 The output file will contain no lines with trailing ``white space'' (spaces,
16580 format effectors).
16581
16582 Empty lines in the original source are preserved
16583 only if they separate declarations or statements.
16584 In such contexts, a
16585 sequence of two or more empty lines is replaced by exactly one empty line.
16586 Note that a blank line will be removed if it separates two ``comment blocks''
16587 (a comment block is a sequence of whole-line comments).
16588 In order to preserve a visual separation between comment blocks, use an
16589 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16590 Likewise, if for some reason you wish to have a sequence of empty lines,
16591 use a sequence of empty comments instead.
16592
16593 @node Formatting Comments
16594 @subsection Formatting Comments
16595
16596 @noindent
16597 Comments in Ada code are of two kinds:
16598 @itemize @bullet
16599 @item
16600 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16601 ``white space'') on a line
16602
16603 @item
16604 an @emph{end-of-line comment}, which follows some other Ada lexical element
16605 on the same line.
16606 @end itemize
16607
16608 @noindent
16609 The indentation of a whole-line comment is that of either
16610 the preceding or following line in
16611 the formatted source, depending on switch settings as will be described below.
16612
16613 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16614 between the end of the preceding Ada lexical element and the beginning
16615 of the comment as appear in the original source,
16616 unless either the comment has to be split to
16617 satisfy the line length limitation, or else the next line contains a
16618 whole line comment that is considered a continuation of this end-of-line
16619 comment (because it starts at the same position).
16620 In the latter two
16621 cases, the start of the end-of-line comment is moved right to the nearest
16622 multiple of the indentation level.
16623 This may result in a ``line overflow'' (the right-shifted comment extending
16624 beyond the maximum line length), in which case the comment is split as
16625 described below.
16626
16627 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16628 (GNAT-style comment line indentation)
16629 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16630 (reference-manual comment line indentation).
16631 With reference-manual style, a whole-line comment is indented as if it
16632 were a declaration or statement at the same place
16633 (i.e., according to the indentation of the preceding line(s)).
16634 With GNAT style, a whole-line comment that is immediately followed by an
16635 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16636 word @b{begin}, is indented based on the construct that follows it.
16637
16638 For example:
16639 @smallexample @c ada
16640 @cartouche
16641 if A then
16642     null;
16643        -- some comment
16644 else
16645    null;
16646 end if;
16647 @end cartouche
16648 @end smallexample
16649
16650 @noindent
16651 Reference-manual indentation produces:
16652
16653 @smallexample @c ada
16654 @cartouche
16655 if A then
16656    null;
16657    --  some comment
16658 else
16659    null;
16660 end if;
16661 @end cartouche
16662 @end smallexample
16663
16664 @noindent
16665 while GNAT-style indentation produces:
16666
16667 @smallexample @c ada
16668 @cartouche
16669 if A then
16670    null;
16671 --  some comment
16672 else
16673    null;
16674 end if;
16675 @end cartouche
16676 @end smallexample
16677
16678 @noindent
16679 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16680 (GNAT style comment beginning) has the following
16681 effect:
16682
16683 @itemize @bullet
16684 @item
16685 For each whole-line comment that does not end with two hyphens,
16686 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16687 to ensure that there are at least two spaces between these hyphens and the
16688 first non-blank character of the comment.
16689 @end itemize
16690
16691 @noindent
16692 For an end-of-line comment, if in the original source the next line is a
16693 whole-line comment that starts at the same position
16694 as the end-of-line comment,
16695 then the whole-line comment (and all whole-line comments
16696 that follow it and that start at the same position)
16697 will start at this position in the output file.
16698
16699 @noindent
16700 That is, if in the original source we have:
16701
16702 @smallexample @c ada
16703 @cartouche
16704 begin
16705 A := B + C;            --  B must be in the range Low1..High1
16706                        --  C must be in the range Low2..High2
16707              --B+C will be in the range Low1+Low2..High1+High2
16708 X := X + 1;
16709 @end cartouche
16710 @end smallexample
16711
16712 @noindent
16713 Then in the formatted source we get
16714
16715 @smallexample @c ada
16716 @cartouche
16717 begin
16718    A := B + C;            --  B must be in the range Low1..High1
16719                           --  C must be in the range Low2..High2
16720    --  B+C will be in the range Low1+Low2..High1+High2
16721    X := X + 1;
16722 @end cartouche
16723 @end smallexample
16724
16725 @noindent
16726 A comment that exceeds the line length limit will be split.
16727 Unless switch
16728 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16729 the line belongs to a reformattable block, splitting the line generates a
16730 @command{gnatpp} warning.
16731 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16732 comments may be reformatted in typical
16733 word processor style (that is, moving words between lines and putting as
16734 many words in a line as possible).
16735
16736 @noindent
16737 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16738 that has a special format (that is, a character that is neither a letter nor digit
16739 not white space nor line break immediately following the leading @code{--} of
16740 the comment) should be without any change moved from the argument source
16741 into reformatted source. This switch allows to preserve comments that are used
16742 as a special marks in the code (e.g.@: SPARK annotation).
16743
16744 @node Construct Layout
16745 @subsection Construct Layout
16746
16747 @noindent
16748 In several cases the suggested layout in the Ada Reference Manual includes
16749 an extra level of indentation that many programmers prefer to avoid. The
16750 affected cases include:
16751
16752 @itemize @bullet
16753
16754 @item Record type declaration (RM 3.8)
16755
16756 @item Record representation clause (RM 13.5.1)
16757
16758 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16759
16760 @item Block statement in case if a block has a statement identifier (RM 5.6)
16761 @end itemize
16762
16763 @noindent
16764 In compact mode (when GNAT style layout or compact layout is set),
16765 the pretty printer uses one level of indentation instead
16766 of two. This is achieved in the record definition and record representation
16767 clause cases by putting the @code{record} keyword on the same line as the
16768 start of the declaration or representation clause, and in the block and loop
16769 case by putting the block or loop header on the same line as the statement
16770 identifier.
16771
16772 @noindent
16773 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16774 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16775 layout on the one hand, and uncompact layout
16776 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16777 can be illustrated by the following examples:
16778
16779 @iftex
16780 @cartouche
16781 @multitable @columnfractions .5 .5
16782 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16783
16784 @item
16785 @smallexample @c ada
16786 type q is record
16787    a : integer;
16788    b : integer;
16789 end record;
16790 @end smallexample
16791 @tab
16792 @smallexample @c ada
16793 type q is
16794    record
16795       a : integer;
16796       b : integer;
16797    end record;
16798 @end smallexample
16799
16800 @item
16801 @smallexample @c ada
16802 for q use record
16803    a at 0 range  0 .. 31;
16804    b at 4 range  0 .. 31;
16805 end record;
16806 @end smallexample
16807 @tab
16808 @smallexample @c ada
16809 for q use
16810    record
16811       a at 0 range  0 .. 31;
16812       b at 4 range  0 .. 31;
16813    end record;
16814 @end smallexample
16815
16816 @item
16817 @smallexample @c ada
16818 Block : declare
16819    A : Integer := 3;
16820 begin
16821    Proc (A, A);
16822 end Block;
16823 @end smallexample
16824 @tab
16825 @smallexample @c ada
16826 Block :
16827    declare
16828       A : Integer := 3;
16829    begin
16830       Proc (A, A);
16831    end Block;
16832 @end smallexample
16833
16834 @item
16835 @smallexample @c ada
16836 Clear : for J in 1 .. 10 loop
16837    A (J) := 0;
16838 end loop Clear;
16839 @end smallexample
16840 @tab
16841 @smallexample @c ada
16842 Clear :
16843    for J in 1 .. 10 loop
16844       A (J) := 0;
16845    end loop Clear;
16846 @end smallexample
16847 @end multitable
16848 @end cartouche
16849 @end iftex
16850
16851 @ifnottex
16852 @smallexample
16853 @cartouche
16854 GNAT style, compact layout              Uncompact layout
16855
16856 type q is record                        type q is
16857    a : integer;                            record
16858    b : integer;                               a : integer;
16859 end record;                                   b : integer;
16860                                            end record;
16861
16862 for q use record                        for q use
16863    a at 0 range  0 .. 31;                  record
16864    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16865 end record;                                   b at 4 range  0 .. 31;
16866                                            end record;
16867
16868 Block : declare                         Block :
16869    A : Integer := 3;                       declare
16870 begin                                         A : Integer := 3;
16871    Proc (A, A);                            begin
16872 end Block;                                    Proc (A, A);
16873                                            end Block;
16874
16875 Clear : for J in 1 .. 10 loop           Clear :
16876    A (J) := 0;                             for J in 1 .. 10 loop
16877 end loop Clear;                               A (J) := 0;
16878                                            end loop Clear;
16879 @end cartouche
16880 @end smallexample
16881 @end ifnottex
16882
16883 @noindent
16884 A further difference between GNAT style layout and compact layout is that
16885 GNAT style layout inserts empty lines as separation for
16886 compound statements, return statements and bodies.
16887
16888 Note that the layout specified by
16889 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16890 for named block and loop statements overrides the layout defined by these
16891 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16892 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16893 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16894
16895 @node Name Casing
16896 @subsection Name Casing
16897
16898 @noindent
16899 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16900 the same casing as the corresponding defining identifier.
16901
16902 You control the casing for defining occurrences via the
16903 @option{^-n^/NAME_CASING^} switch.
16904 @ifclear vms
16905 With @option{-nD} (``as declared'', which is the default),
16906 @end ifclear
16907 @ifset vms
16908 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16909 @end ifset
16910 defining occurrences appear exactly as in the source file
16911 where they are declared.
16912 The other ^values for this switch^options for this qualifier^ ---
16913 @option{^-nU^UPPER_CASE^},
16914 @option{^-nL^LOWER_CASE^},
16915 @option{^-nM^MIXED_CASE^} ---
16916 result in
16917 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16918 If @command{gnatpp} changes the casing of a defining
16919 occurrence, it analogously changes the casing of all the
16920 usage occurrences of this name.
16921
16922 If the defining occurrence of a name is not in the source compilation unit
16923 currently being processed by @command{gnatpp}, the casing of each reference to
16924 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16925 switch (subject to the dictionary file mechanism described below).
16926 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
16927 had affected the
16928 casing for the defining occurrence of the name.
16929
16930 Some names may need to be spelled with casing conventions that are not
16931 covered by the upper-, lower-, and mixed-case transformations.
16932 You can arrange correct casing by placing such names in a
16933 @emph{dictionary file},
16934 and then supplying a @option{^-D^/DICTIONARY^} switch.
16935 The casing of names from dictionary files overrides
16936 any @option{^-n^/NAME_CASING^} switch.
16937
16938 To handle the casing of Ada predefined names and the names from GNAT libraries,
16939 @command{gnatpp} assumes a default dictionary file.
16940 The name of each predefined entity is spelled with the same casing as is used
16941 for the entity in the @cite{Ada Reference Manual}.
16942 The name of each entity in the GNAT libraries is spelled with the same casing
16943 as is used in the declaration of that entity.
16944
16945 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
16946 default dictionary file.
16947 Instead, the casing for predefined and GNAT-defined names will be established
16948 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
16949 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
16950 will appear as just shown,
16951 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
16952 To ensure that even such names are rendered in uppercase,
16953 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
16954 (or else, less conveniently, place these names in upper case in a dictionary
16955 file).
16956
16957 A dictionary file is
16958 a plain text file; each line in this file can be either a blank line
16959 (containing only space characters and ASCII.HT characters), an Ada comment
16960 line, or the specification of exactly one @emph{casing schema}.
16961
16962 A casing schema is a string that has the following syntax:
16963
16964 @smallexample
16965 @cartouche
16966   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
16967
16968   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
16969 @end cartouche
16970 @end smallexample
16971
16972 @noindent
16973 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
16974 @var{identifier} lexical element and the @var{letter_or_digit} category.)
16975
16976 The casing schema string can be followed by white space and/or an Ada-style
16977 comment; any amount of white space is allowed before the string.
16978
16979 If a dictionary file is passed as
16980 @ifclear vms
16981 the value of a @option{-D@var{file}} switch
16982 @end ifclear
16983 @ifset vms
16984 an option to the @option{/DICTIONARY} qualifier
16985 @end ifset
16986 then for every
16987 simple name and every identifier, @command{gnatpp} checks if the dictionary
16988 defines the casing for the name or for some of its parts (the term ``subword''
16989 is used below to denote the part of a name which is delimited by ``_'' or by
16990 the beginning or end of the word and which does not contain any ``_'' inside):
16991
16992 @itemize @bullet
16993 @item
16994 if the whole name is in the dictionary, @command{gnatpp} uses for this name
16995 the casing defined by the dictionary; no subwords are checked for this word
16996
16997 @item
16998 for every subword @command{gnatpp} checks if the dictionary contains the
16999 corresponding string of the form @code{*@var{simple_identifier}*},
17000 and if it does, the casing of this @var{simple_identifier} is used
17001 for this subword
17002
17003 @item
17004 if the whole name does not contain any ``_'' inside, and if for this name
17005 the dictionary contains two entries - one of the form @var{identifier},
17006 and another - of the form *@var{simple_identifier}*, then the first one
17007 is applied to define the casing of this name
17008
17009 @item
17010 if more than one dictionary file is passed as @command{gnatpp} switches, each
17011 dictionary adds new casing exceptions and overrides all the existing casing
17012 exceptions set by the previous dictionaries
17013
17014 @item
17015 when @command{gnatpp} checks if the word or subword is in the dictionary,
17016 this check is not case sensitive
17017 @end itemize
17018
17019 @noindent
17020 For example, suppose we have the following source to reformat:
17021
17022 @smallexample @c ada
17023 @cartouche
17024 procedure test is
17025    name1 : integer := 1;
17026    name4_name3_name2 : integer := 2;
17027    name2_name3_name4 : Boolean;
17028    name1_var : Float;
17029 begin
17030    name2_name3_name4 := name4_name3_name2 > name1;
17031 end;
17032 @end cartouche
17033 @end smallexample
17034
17035 @noindent
17036 And suppose we have two dictionaries:
17037
17038 @smallexample
17039 @cartouche
17040 @i{dict1:}
17041    NAME1
17042    *NaMe3*
17043    *Name1*
17044 @end cartouche
17045
17046 @cartouche
17047 @i{dict2:}
17048   *NAME3*
17049 @end cartouche
17050 @end smallexample
17051
17052 @noindent
17053 If @command{gnatpp} is called with the following switches:
17054
17055 @smallexample
17056 @ifclear vms
17057 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
17058 @end ifclear
17059 @ifset vms
17060 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
17061 @end ifset
17062 @end smallexample
17063
17064 @noindent
17065 then we will get the following name casing in the @command{gnatpp} output:
17066
17067 @smallexample @c ada
17068 @cartouche
17069 procedure Test is
17070    NAME1             : Integer := 1;
17071    Name4_NAME3_Name2 : Integer := 2;
17072    Name2_NAME3_Name4 : Boolean;
17073    Name1_Var         : Float;
17074 begin
17075    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
17076 end Test;
17077 @end cartouche
17078 @end smallexample
17079
17080 @c *********************************
17081 @node The GNAT Metric Tool gnatmetric
17082 @chapter The GNAT Metric Tool @command{gnatmetric}
17083 @findex gnatmetric
17084 @cindex Metric tool
17085
17086 @noindent
17087 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
17088 for computing various program metrics.
17089 It takes an Ada source file as input and generates a file containing the
17090 metrics data as output. Various switches control which
17091 metrics are computed and output.
17092
17093 @command{gnatmetric} generates and uses the ASIS
17094 tree for the input source and thus requires the input to be syntactically and
17095 semantically legal.
17096 If this condition is not met, @command{gnatmetric} will generate
17097 an error message; no metric information for this file will be
17098 computed and reported.
17099
17100 If the compilation unit contained in the input source depends semantically
17101 upon units in files located outside the current directory, you have to provide
17102 the source search path when invoking @command{gnatmetric}.
17103 If it depends semantically upon units that are contained
17104 in files with names that do not follow the GNAT file naming rules, you have to
17105 provide the configuration file describing the corresponding naming scheme (see
17106 the description of the @command{gnatmetric} switches below.)
17107 Alternatively, you may use a project file and invoke @command{gnatmetric}
17108 through the @command{gnat} driver.
17109
17110 The @command{gnatmetric} command has the form
17111
17112 @smallexample
17113 $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17114 @end smallexample
17115
17116 @noindent
17117 where
17118 @itemize @bullet
17119 @item
17120 @var{switches} specify the metrics to compute and define the destination for
17121 the output
17122
17123 @item
17124 Each @var{filename} is the name (including the extension) of a source
17125 file to process. ``Wildcards'' are allowed, and
17126 the file name may contain path information.
17127 If no @var{filename} is supplied, then the @var{switches} list must contain
17128 at least one
17129 @option{-files} switch (@pxref{Other gnatmetric Switches}).
17130 Including both a @option{-files} switch and one or more
17131 @var{filename} arguments is permitted.
17132
17133 @item
17134 @samp{-cargs @var{gcc_switches}} is a list of switches for
17135 @command{gcc}. They will be passed on to all compiler invocations made by
17136 @command{gnatmetric} to generate the ASIS trees. Here you can provide
17137 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17138 and use the @option{-gnatec} switch to set the configuration file.
17139 @end itemize
17140
17141 @menu
17142 * Switches for gnatmetric::
17143 @end menu
17144
17145 @node Switches for gnatmetric
17146 @section Switches for @command{gnatmetric}
17147
17148 @noindent
17149 The following subsections describe the various switches accepted by
17150 @command{gnatmetric}, organized by category.
17151
17152 @menu
17153 * Output Files Control::
17154 * Disable Metrics For Local Units::
17155 * Specifying a set of metrics to compute::
17156 * Other gnatmetric Switches::
17157 * Generate project-wide metrics::
17158 @end menu
17159
17160 @node Output Files Control
17161 @subsection Output File Control
17162 @cindex Output file control in @command{gnatmetric}
17163
17164 @noindent
17165 @command{gnatmetric} has two output formats. It can generate a
17166 textual (human-readable) form, and also XML. By default only textual
17167 output is generated.
17168
17169 When generating the output in textual form, @command{gnatmetric} creates
17170 for each Ada source file a corresponding text file
17171 containing the computed metrics, except for the case when the set of metrics
17172 specified by gnatmetric parameters consists only of metrics that are computed
17173 for the whole set of analyzed sources, but not for each Ada source.
17174 By default, this file is placed in the same directory as where the source
17175 file is located, and its name is obtained
17176 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
17177 input file.
17178
17179 All the output information generated in XML format is placed in a single
17180 file. By default this file is placed in the current directory and has the
17181 name ^@file{metrix.xml}^@file{METRIX$XML}^.
17182
17183 Some of the computed metrics are summed over the units passed to
17184 @command{gnatmetric}; for example, the total number of lines of code.
17185 By default this information is sent to @file{stdout}, but a file
17186 can be specified with the @option{-og} switch.
17187
17188 The following switches control the @command{gnatmetric} output:
17189
17190 @table @option
17191 @cindex @option{^-x^/XML^} (@command{gnatmetric})
17192 @item ^-x^/XML^
17193 Generate the XML output
17194
17195 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
17196 @item ^-xs^/XSD^
17197 Generate the XML output and the XML schema file that describes the structure
17198 of the XML metric report, this schema is assigned to the XML file. The schema
17199 file has the same name as the XML output file with @file{.xml} suffix replaced
17200 with @file{.xsd}
17201
17202 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
17203 @item ^-nt^/NO_TEXT^
17204 Do not generate the output in text form (implies @option{^-x^/XML^})
17205
17206 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
17207 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
17208 Put textual files with detailed metrics into @var{output_dir}
17209
17210 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
17211 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
17212 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
17213 in the name of the output file.
17214
17215 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
17216 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
17217 Put global metrics into @var{file_name}
17218
17219 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
17220 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
17221 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
17222
17223 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
17224 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
17225 Use ``short'' source file names in the output.  (The @command{gnatmetric}
17226 output includes the name(s) of the Ada source file(s) from which the metrics
17227 are computed.  By default each name includes the absolute path. The
17228 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
17229 to exclude all directory information from the file names that are output.)
17230
17231 @end table
17232
17233 @node Disable Metrics For Local Units
17234 @subsection Disable Metrics For Local Units
17235 @cindex Disable Metrics For Local Units in @command{gnatmetric}
17236
17237 @noindent
17238 @command{gnatmetric} relies on the GNAT compilation model @minus{}
17239 one compilation
17240 unit per one source file. It computes line metrics for the whole source
17241 file, and it also computes syntax
17242 and complexity metrics for the file's outermost unit.
17243
17244 By default, @command{gnatmetric} will also compute all metrics for certain
17245 kinds of locally declared program units:
17246
17247 @itemize @bullet
17248 @item
17249 subprogram (and generic subprogram) bodies;
17250
17251 @item
17252 package (and generic package) specs and bodies;
17253
17254 @item
17255 task object and type specifications and bodies;
17256
17257 @item
17258 protected object and type specifications and bodies.
17259 @end itemize
17260
17261 @noindent
17262 These kinds of entities will be referred to as
17263 @emph{eligible local program units}, or simply @emph{eligible local units},
17264 @cindex Eligible local unit (for @command{gnatmetric})
17265 in the discussion below.
17266
17267 Note that a subprogram declaration, generic instantiation,
17268 or renaming declaration only receives metrics
17269 computation when it appear as the outermost entity
17270 in a source file.
17271
17272 Suppression of metrics computation for eligible local units can be
17273 obtained via the following switch:
17274
17275 @table @option
17276 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
17277 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
17278 Do not compute detailed metrics for eligible local program units
17279
17280 @end table
17281
17282 @node Specifying a set of metrics to compute
17283 @subsection Specifying a set of metrics to compute
17284
17285 @noindent
17286 By default all the metrics are computed and reported. The switches
17287 described in this subsection allow you to control, on an individual
17288 basis, whether metrics are computed and
17289 reported. If at least one positive metric
17290 switch is specified (that is, a switch that defines that a given
17291 metric or set of metrics is to be computed), then only
17292 explicitly specified metrics are reported.
17293
17294 @menu
17295 * Line Metrics Control::
17296 * Syntax Metrics Control::
17297 * Complexity Metrics Control::
17298 * Object-Oriented Metrics Control::
17299 @end menu
17300
17301 @node Line Metrics Control
17302 @subsubsection Line Metrics Control
17303 @cindex Line metrics control in @command{gnatmetric}
17304
17305 @noindent
17306 For any (legal) source file, and for each of its
17307 eligible local program units, @command{gnatmetric} computes the following
17308 metrics:
17309
17310 @itemize @bullet
17311 @item
17312 the total number of lines;
17313
17314 @item
17315 the total number of code lines (i.e., non-blank lines that are not comments)
17316
17317 @item
17318 the number of comment lines
17319
17320 @item
17321 the number of code lines containing end-of-line comments;
17322
17323 @item
17324 the comment percentage: the ratio between the number of lines that contain
17325 comments and the number of all non-blank lines, expressed as a percentage;
17326
17327 @item
17328 the number of empty lines and lines containing only space characters and/or
17329 format effectors (blank lines)
17330
17331 @item
17332 the average number of code lines in subprogram bodies, task bodies, entry
17333 bodies and statement sequences in package bodies (this metric is only computed
17334 across the whole set of the analyzed units)
17335
17336 @end itemize
17337
17338 @noindent
17339 @command{gnatmetric} sums the values of the line metrics for all the
17340 files being processed and then generates the cumulative results. The tool
17341 also computes for all the files being processed the average number of code
17342 lines in bodies.
17343
17344 You can use the following switches to select the specific line metrics
17345 to be computed and reported.
17346
17347 @table @option
17348 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17349
17350 @ifclear vms
17351 @cindex @option{--no-lines@var{x}}
17352 @end ifclear
17353
17354 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
17355 Report all the line metrics
17356
17357 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
17358 Do not report any of line metrics
17359
17360 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
17361 Report the number of all lines
17362
17363 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
17364 Do not report the number of all lines
17365
17366 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
17367 Report the number of code lines
17368
17369 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
17370 Do not report the number of code lines
17371
17372 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
17373 Report the number of comment lines
17374
17375 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
17376 Do not report the number of comment lines
17377
17378 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
17379 Report the number of code lines containing
17380 end-of-line comments
17381
17382 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
17383 Do not report the number of code lines containing
17384 end-of-line comments
17385
17386 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
17387 Report the comment percentage in the program text
17388
17389 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
17390 Do not report the comment percentage in the program text
17391
17392 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
17393 Report the number of blank lines
17394
17395 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
17396 Do not report the number of blank lines
17397
17398 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
17399 Report the average number of code lines in subprogram bodies, task bodies,
17400 entry bodies and statement sequences in package bodies. The metric is computed
17401 and reported for the whole set of processed Ada sources only.
17402
17403 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
17404 Do not report the average number of code lines in subprogram bodies,
17405 task bodies, entry bodies and statement sequences in package bodies.
17406
17407 @end table
17408
17409 @node Syntax Metrics Control
17410 @subsubsection Syntax Metrics Control
17411 @cindex Syntax metrics control in @command{gnatmetric}
17412
17413 @noindent
17414 @command{gnatmetric} computes various syntactic metrics for the
17415 outermost unit and for each eligible local unit:
17416
17417 @table @emph
17418 @item LSLOC (``Logical Source Lines Of Code'')
17419 The total number of declarations and the total number of statements
17420
17421 @item Maximal static nesting level of inner program units
17422 According to
17423 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17424 package, a task unit, a protected unit, a
17425 protected entry, a generic unit, or an explicitly declared subprogram other
17426 than an enumeration literal.''
17427
17428 @item Maximal nesting level of composite syntactic constructs
17429 This corresponds to the notion of the
17430 maximum nesting level in the GNAT built-in style checks
17431 (@pxref{Style Checking})
17432 @end table
17433
17434 @noindent
17435 For the outermost unit in the file, @command{gnatmetric} additionally computes
17436 the following metrics:
17437
17438 @table @emph
17439 @item Public subprograms
17440 This metric is computed for package specs. It is the
17441 number of subprograms and generic subprograms declared in the visible
17442 part (including the visible part of nested packages, protected objects, and
17443 protected types).
17444
17445 @item All subprograms
17446 This metric is computed for bodies and subunits. The
17447 metric is equal to a total number of subprogram bodies in the compilation
17448 unit.
17449 Neither generic instantiations nor renamings-as-a-body nor body stubs
17450 are counted. Any subprogram body is counted, independently of its nesting
17451 level and enclosing constructs. Generic bodies and bodies of protected
17452 subprograms are counted in the same way as ``usual'' subprogram bodies.
17453
17454 @item Public types
17455 This metric is computed for package specs and
17456 generic package declarations. It is the total number of types
17457 that can be referenced from outside this compilation unit, plus the
17458 number of types from all the visible parts of all the visible generic
17459 packages. Generic formal types are not counted.  Only types, not subtypes,
17460 are included.
17461
17462 @noindent
17463 Along with the total number of public types, the following
17464 types are counted and reported separately:
17465
17466 @itemize @bullet
17467 @item
17468 Abstract types
17469
17470 @item
17471 Root tagged types (abstract, non-abstract, private, non-private). Type
17472 extensions are @emph{not} counted
17473
17474 @item
17475 Private types (including private extensions)
17476
17477 @item
17478 Task types
17479
17480 @item
17481 Protected types
17482
17483 @end itemize
17484
17485 @item All types
17486 This metric is computed for any compilation unit. It is equal to the total
17487 number of the declarations of different types given in the compilation unit.
17488 The private and the corresponding full type declaration are counted as one
17489 type declaration. Incomplete type declarations and generic formal types
17490 are not counted.
17491 No distinction is made among different kinds of types (abstract,
17492 private etc.); the total number of types is computed and reported.
17493
17494 @end table
17495
17496 @noindent
17497 By default, all the syntax metrics are computed and reported. You can use the
17498 following switches to select specific syntax metrics.
17499
17500 @table @option
17501
17502 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17503
17504 @ifclear vms
17505 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17506 @end ifclear
17507
17508 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
17509 Report all the syntax metrics
17510
17511 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
17512 Do not report any of syntax metrics
17513
17514 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
17515 Report the total number of declarations
17516
17517 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
17518 Do not report the total number of declarations
17519
17520 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
17521 Report the total number of statements
17522
17523 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
17524 Do not report the total number of statements
17525
17526 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
17527 Report the number of public subprograms in a compilation unit
17528
17529 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
17530 Do not report the number of public subprograms in a compilation unit
17531
17532 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
17533 Report the number of all the subprograms in a compilation unit
17534
17535 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
17536 Do not report the number of all the subprograms in a compilation unit
17537
17538 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
17539 Report the number of public types in a compilation unit
17540
17541 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
17542 Do not report the number of public types in a compilation unit
17543
17544 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
17545 Report the number of all the types in a compilation unit
17546
17547 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
17548 Do not report the number of all the types in a compilation unit
17549
17550 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
17551 Report the maximal program unit nesting level
17552
17553 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17554 Do not report the maximal program unit nesting level
17555
17556 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
17557 Report the maximal construct nesting level
17558
17559 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
17560 Do not report the maximal construct nesting level
17561
17562 @end table
17563
17564 @node Complexity Metrics Control
17565 @subsubsection Complexity Metrics Control
17566 @cindex Complexity metrics control in @command{gnatmetric}
17567
17568 @noindent
17569 For a program unit that is an executable body (a subprogram body (including
17570 generic bodies), task body, entry body or a package body containing
17571 its own statement sequence) @command{gnatmetric} computes the following
17572 complexity metrics:
17573
17574 @itemize @bullet
17575 @item
17576 McCabe cyclomatic complexity;
17577
17578 @item
17579 McCabe essential complexity;
17580
17581 @item
17582 maximal loop nesting level
17583
17584 @end itemize
17585
17586 @noindent
17587 The McCabe complexity metrics are defined
17588 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17589
17590 According to McCabe, both control statements and short-circuit control forms
17591 should be taken into account when computing cyclomatic complexity. For each
17592 body, we compute three metric values:
17593
17594 @itemize @bullet
17595 @item
17596 the complexity introduced by control
17597 statements only, without taking into account short-circuit forms,
17598
17599 @item
17600 the complexity introduced by short-circuit control forms only, and
17601
17602 @item
17603 the total
17604 cyclomatic complexity, which is the sum of these two values.
17605 @end itemize
17606
17607 @noindent
17608 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17609 the code in the exception handlers and in all the nested program units.
17610
17611 By default, all the complexity metrics are computed and reported.
17612 For more fine-grained control you can use
17613 the following switches:
17614
17615 @table @option
17616 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17617
17618 @ifclear vms
17619 @cindex @option{--no-complexity@var{x}}
17620 @end ifclear
17621
17622 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
17623 Report all the complexity metrics
17624
17625 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
17626 Do not report any of complexity metrics
17627
17628 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
17629 Report the McCabe Cyclomatic Complexity
17630
17631 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
17632 Do not report the McCabe Cyclomatic Complexity
17633
17634 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
17635 Report the Essential Complexity
17636
17637 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
17638 Do not report the Essential Complexity
17639
17640 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17641 Report maximal loop nesting level
17642
17643 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
17644 Do not report maximal loop nesting level
17645
17646 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
17647 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17648 task bodies, entry bodies and statement sequences in package bodies.
17649 The metric is computed and reported for whole set of processed Ada sources
17650 only.
17651
17652 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
17653 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17654 bodies, task bodies, entry bodies and statement sequences in package bodies
17655
17656 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17657 @item ^-ne^/NO_EXITS_AS_GOTOS^
17658 Do not consider @code{exit} statements as @code{goto}s when
17659 computing Essential Complexity
17660
17661 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
17662 Report the extra exit points for subprogram bodies. As an exit point, this
17663 metric counts @code{return} statements and raise statements in case when the
17664 raised exception is not handled in the same body. In case of a function this
17665 metric subtracts 1 from the number of exit points, because a function body
17666 must contain at least one @code{return} statement.
17667
17668 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
17669 Do not report the extra exit points for subprogram bodies
17670 @end table
17671
17672
17673 @node Object-Oriented Metrics Control
17674 @subsubsection Object-Oriented Metrics Control
17675 @cindex Object-Oriented metrics control in @command{gnatmetric}
17676
17677 @noindent
17678 @cindex Coupling metrics (in in @command{gnatmetric})
17679 Coupling metrics are object-oriented metrics that measure the
17680 dependencies between a given class (or a group of classes) and the
17681 ``external world'' (that is, the other classes in the program). In this
17682 subsection the term ``class'' is used in its
17683 traditional object-oriented programming sense
17684 (an instantiable module that contains data and/or method members).
17685 A @emph{category} (of classes)
17686 is a group of closely related classes that are reused and/or
17687 modified together.
17688
17689 A class @code{K}'s @emph{efferent coupling} is the number of classes
17690 that @code{K} depends upon.
17691 A category's efferent coupling is the number of classes outside the
17692 category that the classes inside the category depend upon.
17693
17694 A class @code{K}'s @emph{afferent coupling} is the number of classes
17695 that depend upon @code{K}.
17696 A category's afferent coupling is the number of classes outside the
17697 category that depend on classes belonging to the category.
17698
17699 Ada's implementation of the object-oriented paradigm does not use the
17700 traditional class notion, so the definition of the coupling
17701 metrics for Ada maps the class and class category notions
17702 onto Ada constructs.
17703
17704 For the coupling metrics, several kinds of modules -- a library package,
17705 a library generic package, and a library generic package instantiation --
17706 that define a tagged type or an interface type are
17707 considered to be a class. A category consists of a library package (or
17708 a library generic package) that defines a tagged or an interface type,
17709 together with all its descendant (generic) packages that define tagged
17710 or interface types. For any package counted as a class,
17711 its body and subunits (if any) are considered
17712 together with its spec when counting the dependencies, and coupling
17713 metrics are reported for spec units only. For dependencies
17714 between classes, the Ada semantic dependencies are considered.
17715 For coupling metrics, only dependencies on units that are considered as
17716 classes, are considered.
17717
17718 When computing coupling metrics, @command{gnatmetric} counts only
17719 dependencies between units that are arguments of the gnatmetric call.
17720 Coupling metrics are program-wide (or project-wide) metrics, so to
17721 get a valid result, you should call @command{gnatmetric} for
17722 the whole set of sources that make up your program. It can be done
17723 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17724 option (see See @ref{The GNAT Driver and Project Files} for details.
17725
17726 By default, all the coupling metrics are disabled. You can use the following
17727 switches to specify the coupling metrics to be computed and reported:
17728
17729 @table @option
17730
17731 @ifclear vms
17732 @cindex @option{--package@var{x}} (@command{gnatmetric})
17733 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17734 @cindex @option{--category@var{x}} (@command{gnatmetric})
17735 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17736 @end ifclear
17737
17738 @ifset vms
17739 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17740 @end ifset
17741
17742 @item ^--coupling-all^/COUPLING_METRICS=ALL^
17743 Report all the coupling metrics
17744
17745 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
17746 Do not report any of  metrics
17747
17748 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
17749 Report package efferent coupling
17750
17751 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
17752 Do not report package efferent coupling
17753
17754 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
17755 Report package afferent coupling
17756
17757 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
17758 Do not report package afferent coupling
17759
17760 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
17761 Report category efferent coupling
17762
17763 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
17764 Do not report category efferent coupling
17765
17766 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
17767 Report category afferent coupling
17768
17769 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
17770 Do not report category afferent coupling
17771
17772 @end table
17773
17774 @node Other gnatmetric Switches
17775 @subsection Other @code{gnatmetric} Switches
17776
17777 @noindent
17778 Additional @command{gnatmetric} switches are as follows:
17779
17780 @table @option
17781 @item ^-files @var{filename}^/FILES=@var{filename}^
17782 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17783 Take the argument source files from the specified file. This file should be an
17784 ordinary text file containing file names separated by spaces or
17785 line breaks. You can use this switch more then once in the same call to
17786 @command{gnatmetric}. You also can combine this switch with
17787 an explicit list of files.
17788
17789 @item ^-v^/VERBOSE^
17790 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17791 Verbose mode;
17792 @command{gnatmetric} generates version information and then
17793 a trace of sources being processed.
17794
17795 @item ^-dv^/DEBUG_OUTPUT^
17796 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17797 Debug mode;
17798 @command{gnatmetric} generates various messages useful to understand what
17799 happens during the metrics computation
17800
17801 @item ^-q^/QUIET^
17802 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17803 Quiet mode.
17804 @end table
17805
17806 @node Generate project-wide metrics
17807 @subsection Generate project-wide metrics
17808
17809 In order to compute metrics on all units of a given project, you can use
17810 the @command{gnat} driver along with the @option{-P} option:
17811 @smallexample
17812    gnat metric -Pproj
17813 @end smallexample
17814
17815 @noindent
17816 If the project @code{proj} depends upon other projects, you can compute
17817 the metrics on the project closure using the @option{-U} option:
17818 @smallexample
17819    gnat metric -Pproj -U
17820 @end smallexample
17821
17822 @noindent
17823 Finally, if not all the units are relevant to a particular main
17824 program in the project closure, you can generate metrics for the set
17825 of units needed to create a given main program (unit closure) using
17826 the @option{-U} option followed by the name of the main unit:
17827 @smallexample
17828    gnat metric -Pproj -U main
17829 @end smallexample
17830
17831
17832 @c ***********************************
17833 @node File Name Krunching Using gnatkr
17834 @chapter File Name Krunching Using @code{gnatkr}
17835 @findex gnatkr
17836
17837 @noindent
17838 This chapter discusses the method used by the compiler to shorten
17839 the default file names chosen for Ada units so that they do not
17840 exceed the maximum length permitted. It also describes the
17841 @code{gnatkr} utility that can be used to determine the result of
17842 applying this shortening.
17843 @menu
17844 * About gnatkr::
17845 * Using gnatkr::
17846 * Krunching Method::
17847 * Examples of gnatkr Usage::
17848 @end menu
17849
17850 @node About gnatkr
17851 @section About @code{gnatkr}
17852
17853 @noindent
17854 The default file naming rule in GNAT
17855 is that the file name must be derived from
17856 the unit name. The exact default rule is as follows:
17857 @itemize @bullet
17858 @item
17859 Take the unit name and replace all dots by hyphens.
17860 @item
17861 If such a replacement occurs in the
17862 second character position of a name, and the first character is
17863 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17864 then replace the dot by the character
17865 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17866 instead of a minus.
17867 @end itemize
17868 The reason for this exception is to avoid clashes
17869 with the standard names for children of System, Ada, Interfaces,
17870 and GNAT, which use the prefixes
17871 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17872 respectively.
17873
17874 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17875 switch of the compiler activates a ``krunching''
17876 circuit that limits file names to nn characters (where nn is a decimal
17877 integer). For example, using OpenVMS,
17878 where the maximum file name length is
17879 39, the value of nn is usually set to 39, but if you want to generate
17880 a set of files that would be usable if ported to a system with some
17881 different maximum file length, then a different value can be specified.
17882 The default value of 39 for OpenVMS need not be specified.
17883
17884 The @code{gnatkr} utility can be used to determine the krunched name for
17885 a given file, when krunched to a specified maximum length.
17886
17887 @node Using gnatkr
17888 @section Using @code{gnatkr}
17889
17890 @noindent
17891 The @code{gnatkr} command has the form
17892
17893 @ifclear vms
17894 @smallexample
17895 $ gnatkr @var{name} @ovar{length}
17896 @end smallexample
17897 @end ifclear
17898
17899 @ifset vms
17900 @smallexample
17901 $ gnatkr @var{name} /COUNT=nn
17902 @end smallexample
17903 @end ifset
17904
17905 @noindent
17906 @var{name} is the uncrunched file name, derived from the name of the unit
17907 in the standard manner described in the previous section (i.e., in particular
17908 all dots are replaced by hyphens). The file name may or may not have an
17909 extension (defined as a suffix of the form period followed by arbitrary
17910 characters other than period). If an extension is present then it will
17911 be preserved in the output. For example, when krunching @file{hellofile.ads}
17912 to eight characters, the result will be hellofil.ads.
17913
17914 Note: for compatibility with previous versions of @code{gnatkr} dots may
17915 appear in the name instead of hyphens, but the last dot will always be
17916 taken as the start of an extension. So if @code{gnatkr} is given an argument
17917 such as @file{Hello.World.adb} it will be treated exactly as if the first
17918 period had been a hyphen, and for example krunching to eight characters
17919 gives the result @file{hellworl.adb}.
17920
17921 Note that the result is always all lower case (except on OpenVMS where it is
17922 all upper case). Characters of the other case are folded as required.
17923
17924 @var{length} represents the length of the krunched name. The default
17925 when no argument is given is ^8^39^ characters. A length of zero stands for
17926 unlimited, in other words do not chop except for system files where the
17927 implied crunching length is always eight characters.
17928
17929 @noindent
17930 The output is the krunched name. The output has an extension only if the
17931 original argument was a file name with an extension.
17932
17933 @node Krunching Method
17934 @section Krunching Method
17935
17936 @noindent
17937 The initial file name is determined by the name of the unit that the file
17938 contains. The name is formed by taking the full expanded name of the
17939 unit and replacing the separating dots with hyphens and
17940 using ^lowercase^uppercase^
17941 for all letters, except that a hyphen in the second character position is
17942 replaced by a ^tilde^dollar sign^ if the first character is
17943 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
17944 The extension is @code{.ads} for a
17945 spec and @code{.adb} for a body.
17946 Krunching does not affect the extension, but the file name is shortened to
17947 the specified length by following these rules:
17948
17949 @itemize @bullet
17950 @item
17951 The name is divided into segments separated by hyphens, tildes or
17952 underscores and all hyphens, tildes, and underscores are
17953 eliminated. If this leaves the name short enough, we are done.
17954
17955 @item
17956 If the name is too long, the longest segment is located (left-most
17957 if there are two of equal length), and shortened by dropping
17958 its last character. This is repeated until the name is short enough.
17959
17960 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
17961 to fit the name into 8 characters as required by some operating systems.
17962
17963 @smallexample
17964 our-strings-wide_fixed 22
17965 our strings wide fixed 19
17966 our string  wide fixed 18
17967 our strin   wide fixed 17
17968 our stri    wide fixed 16
17969 our stri    wide fixe  15
17970 our str     wide fixe  14
17971 our str     wid  fixe  13
17972 our str     wid  fix   12
17973 ou  str     wid  fix   11
17974 ou  st      wid  fix   10
17975 ou  st      wi   fix   9
17976 ou  st      wi   fi    8
17977 Final file name: oustwifi.adb
17978 @end smallexample
17979
17980 @item
17981 The file names for all predefined units are always krunched to eight
17982 characters. The krunching of these predefined units uses the following
17983 special prefix replacements:
17984
17985 @table @file
17986 @item ada-
17987 replaced by @file{^a^A^-}
17988
17989 @item gnat-
17990 replaced by @file{^g^G^-}
17991
17992 @item interfaces-
17993 replaced by @file{^i^I^-}
17994
17995 @item system-
17996 replaced by @file{^s^S^-}
17997 @end table
17998
17999 These system files have a hyphen in the second character position. That
18000 is why normal user files replace such a character with a
18001 ^tilde^dollar sign^, to
18002 avoid confusion with system file names.
18003
18004 As an example of this special rule, consider
18005 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
18006
18007 @smallexample
18008 ada-strings-wide_fixed 22
18009 a-  strings wide fixed 18
18010 a-  string  wide fixed 17
18011 a-  strin   wide fixed 16
18012 a-  stri    wide fixed 15
18013 a-  stri    wide fixe  14
18014 a-  str     wide fixe  13
18015 a-  str     wid  fixe  12
18016 a-  str     wid  fix   11
18017 a-  st      wid  fix   10
18018 a-  st      wi   fix   9
18019 a-  st      wi   fi    8
18020 Final file name: a-stwifi.adb
18021 @end smallexample
18022 @end itemize
18023
18024 Of course no file shortening algorithm can guarantee uniqueness over all
18025 possible unit names, and if file name krunching is used then it is your
18026 responsibility to ensure that no name clashes occur. The utility
18027 program @code{gnatkr} is supplied for conveniently determining the
18028 krunched name of a file.
18029
18030 @node Examples of gnatkr Usage
18031 @section Examples of @code{gnatkr} Usage
18032
18033 @smallexample
18034 @iftex
18035 @leftskip=0cm
18036 @end iftex
18037 @ifclear vms
18038 $ gnatkr very_long_unit_name.ads      --> velounna.ads
18039 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
18040 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
18041 $ gnatkr grandparent-parent-child     --> grparchi
18042 @end ifclear
18043 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
18044 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
18045 @end smallexample
18046
18047 @node Preprocessing Using gnatprep
18048 @chapter Preprocessing Using @code{gnatprep}
18049 @findex gnatprep
18050
18051 @noindent
18052 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
18053 preprocessing.
18054 Although designed for use with GNAT, @code{gnatprep} does not depend on any
18055 special GNAT features.
18056 For further discussion of conditional compilation in general, see
18057 @ref{Conditional Compilation}.
18058
18059 @menu
18060 * Preprocessing Symbols::
18061 * Using gnatprep::
18062 * Switches for gnatprep::
18063 * Form of Definitions File::
18064 * Form of Input Text for gnatprep::
18065 @end menu
18066
18067 @node Preprocessing Symbols
18068 @section Preprocessing Symbols
18069
18070 @noindent
18071 Preprocessing symbols are defined in definition files and referred to in
18072 sources to be preprocessed. A Preprocessing symbol is an identifier, following
18073 normal Ada (case-insensitive) rules for its syntax, with the restriction that
18074 all characters need to be in the ASCII set (no accented letters).
18075
18076 @node Using gnatprep
18077 @section Using @code{gnatprep}
18078
18079 @noindent
18080 To call @code{gnatprep} use
18081
18082 @smallexample
18083 $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
18084 @end smallexample
18085
18086 @noindent
18087 where
18088 @table @var
18089 @item switches
18090 is an optional sequence of switches as described in the next section.
18091
18092 @item infile
18093 is the full name of the input file, which is an Ada source
18094 file containing preprocessor directives.
18095
18096 @item outfile
18097 is the full name of the output file, which is an Ada source
18098 in standard Ada form. When used with GNAT, this file name will
18099 normally have an ads or adb suffix.
18100
18101 @item deffile
18102 is the full name of a text file containing definitions of
18103 preprocessing symbols to be referenced by the preprocessor. This argument is
18104 optional, and can be replaced by the use of the @option{-D} switch.
18105
18106 @end table
18107
18108 @node Switches for gnatprep
18109 @section Switches for @code{gnatprep}
18110
18111 @table @option
18112 @c !sort!
18113
18114 @item ^-b^/BLANK_LINES^
18115 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
18116 Causes both preprocessor lines and the lines deleted by
18117 preprocessing to be replaced by blank lines in the output source file,
18118 preserving line numbers in the output file.
18119
18120 @item ^-c^/COMMENTS^
18121 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
18122 Causes both preprocessor lines and the lines deleted
18123 by preprocessing to be retained in the output source as comments marked
18124 with the special string @code{"--! "}. This option will result in line numbers
18125 being preserved in the output file.
18126
18127 @item ^-C^/REPLACE_IN_COMMENTS^
18128 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
18129 Causes comments to be scanned. Normally comments are ignored by gnatprep.
18130 If this option is specified, then comments are scanned and any $symbol
18131 substitutions performed as in program text. This is particularly useful
18132 when structured comments are used (e.g., when writing programs in the
18133 SPARK dialect of Ada). Note that this switch is not available when
18134 doing integrated preprocessing (it would be useless in this context
18135 since comments are ignored by the compiler in any case).
18136
18137 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
18138 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
18139 Defines a new preprocessing symbol, associated with value. If no value is given
18140 on the command line, then symbol is considered to be @code{True}. This switch
18141 can be used in place of a definition file.
18142
18143 @ifset vms
18144 @item /REMOVE
18145 @cindex @option{/REMOVE} (@command{gnatprep})
18146 This is the default setting which causes lines deleted by preprocessing
18147 to be entirely removed from the output file.
18148 @end ifset
18149
18150 @item ^-r^/REFERENCE^
18151 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
18152 Causes a @code{Source_Reference} pragma to be generated that
18153 references the original input file, so that error messages will use
18154 the file name of this original file. The use of this switch implies
18155 that preprocessor lines are not to be removed from the file, so its
18156 use will force @option{^-b^/BLANK_LINES^} mode if
18157 @option{^-c^/COMMENTS^}
18158 has not been specified explicitly.
18159
18160 Note that if the file to be preprocessed contains multiple units, then
18161 it will be necessary to @code{gnatchop} the output file from
18162 @code{gnatprep}. If a @code{Source_Reference} pragma is present
18163 in the preprocessed file, it will be respected by
18164 @code{gnatchop ^-r^/REFERENCE^}
18165 so that the final chopped files will correctly refer to the original
18166 input source file for @code{gnatprep}.
18167
18168 @item ^-s^/SYMBOLS^
18169 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
18170 Causes a sorted list of symbol names and values to be
18171 listed on the standard output file.
18172
18173 @item ^-u^/UNDEFINED^
18174 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
18175 Causes undefined symbols to be treated as having the value FALSE in the context
18176 of a preprocessor test. In the absence of this option, an undefined symbol in
18177 a @code{#if} or @code{#elsif} test will be treated as an error.
18178
18179 @end table
18180
18181 @ifclear vms
18182 @noindent
18183 Note: if neither @option{-b} nor @option{-c} is present,
18184 then preprocessor lines and
18185 deleted lines are completely removed from the output, unless -r is
18186 specified, in which case -b is assumed.
18187 @end ifclear
18188
18189 @node Form of Definitions File
18190 @section Form of Definitions File
18191
18192 @noindent
18193 The definitions file contains lines of the form
18194
18195 @smallexample
18196 symbol := value
18197 @end smallexample
18198
18199 @noindent
18200 where symbol is a preprocessing symbol, and value is one of the following:
18201
18202 @itemize @bullet
18203 @item
18204 Empty, corresponding to a null substitution
18205 @item
18206 A string literal using normal Ada syntax
18207 @item
18208 Any sequence of characters from the set
18209 (letters, digits, period, underline).
18210 @end itemize
18211
18212 @noindent
18213 Comment lines may also appear in the definitions file, starting with
18214 the usual @code{--},
18215 and comments may be added to the definitions lines.
18216
18217 @node Form of Input Text for gnatprep
18218 @section Form of Input Text for @code{gnatprep}
18219
18220 @noindent
18221 The input text may contain preprocessor conditional inclusion lines,
18222 as well as general symbol substitution sequences.
18223
18224 The preprocessor conditional inclusion commands have the form
18225
18226 @smallexample
18227 @group
18228 @cartouche
18229 #if @i{expression} @r{[}then@r{]}
18230    lines
18231 #elsif @i{expression} @r{[}then@r{]}
18232    lines
18233 #elsif @i{expression} @r{[}then@r{]}
18234    lines
18235 @dots{}
18236 #else
18237    lines
18238 #end if;
18239 @end cartouche
18240 @end group
18241 @end smallexample
18242
18243 @noindent
18244 In this example, @i{expression} is defined by the following grammar:
18245 @smallexample
18246 @i{expression} ::=  <symbol>
18247 @i{expression} ::=  <symbol> = "<value>"
18248 @i{expression} ::=  <symbol> = <symbol>
18249 @i{expression} ::=  <symbol> 'Defined
18250 @i{expression} ::=  not @i{expression}
18251 @i{expression} ::=  @i{expression} and @i{expression}
18252 @i{expression} ::=  @i{expression} or @i{expression}
18253 @i{expression} ::=  @i{expression} and then @i{expression}
18254 @i{expression} ::=  @i{expression} or else @i{expression}
18255 @i{expression} ::=  ( @i{expression} )
18256 @end smallexample
18257
18258 The following restriction exists: it is not allowed to have "and" or "or"
18259 following "not" in the same expression without parentheses. For example, this
18260 is not allowed:
18261
18262 @smallexample
18263    not X or Y
18264 @end smallexample
18265
18266 This should be one of the following:
18267
18268 @smallexample
18269    (not X) or Y
18270    not (X or Y)
18271 @end smallexample
18272
18273 @noindent
18274 For the first test (@i{expression} ::= <symbol>) the symbol must have
18275 either the value true or false, that is to say the right-hand of the
18276 symbol definition must be one of the (case-insensitive) literals
18277 @code{True} or @code{False}. If the value is true, then the
18278 corresponding lines are included, and if the value is false, they are
18279 excluded.
18280
18281 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
18282 the symbol has been defined in the definition file or by a @option{-D}
18283 switch on the command line. Otherwise, the test is false.
18284
18285 The equality tests are case insensitive, as are all the preprocessor lines.
18286
18287 If the symbol referenced is not defined in the symbol definitions file,
18288 then the effect depends on whether or not switch @option{-u}
18289 is specified. If so, then the symbol is treated as if it had the value
18290 false and the test fails. If this switch is not specified, then
18291 it is an error to reference an undefined symbol. It is also an error to
18292 reference a symbol that is defined with a value other than @code{True}
18293 or @code{False}.
18294
18295 The use of the @code{not} operator inverts the sense of this logical test.
18296 The @code{not} operator cannot be combined with the @code{or} or @code{and}
18297 operators, without parentheses. For example, "if not X or Y then" is not
18298 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
18299
18300 The @code{then} keyword is optional as shown
18301
18302 The @code{#} must be the first non-blank character on a line, but
18303 otherwise the format is free form. Spaces or tabs may appear between
18304 the @code{#} and the keyword. The keywords and the symbols are case
18305 insensitive as in normal Ada code. Comments may be used on a
18306 preprocessor line, but other than that, no other tokens may appear on a
18307 preprocessor line. Any number of @code{elsif} clauses can be present,
18308 including none at all. The @code{else} is optional, as in Ada.
18309
18310 The @code{#} marking the start of a preprocessor line must be the first
18311 non-blank character on the line, i.e., it must be preceded only by
18312 spaces or horizontal tabs.
18313
18314 Symbol substitution outside of preprocessor lines is obtained by using
18315 the sequence
18316
18317 @smallexample
18318 $symbol
18319 @end smallexample
18320
18321 @noindent
18322 anywhere within a source line, except in a comment or within a
18323 string literal. The identifier
18324 following the @code{$} must match one of the symbols defined in the symbol
18325 definition file, and the result is to substitute the value of the
18326 symbol in place of @code{$symbol} in the output file.
18327
18328 Note that although the substitution of strings within a string literal
18329 is not possible, it is possible to have a symbol whose defined value is
18330 a string literal. So instead of setting XYZ to @code{hello} and writing:
18331
18332 @smallexample
18333 Header : String := "$XYZ";
18334 @end smallexample
18335
18336 @noindent
18337 you should set XYZ to @code{"hello"} and write:
18338
18339 @smallexample
18340 Header : String := $XYZ;
18341 @end smallexample
18342
18343 @noindent
18344 and then the substitution will occur as desired.
18345
18346 @ifset vms
18347 @node The GNAT Run-Time Library Builder gnatlbr
18348 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18349 @findex gnatlbr
18350 @cindex Library builder
18351
18352 @noindent
18353 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18354 supplied configuration pragmas.
18355
18356 @menu
18357 * Running gnatlbr::
18358 * Switches for gnatlbr::
18359 * Examples of gnatlbr Usage::
18360 @end menu
18361
18362 @node Running gnatlbr
18363 @section Running @code{gnatlbr}
18364
18365 @noindent
18366 The @code{gnatlbr} command has the form
18367
18368 @smallexample
18369 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18370 @end smallexample
18371
18372 @node Switches for gnatlbr
18373 @section Switches for @code{gnatlbr}
18374
18375 @noindent
18376 @code{gnatlbr} recognizes the following switches:
18377
18378 @table @option
18379 @c !sort!
18380 @item /CREATE=directory
18381 @cindex @code{/CREATE} (@code{gnatlbr})
18382 Create the new run-time library in the specified directory.
18383
18384 @item /SET=directory
18385 @cindex @code{/SET} (@code{gnatlbr})
18386 Make the library in the specified directory the current run-time library.
18387
18388 @item /DELETE=directory
18389 @cindex @code{/DELETE} (@code{gnatlbr})
18390 Delete the run-time library in the specified directory.
18391
18392 @item /CONFIG=file
18393 @cindex @code{/CONFIG} (@code{gnatlbr})
18394 With /CREATE: Use the configuration pragmas in the specified file when
18395 building the library.
18396
18397 With /SET: Use the configuration pragmas in the specified file when
18398 compiling.
18399
18400 @end table
18401
18402 @node Examples of gnatlbr Usage
18403 @section Example of @code{gnatlbr} Usage
18404
18405 @smallexample
18406 Contents of VAXFLOAT.ADC:
18407 pragma Float_Representation (VAX_Float);
18408
18409 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18410
18411 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18412
18413 @end smallexample
18414 @end ifset
18415
18416 @node The GNAT Library Browser gnatls
18417 @chapter The GNAT Library Browser @code{gnatls}
18418 @findex gnatls
18419 @cindex Library browser
18420
18421 @noindent
18422 @code{gnatls} is a tool that outputs information about compiled
18423 units. It gives the relationship between objects, unit names and source
18424 files. It can also be used to check the source dependencies of a unit
18425 as well as various characteristics.
18426
18427 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18428 driver (see @ref{The GNAT Driver and Project Files}).
18429
18430 @menu
18431 * Running gnatls::
18432 * Switches for gnatls::
18433 * Examples of gnatls Usage::
18434 @end menu
18435
18436 @node Running gnatls
18437 @section Running @code{gnatls}
18438
18439 @noindent
18440 The @code{gnatls} command has the form
18441
18442 @smallexample
18443 $ gnatls switches @var{object_or_ali_file}
18444 @end smallexample
18445
18446 @noindent
18447 The main argument is the list of object or @file{ali} files
18448 (@pxref{The Ada Library Information Files})
18449 for which information is requested.
18450
18451 In normal mode, without additional option, @code{gnatls} produces a
18452 four-column listing. Each line represents information for a specific
18453 object. The first column gives the full path of the object, the second
18454 column gives the name of the principal unit in this object, the third
18455 column gives the status of the source and the fourth column gives the
18456 full path of the source representing this unit.
18457 Here is a simple example of use:
18458
18459 @smallexample
18460 $ gnatls *.o
18461 ^./^[]^demo1.o            demo1            DIF demo1.adb
18462 ^./^[]^demo2.o            demo2             OK demo2.adb
18463 ^./^[]^hello.o            h1                OK hello.adb
18464 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
18465 ^./^[]^instr.o            instr             OK instr.adb
18466 ^./^[]^tef.o              tef              DIF tef.adb
18467 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
18468 ^./^[]^tgef.o             tgef             DIF tgef.adb
18469 @end smallexample
18470
18471 @noindent
18472 The first line can be interpreted as follows: the main unit which is
18473 contained in
18474 object file @file{demo1.o} is demo1, whose main source is in
18475 @file{demo1.adb}. Furthermore, the version of the source used for the
18476 compilation of demo1 has been modified (DIF). Each source file has a status
18477 qualifier which can be:
18478
18479 @table @code
18480 @item OK (unchanged)
18481 The version of the source file used for the compilation of the
18482 specified unit corresponds exactly to the actual source file.
18483
18484 @item MOK (slightly modified)
18485 The version of the source file used for the compilation of the
18486 specified unit differs from the actual source file but not enough to
18487 require recompilation. If you use gnatmake with the qualifier
18488 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18489 MOK will not be recompiled.
18490
18491 @item DIF (modified)
18492 No version of the source found on the path corresponds to the source
18493 used to build this object.
18494
18495 @item ??? (file not found)
18496 No source file was found for this unit.
18497
18498 @item HID (hidden,  unchanged version not first on PATH)
18499 The version of the source that corresponds exactly to the source used
18500 for compilation has been found on the path but it is hidden by another
18501 version of the same source that has been modified.
18502
18503 @end table
18504
18505 @node Switches for gnatls
18506 @section Switches for @code{gnatls}
18507
18508 @noindent
18509 @code{gnatls} recognizes the following switches:
18510
18511 @table @option
18512 @c !sort!
18513 @cindex @option{--version} @command{gnatls}
18514 Display Copyright and version, then exit disregarding all other options.
18515
18516 @item --help
18517 @cindex @option{--help} @command{gnatls}
18518 If @option{--version} was not used, display usage, then exit disregarding
18519 all other options.
18520
18521 @item ^-a^/ALL_UNITS^
18522 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18523 Consider all units, including those of the predefined Ada library.
18524 Especially useful with @option{^-d^/DEPENDENCIES^}.
18525
18526 @item ^-d^/DEPENDENCIES^
18527 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18528 List sources from which specified units depend on.
18529
18530 @item ^-h^/OUTPUT=OPTIONS^
18531 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18532 Output the list of options.
18533
18534 @item ^-o^/OUTPUT=OBJECTS^
18535 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18536 Only output information about object files.
18537
18538 @item ^-s^/OUTPUT=SOURCES^
18539 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18540 Only output information about source files.
18541
18542 @item ^-u^/OUTPUT=UNITS^
18543 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18544 Only output information about compilation units.
18545
18546 @item ^-files^/FILES^=@var{file}
18547 @cindex @option{^-files^/FILES^} (@code{gnatls})
18548 Take as arguments the files listed in text file @var{file}.
18549 Text file @var{file} may contain empty lines that are ignored.
18550 Each nonempty line should contain the name of an existing file.
18551 Several such switches may be specified simultaneously.
18552
18553 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18554 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18555 @itemx ^-I^/SEARCH=^@var{dir}
18556 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
18557 @itemx -nostdinc
18558 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18559 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18560 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18561 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18562 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18563 flags (@pxref{Switches for gnatmake}).
18564
18565 @item --RTS=@var{rts-path}
18566 @cindex @option{--RTS} (@code{gnatls})
18567 Specifies the default location of the runtime library. Same meaning as the
18568 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18569
18570 @item ^-v^/OUTPUT=VERBOSE^
18571 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18572 Verbose mode. Output the complete source, object and project paths. Do not use
18573 the default column layout but instead use long format giving as much as
18574 information possible on each requested units, including special
18575 characteristics such as:
18576
18577 @table @code
18578 @item  Preelaborable
18579 The unit is preelaborable in the Ada sense.
18580
18581 @item No_Elab_Code
18582 No elaboration code has been produced by the compiler for this unit.
18583
18584 @item Pure
18585 The unit is pure in the Ada sense.
18586
18587 @item Elaborate_Body
18588 The unit contains a pragma Elaborate_Body.
18589
18590 @item Remote_Types
18591 The unit contains a pragma Remote_Types.
18592
18593 @item Shared_Passive
18594 The unit contains a pragma Shared_Passive.
18595
18596 @item Predefined
18597 This unit is part of the predefined environment and cannot be modified
18598 by the user.
18599
18600 @item Remote_Call_Interface
18601 The unit contains a pragma Remote_Call_Interface.
18602
18603 @end table
18604
18605 @end table
18606
18607 @node Examples of gnatls Usage
18608 @section Example of @code{gnatls} Usage
18609 @ifclear vms
18610
18611 @noindent
18612 Example of using the verbose switch. Note how the source and
18613 object paths are affected by the -I switch.
18614
18615 @smallexample
18616 $ gnatls -v -I.. demo1.o
18617
18618 GNATLS 5.03w (20041123-34)
18619 Copyright 1997-2004 Free Software Foundation, Inc.
18620
18621 Source Search Path:
18622    <Current_Directory>
18623    ../
18624    /home/comar/local/adainclude/
18625
18626 Object Search Path:
18627    <Current_Directory>
18628    ../
18629    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18630
18631 Project Search Path:
18632    <Current_Directory>
18633    /home/comar/local/lib/gnat/
18634
18635 ./demo1.o
18636    Unit =>
18637      Name   => demo1
18638      Kind   => subprogram body
18639      Flags  => No_Elab_Code
18640      Source => demo1.adb    modified
18641 @end smallexample
18642
18643 @noindent
18644 The following is an example of use of the dependency list.
18645 Note the use of the -s switch
18646 which gives a straight list of source files. This can be useful for
18647 building specialized scripts.
18648
18649 @smallexample
18650 $ gnatls -d demo2.o
18651 ./demo2.o   demo2        OK demo2.adb
18652                          OK gen_list.ads
18653                          OK gen_list.adb
18654                          OK instr.ads
18655                          OK instr-child.ads
18656
18657 $ gnatls -d -s -a demo1.o
18658 demo1.adb
18659 /home/comar/local/adainclude/ada.ads
18660 /home/comar/local/adainclude/a-finali.ads
18661 /home/comar/local/adainclude/a-filico.ads
18662 /home/comar/local/adainclude/a-stream.ads
18663 /home/comar/local/adainclude/a-tags.ads
18664 gen_list.ads
18665 gen_list.adb
18666 /home/comar/local/adainclude/gnat.ads
18667 /home/comar/local/adainclude/g-io.ads
18668 instr.ads
18669 /home/comar/local/adainclude/system.ads
18670 /home/comar/local/adainclude/s-exctab.ads
18671 /home/comar/local/adainclude/s-finimp.ads
18672 /home/comar/local/adainclude/s-finroo.ads
18673 /home/comar/local/adainclude/s-secsta.ads
18674 /home/comar/local/adainclude/s-stalib.ads
18675 /home/comar/local/adainclude/s-stoele.ads
18676 /home/comar/local/adainclude/s-stratt.ads
18677 /home/comar/local/adainclude/s-tasoli.ads
18678 /home/comar/local/adainclude/s-unstyp.ads
18679 /home/comar/local/adainclude/unchconv.ads
18680 @end smallexample
18681 @end ifclear
18682
18683 @ifset vms
18684 @smallexample
18685 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18686
18687 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18688 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18689 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18690 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18691 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18692 demo1.adb
18693 gen_list.ads
18694 gen_list.adb
18695 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18696 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18697 instr.ads
18698 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18699 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18700 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18701 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18702 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18703 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18704 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18705 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18706 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18707 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18708 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18709 @end smallexample
18710 @end ifset
18711
18712 @node Cleaning Up Using gnatclean
18713 @chapter Cleaning Up Using @code{gnatclean}
18714 @findex gnatclean
18715 @cindex Cleaning tool
18716
18717 @noindent
18718 @code{gnatclean} is a tool that allows the deletion of files produced by the
18719 compiler, binder and linker, including ALI files, object files, tree files,
18720 expanded source files, library files, interface copy source files, binder
18721 generated files and executable files.
18722
18723 @menu
18724 * Running gnatclean::
18725 * Switches for gnatclean::
18726 @c * Examples of gnatclean Usage::
18727 @end menu
18728
18729 @node Running gnatclean
18730 @section Running @code{gnatclean}
18731
18732 @noindent
18733 The @code{gnatclean} command has the form:
18734
18735 @smallexample
18736 $ gnatclean switches @var{names}
18737 @end smallexample
18738
18739 @noindent
18740 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18741 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18742 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18743
18744 @noindent
18745 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18746 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18747 the linker. In informative-only mode, specified by switch
18748 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18749 normal mode is listed, but no file is actually deleted.
18750
18751 @node Switches for gnatclean
18752 @section Switches for @code{gnatclean}
18753
18754 @noindent
18755 @code{gnatclean} recognizes the following switches:
18756
18757 @table @option
18758 @c !sort!
18759 @cindex @option{--version} @command{gnatclean}
18760 Display Copyright and version, then exit disregarding all other options.
18761
18762 @item --help
18763 @cindex @option{--help} @command{gnatclean}
18764 If @option{--version} was not used, display usage, then exit disregarding
18765 all other options.
18766
18767 @item ^-c^/COMPILER_FILES_ONLY^
18768 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18769 Only attempt to delete the files produced by the compiler, not those produced
18770 by the binder or the linker. The files that are not to be deleted are library
18771 files, interface copy files, binder generated files and executable files.
18772
18773 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18774 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18775 Indicate that ALI and object files should normally be found in directory
18776 @var{dir}.
18777
18778 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18779 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18780 When using project files, if some errors or warnings are detected during
18781 parsing and verbose mode is not in effect (no use of switch
18782 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18783 file, rather than its simple file name.
18784
18785 @item ^-h^/HELP^
18786 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18787 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18788
18789 @item ^-n^/NODELETE^
18790 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18791 Informative-only mode. Do not delete any files. Output the list of the files
18792 that would have been deleted if this switch was not specified.
18793
18794 @item ^-P^/PROJECT_FILE=^@var{project}
18795 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18796 Use project file @var{project}. Only one such switch can be used.
18797 When cleaning a project file, the files produced by the compilation of the
18798 immediate sources or inherited sources of the project files are to be
18799 deleted. This is not depending on the presence or not of executable names
18800 on the command line.
18801
18802 @item ^-q^/QUIET^
18803 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18804 Quiet output. If there are no errors, do not output anything, except in
18805 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18806 (switch ^-n^/NODELETE^).
18807
18808 @item ^-r^/RECURSIVE^
18809 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18810 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18811 clean all imported and extended project files, recursively. If this switch
18812 is not specified, only the files related to the main project file are to be
18813 deleted. This switch has no effect if no project file is specified.
18814
18815 @item ^-v^/VERBOSE^
18816 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18817 Verbose mode.
18818
18819 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18820 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18821 Indicates the verbosity of the parsing of GNAT project files.
18822 @xref{Switches Related to Project Files}.
18823
18824 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18825 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18826 Indicates that external variable @var{name} has the value @var{value}.
18827 The Project Manager will use this value for occurrences of
18828 @code{external(name)} when parsing the project file.
18829 @xref{Switches Related to Project Files}.
18830
18831 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18832 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18833 When searching for ALI and object files, look in directory
18834 @var{dir}.
18835
18836 @item ^-I^/SEARCH=^@var{dir}
18837 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18838 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18839
18840 @item ^-I-^/NOCURRENT_DIRECTORY^
18841 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18842 @cindex Source files, suppressing search
18843 Do not look for ALI or object files in the directory
18844 where @code{gnatclean} was invoked.
18845
18846 @end table
18847
18848 @c @node Examples of gnatclean Usage
18849 @c @section Examples of @code{gnatclean} Usage
18850
18851 @ifclear vms
18852 @node GNAT and Libraries
18853 @chapter GNAT and Libraries
18854 @cindex Library, building, installing, using
18855
18856 @noindent
18857 This chapter describes how to build and use libraries with GNAT, and also shows
18858 how to recompile the GNAT run-time library. You should be familiar with the
18859 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18860 chapter.
18861
18862 @menu
18863 * Introduction to Libraries in GNAT::
18864 * General Ada Libraries::
18865 * Stand-alone Ada Libraries::
18866 * Rebuilding the GNAT Run-Time Library::
18867 @end menu
18868
18869 @node Introduction to Libraries in GNAT
18870 @section Introduction to Libraries in GNAT
18871
18872 @noindent
18873 A library is, conceptually, a collection of objects which does not have its
18874 own main thread of execution, but rather provides certain services to the
18875 applications that use it. A library can be either statically linked with the
18876 application, in which case its code is directly included in the application,
18877 or, on platforms that support it, be dynamically linked, in which case
18878 its code is shared by all applications making use of this library.
18879
18880 GNAT supports both types of libraries.
18881 In the static case, the compiled code can be provided in different ways. The
18882 simplest approach is to provide directly the set of objects resulting from
18883 compilation of the library source files. Alternatively, you can group the
18884 objects into an archive using whatever commands are provided by the operating
18885 system. For the latter case, the objects are grouped into a shared library.
18886
18887 In the GNAT environment, a library has three types of components:
18888 @itemize @bullet
18889 @item
18890 Source files.
18891 @item
18892 @file{ALI} files.
18893 @xref{The Ada Library Information Files}.
18894 @item
18895 Object files, an archive or a shared library.
18896 @end itemize
18897
18898 @noindent
18899 A GNAT library may expose all its source files, which is useful for
18900 documentation purposes. Alternatively, it may expose only the units needed by
18901 an external user to make use of the library. That is to say, the specs
18902 reflecting the library services along with all the units needed to compile
18903 those specs, which can include generic bodies or any body implementing an
18904 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18905 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18906
18907 All compilation units comprising an application, including those in a library,
18908 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18909 computes the elaboration order from the @file{ALI} files and this is why they
18910 constitute a mandatory part of GNAT libraries.
18911 @emph{Stand-alone libraries} are the exception to this rule because a specific
18912 library elaboration routine is produced independently of the application(s)
18913 using the library.
18914
18915 @node General Ada Libraries
18916 @section General Ada Libraries
18917
18918 @menu
18919 * Building a library::
18920 * Installing a library::
18921 * Using a library::
18922 @end menu
18923
18924 @node Building a library
18925 @subsection Building a library
18926
18927 @noindent
18928 The easiest way to build a library is to use the Project Manager,
18929 which supports a special type of project called a @emph{Library Project}
18930 (@pxref{Library Projects}).
18931
18932 A project is considered a library project, when two project-level attributes
18933 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
18934 control different aspects of library configuration, additional optional
18935 project-level attributes can be specified:
18936 @table @code
18937 @item Library_Kind
18938 This attribute controls whether the library is to be static or dynamic
18939
18940 @item Library_Version
18941 This attribute specifies the library version; this value is used
18942 during dynamic linking of shared libraries to determine if the currently
18943 installed versions of the binaries are compatible.
18944
18945 @item Library_Options
18946 @item Library_GCC
18947 These attributes specify additional low-level options to be used during
18948 library generation, and redefine the actual application used to generate
18949 library.
18950 @end table
18951
18952 @noindent
18953 The GNAT Project Manager takes full care of the library maintenance task,
18954 including recompilation of the source files for which objects do not exist
18955 or are not up to date, assembly of the library archive, and installation of
18956 the library (i.e., copying associated source, object and @file{ALI} files
18957 to the specified location).
18958
18959 Here is a simple library project file:
18960 @smallexample @c ada
18961 project My_Lib is
18962    for Source_Dirs use ("src1", "src2");
18963    for Object_Dir use "obj";
18964    for Library_Name use "mylib";
18965    for Library_Dir use "lib";
18966    for Library_Kind use "dynamic";
18967 end My_lib;
18968 @end smallexample
18969
18970 @noindent
18971 and the compilation command to build and install the library:
18972
18973 @smallexample @c ada
18974   $ gnatmake -Pmy_lib
18975 @end smallexample
18976
18977 @noindent
18978 It is not entirely trivial to perform manually all the steps required to
18979 produce a library. We recommend that you use the GNAT Project Manager
18980 for this task. In special cases where this is not desired, the necessary
18981 steps are discussed below.
18982
18983 There are various possibilities for compiling the units that make up the
18984 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
18985 with a conventional script. For simple libraries, it is also possible to create
18986 a dummy main program which depends upon all the packages that comprise the
18987 interface of the library. This dummy main program can then be given to
18988 @command{gnatmake}, which will ensure that all necessary objects are built.
18989
18990 After this task is accomplished, you should follow the standard procedure
18991 of the underlying operating system to produce the static or shared library.
18992
18993 Here is an example of such a dummy program:
18994 @smallexample @c ada
18995 @group
18996 with My_Lib.Service1;
18997 with My_Lib.Service2;
18998 with My_Lib.Service3;
18999 procedure My_Lib_Dummy is
19000 begin
19001    null;
19002 end;
19003 @end group
19004 @end smallexample
19005
19006 @noindent
19007 Here are the generic commands that will build an archive or a shared library.
19008
19009 @smallexample
19010 # compiling the library
19011 $ gnatmake -c my_lib_dummy.adb
19012
19013 # we don't need the dummy object itself
19014 $ rm my_lib_dummy.o my_lib_dummy.ali
19015
19016 # create an archive with the remaining objects
19017 $ ar rc libmy_lib.a *.o
19018 # some systems may require "ranlib" to be run as well
19019
19020 # or create a shared library
19021 $ gcc -shared -o libmy_lib.so *.o
19022 # some systems may require the code to have been compiled with -fPIC
19023
19024 # remove the object files that are now in the library
19025 $ rm *.o
19026
19027 # Make the ALI files read-only so that gnatmake will not try to
19028 # regenerate the objects that are in the library
19029 $ chmod -w *.ali
19030 @end smallexample
19031
19032 @noindent
19033 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
19034 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
19035 be accessed by the directive @option{-l@var{xxx}} at link time.
19036
19037 @node Installing a library
19038 @subsection Installing a library
19039 @cindex @code{ADA_PROJECT_PATH}
19040
19041 @noindent
19042 If you use project files, library installation is part of the library build
19043 process. Thus no further action is needed in order to make use of the
19044 libraries that are built as part of the general application build. A usable
19045 version of the library is installed in the directory specified by the
19046 @code{Library_Dir} attribute of the library project file.
19047
19048 You may want to install a library in a context different from where the library
19049 is built. This situation arises with third party suppliers, who may want
19050 to distribute a library in binary form where the user is not expected to be
19051 able to recompile the library. The simplest option in this case is to provide
19052 a project file slightly different from the one used to build the library, by
19053 using the @code{externally_built} attribute. For instance, the project
19054 file used to build the library in the previous section can be changed into the
19055 following one when the library is installed:
19056
19057 @smallexample @c projectfile
19058 project My_Lib is
19059    for Source_Dirs use ("src1", "src2");
19060    for Library_Name use "mylib";
19061    for Library_Dir use "lib";
19062    for Library_Kind use "dynamic";
19063    for Externally_Built use "true";
19064 end My_lib;
19065 @end smallexample
19066
19067 @noindent
19068 This project file assumes that the directories @file{src1},
19069 @file{src2}, and @file{lib} exist in
19070 the directory containing the project file. The @code{externally_built}
19071 attribute makes it clear to the GNAT builder that it should not attempt to
19072 recompile any of the units from this library. It allows the library provider to
19073 restrict the source set to the minimum necessary for clients to make use of the
19074 library as described in the first section of this chapter. It is the
19075 responsibility of the library provider to install the necessary sources, ALI
19076 files and libraries in the directories mentioned in the project file. For
19077 convenience, the user's library project file should be installed in a location
19078 that will be searched automatically by the GNAT
19079 builder. These are the directories referenced in the @env{ADA_PROJECT_PATH}
19080 environment variable (@pxref{Importing Projects}), and also the default GNAT
19081 library location that can be queried with @command{gnatls -v} and is usually of
19082 the form $gnat_install_root/lib/gnat.
19083
19084 When project files are not an option, it is also possible, but not recommended,
19085 to install the library so that the sources needed to use the library are on the
19086 Ada source path and the ALI files & libraries be on the Ada Object path (see
19087 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
19088 administrator can place general-purpose libraries in the default compiler
19089 paths, by specifying the libraries' location in the configuration files
19090 @file{ada_source_path} and @file{ada_object_path}. These configuration files
19091 must be located in the GNAT installation tree at the same place as the gcc spec
19092 file. The location of the gcc spec file can be determined as follows:
19093 @smallexample
19094 $ gcc -v
19095 @end smallexample
19096
19097 @noindent
19098 The configuration files mentioned above have a simple format: each line
19099 must contain one unique directory name.
19100 Those names are added to the corresponding path
19101 in their order of appearance in the file. The names can be either absolute
19102 or relative; in the latter case, they are relative to where theses files
19103 are located.
19104
19105 The files @file{ada_source_path} and @file{ada_object_path} might not be
19106 present in a
19107 GNAT installation, in which case, GNAT will look for its run-time library in
19108 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
19109 objects and @file{ALI} files). When the files exist, the compiler does not
19110 look in @file{adainclude} and @file{adalib}, and thus the
19111 @file{ada_source_path} file
19112 must contain the location for the GNAT run-time sources (which can simply
19113 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
19114 contain the location for the GNAT run-time objects (which can simply
19115 be @file{adalib}).
19116
19117 You can also specify a new default path to the run-time library at compilation
19118 time with the switch @option{--RTS=rts-path}. You can thus choose / change
19119 the run-time library you want your program to be compiled with. This switch is
19120 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
19121 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
19122
19123 It is possible to install a library before or after the standard GNAT
19124 library, by reordering the lines in the configuration files. In general, a
19125 library must be installed before the GNAT library if it redefines
19126 any part of it.
19127
19128 @node Using a library
19129 @subsection Using a library
19130
19131 @noindent Once again, the project facility greatly simplifies the use of
19132 libraries. In this context, using a library is just a matter of adding a
19133 @code{with} clause in the user project. For instance, to make use of the
19134 library @code{My_Lib} shown in examples in earlier sections, you can
19135 write:
19136
19137 @smallexample @c projectfile
19138 with "my_lib";
19139 project My_Proj is
19140   @dots{}
19141 end My_Proj;
19142 @end smallexample
19143
19144 Even if you have a third-party, non-Ada library, you can still use GNAT's
19145 Project Manager facility to provide a wrapper for it. For example, the
19146 following project, when @code{with}ed by your main project, will link with the
19147 third-party library @file{liba.a}:
19148
19149 @smallexample @c projectfile
19150 @group
19151 project Liba is
19152    for Externally_Built use "true";
19153    for Source_Files use ();
19154    for Library_Dir use "lib";
19155    for Library_Name use "a";
19156    for Library_Kind use "static";
19157 end Liba;
19158 @end group
19159 @end smallexample
19160 This is an alternative to the use of @code{pragma Linker_Options}. It is
19161 especially interesting in the context of systems with several interdependent
19162 static libraries where finding a proper linker order is not easy and best be
19163 left to the tools having visibility over project dependence information.
19164
19165 @noindent
19166 In order to use an Ada library manually, you need to make sure that this
19167 library is on both your source and object path
19168 (see @ref{Search Paths and the Run-Time Library (RTL)}
19169 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
19170 in an archive or a shared library, you need to specify the desired
19171 library at link time.
19172
19173 For example, you can use the library @file{mylib} installed in
19174 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
19175
19176 @smallexample
19177 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
19178   -largs -lmy_lib
19179 @end smallexample
19180
19181 @noindent
19182 This can be expressed more simply:
19183 @smallexample
19184 $ gnatmake my_appl
19185 @end smallexample
19186 @noindent
19187 when the following conditions are met:
19188 @itemize @bullet
19189 @item
19190 @file{/dir/my_lib_src} has been added by the user to the environment
19191 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
19192 @file{ada_source_path}
19193 @item
19194 @file{/dir/my_lib_obj} has been added by the user to the environment
19195 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
19196 @file{ada_object_path}
19197 @item
19198 a pragma @code{Linker_Options} has been added to one of the sources.
19199 For example:
19200
19201 @smallexample @c ada
19202 pragma Linker_Options ("-lmy_lib");
19203 @end smallexample
19204 @end itemize
19205
19206 @node Stand-alone Ada Libraries
19207 @section Stand-alone Ada Libraries
19208 @cindex Stand-alone library, building, using
19209
19210 @menu
19211 * Introduction to Stand-alone Libraries::
19212 * Building a Stand-alone Library::
19213 * Creating a Stand-alone Library to be used in a non-Ada context::
19214 * Restrictions in Stand-alone Libraries::
19215 @end menu
19216
19217 @node Introduction to Stand-alone Libraries
19218 @subsection Introduction to Stand-alone Libraries
19219
19220 @noindent
19221 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
19222 necessary code to
19223 elaborate the Ada units that are included in the library. In contrast with
19224 an ordinary library, which consists of all sources, objects and @file{ALI}
19225 files of the
19226 library, a SAL may specify a restricted subset of compilation units
19227 to serve as a library interface. In this case, the fully
19228 self-sufficient set of files will normally consist of an objects
19229 archive, the sources of interface units' specs, and the @file{ALI}
19230 files of interface units.
19231 If an interface spec contains a generic unit or an inlined subprogram,
19232 the body's
19233 source must also be provided; if the units that must be provided in the source
19234 form depend on other units, the source and @file{ALI} files of those must
19235 also be provided.
19236
19237 The main purpose of a SAL is to minimize the recompilation overhead of client
19238 applications when a new version of the library is installed. Specifically,
19239 if the interface sources have not changed, client applications do not need to
19240 be recompiled. If, furthermore, a SAL is provided in the shared form and its
19241 version, controlled by @code{Library_Version} attribute, is not changed,
19242 then the clients do not need to be relinked.
19243
19244 SALs also allow the library providers to minimize the amount of library source
19245 text exposed to the clients.  Such ``information hiding'' might be useful or
19246 necessary for various reasons.
19247
19248 Stand-alone libraries are also well suited to be used in an executable whose
19249 main routine is not written in Ada.
19250
19251 @node Building a Stand-alone Library
19252 @subsection Building a Stand-alone Library
19253
19254 @noindent
19255 GNAT's Project facility provides a simple way of building and installing
19256 stand-alone libraries; see @ref{Stand-alone Library Projects}.
19257 To be a Stand-alone Library Project, in addition to the two attributes
19258 that make a project a Library Project (@code{Library_Name} and
19259 @code{Library_Dir}; see @ref{Library Projects}), the attribute
19260 @code{Library_Interface} must be defined.  For example:
19261
19262 @smallexample @c projectfile
19263 @group
19264    for Library_Dir use "lib_dir";
19265    for Library_Name use "dummy";
19266    for Library_Interface use ("int1", "int1.child");
19267 @end group
19268 @end smallexample
19269
19270 @noindent
19271 Attribute @code{Library_Interface} has a non-empty string list value,
19272 each string in the list designating a unit contained in an immediate source
19273 of the project file.
19274
19275 When a Stand-alone Library is built, first the binder is invoked to build
19276 a package whose name depends on the library name
19277 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
19278 This binder-generated package includes initialization and
19279 finalization procedures whose
19280 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
19281 in the example
19282 above). The object corresponding to this package is included in the library.
19283
19284 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
19285 calling of these procedures if a static SAL is built, or if a shared SAL
19286 is built
19287 with the project-level attribute @code{Library_Auto_Init} set to
19288 @code{"false"}.
19289
19290 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
19291 (those that are listed in attribute @code{Library_Interface}) are copied to
19292 the Library Directory. As a consequence, only the Interface Units may be
19293 imported from Ada units outside of the library. If other units are imported,
19294 the binding phase will fail.
19295
19296 The attribute @code{Library_Src_Dir} may be specified for a
19297 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
19298 single string value. Its value must be the path (absolute or relative to the
19299 project directory) of an existing directory. This directory cannot be the
19300 object directory or one of the source directories, but it can be the same as
19301 the library directory. The sources of the Interface
19302 Units of the library that are needed by an Ada client of the library will be
19303 copied to the designated directory, called the Interface Copy directory.
19304 These sources include the specs of the Interface Units, but they may also
19305 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
19306 are used, or when there is a generic unit in the spec. Before the sources
19307 are copied to the Interface Copy directory, an attempt is made to delete all
19308 files in the Interface Copy directory.
19309
19310 Building stand-alone libraries by hand is somewhat tedious, but for those
19311 occasions when it is necessary here are the steps that you need to perform:
19312 @itemize @bullet
19313 @item
19314 Compile all library sources.
19315
19316 @item
19317 Invoke the binder with the switch @option{-n} (No Ada main program),
19318 with all the @file{ALI} files of the interfaces, and
19319 with the switch @option{-L} to give specific names to the @code{init}
19320 and @code{final} procedures.  For example:
19321 @smallexample
19322   gnatbind -n int1.ali int2.ali -Lsal1
19323 @end smallexample
19324
19325 @item
19326 Compile the binder generated file:
19327 @smallexample
19328   gcc -c b~int2.adb
19329 @end smallexample
19330
19331 @item
19332 Link the dynamic library with all the necessary object files,
19333 indicating to the linker the names of the @code{init} (and possibly
19334 @code{final}) procedures for automatic initialization (and finalization).
19335 The built library should be placed in a directory different from
19336 the object directory.
19337
19338 @item
19339 Copy the @code{ALI} files of the interface to the library directory,
19340 add in this copy an indication that it is an interface to a SAL
19341 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19342 with letter ``P'') and make the modified copy of the @file{ALI} file
19343 read-only.
19344 @end itemize
19345
19346 @noindent
19347 Using SALs is not different from using other libraries
19348 (see @ref{Using a library}).
19349
19350 @node Creating a Stand-alone Library to be used in a non-Ada context
19351 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19352
19353 @noindent
19354 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19355 a non-Ada context.
19356
19357 The only extra step required is to ensure that library interface subprograms
19358 are compatible with the main program, by means of @code{pragma Export}
19359 or @code{pragma Convention}.
19360
19361 Here is an example of simple library interface for use with C main program:
19362
19363 @smallexample @c ada
19364 package Interface is
19365
19366    procedure Do_Something;
19367    pragma Export (C, Do_Something, "do_something");
19368
19369    procedure Do_Something_Else;
19370    pragma Export (C, Do_Something_Else, "do_something_else");
19371
19372 end Interface;
19373 @end smallexample
19374
19375 @noindent
19376 On the foreign language side, you must provide a ``foreign'' view of the
19377 library interface; remember that it should contain elaboration routines in
19378 addition to interface subprograms.
19379
19380 The example below shows the content of @code{mylib_interface.h} (note
19381 that there is no rule for the naming of this file, any name can be used)
19382 @smallexample
19383 /* the library elaboration procedure */
19384 extern void mylibinit (void);
19385
19386 /* the library finalization procedure */
19387 extern void mylibfinal (void);
19388
19389 /* the interface exported by the library */
19390 extern void do_something (void);
19391 extern void do_something_else (void);
19392 @end smallexample
19393
19394 @noindent
19395 Libraries built as explained above can be used from any program, provided
19396 that the elaboration procedures (named @code{mylibinit} in the previous
19397 example) are called before the library services are used. Any number of
19398 libraries can be used simultaneously, as long as the elaboration
19399 procedure of each library is called.
19400
19401 Below is an example of a C program that uses the @code{mylib} library.
19402
19403 @smallexample
19404 #include "mylib_interface.h"
19405
19406 int
19407 main (void)
19408 @{
19409    /* First, elaborate the library before using it */
19410    mylibinit ();
19411
19412    /* Main program, using the library exported entities */
19413    do_something ();
19414    do_something_else ();
19415
19416    /* Library finalization at the end of the program */
19417    mylibfinal ();
19418    return 0;
19419 @}
19420 @end smallexample
19421
19422 @noindent
19423 Note that invoking any library finalization procedure generated by
19424 @code{gnatbind} shuts down the Ada run-time environment.
19425 Consequently, the
19426 finalization of all Ada libraries must be performed at the end of the program.
19427 No call to these libraries or to the Ada run-time library should be made
19428 after the finalization phase.
19429
19430 @node Restrictions in Stand-alone Libraries
19431 @subsection Restrictions in Stand-alone Libraries
19432
19433 @noindent
19434 The pragmas listed below should be used with caution inside libraries,
19435 as they can create incompatibilities with other Ada libraries:
19436 @itemize @bullet
19437 @item pragma @code{Locking_Policy}
19438 @item pragma @code{Queuing_Policy}
19439 @item pragma @code{Task_Dispatching_Policy}
19440 @item pragma @code{Unreserve_All_Interrupts}
19441 @end itemize
19442
19443 @noindent
19444 When using a library that contains such pragmas, the user must make sure
19445 that all libraries use the same pragmas with the same values. Otherwise,
19446 @code{Program_Error} will
19447 be raised during the elaboration of the conflicting
19448 libraries. The usage of these pragmas and its consequences for the user
19449 should therefore be well documented.
19450
19451 Similarly, the traceback in the exception occurrence mechanism should be
19452 enabled or disabled in a consistent manner across all libraries.
19453 Otherwise, Program_Error will be raised during the elaboration of the
19454 conflicting libraries.
19455
19456 If the @code{Version} or @code{Body_Version}
19457 attributes are used inside a library, then you need to
19458 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19459 libraries, so that version identifiers can be properly computed.
19460 In practice these attributes are rarely used, so this is unlikely
19461 to be a consideration.
19462
19463 @node  Rebuilding the GNAT Run-Time Library
19464 @section Rebuilding the GNAT Run-Time Library
19465 @cindex GNAT Run-Time Library, rebuilding
19466 @cindex Building the GNAT Run-Time Library
19467 @cindex Rebuilding the GNAT Run-Time Library
19468 @cindex Run-Time Library, rebuilding
19469
19470 @noindent
19471 It may be useful to recompile the GNAT library in various contexts, the
19472 most important one being the use of partition-wide configuration pragmas
19473 such as @code{Normalize_Scalars}. A special Makefile called
19474 @code{Makefile.adalib} is provided to that effect and can be found in
19475 the directory containing the GNAT library. The location of this
19476 directory depends on the way the GNAT environment has been installed and can
19477 be determined by means of the command:
19478
19479 @smallexample
19480 $ gnatls -v
19481 @end smallexample
19482
19483 @noindent
19484 The last entry in the object search path usually contains the
19485 gnat library. This Makefile contains its own documentation and in
19486 particular the set of instructions needed to rebuild a new library and
19487 to use it.
19488
19489 @node Using the GNU make Utility
19490 @chapter Using the GNU @code{make} Utility
19491 @findex make
19492
19493 @noindent
19494 This chapter offers some examples of makefiles that solve specific
19495 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19496 make, make, GNU @code{make}}), nor does it try to replace the
19497 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19498
19499 All the examples in this section are specific to the GNU version of
19500 make. Although @command{make} is a standard utility, and the basic language
19501 is the same, these examples use some advanced features found only in
19502 @code{GNU make}.
19503
19504 @menu
19505 * Using gnatmake in a Makefile::
19506 * Automatically Creating a List of Directories::
19507 * Generating the Command Line Switches::
19508 * Overcoming Command Line Length Limits::
19509 @end menu
19510
19511 @node Using gnatmake in a Makefile
19512 @section Using gnatmake in a Makefile
19513 @findex makefile
19514 @cindex GNU make
19515
19516 @noindent
19517 Complex project organizations can be handled in a very powerful way by
19518 using GNU make combined with gnatmake. For instance, here is a Makefile
19519 which allows you to build each subsystem of a big project into a separate
19520 shared library. Such a makefile allows you to significantly reduce the link
19521 time of very big applications while maintaining full coherence at
19522 each step of the build process.
19523
19524 The list of dependencies are handled automatically by
19525 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19526 the appropriate directories.
19527
19528 Note that you should also read the example on how to automatically
19529 create the list of directories
19530 (@pxref{Automatically Creating a List of Directories})
19531 which might help you in case your project has a lot of subdirectories.
19532
19533 @smallexample
19534 @iftex
19535 @leftskip=0cm
19536 @font@heightrm=cmr8
19537 @heightrm
19538 @end iftex
19539 ## This Makefile is intended to be used with the following directory
19540 ## configuration:
19541 ##  - The sources are split into a series of csc (computer software components)
19542 ##    Each of these csc is put in its own directory.
19543 ##    Their name are referenced by the directory names.
19544 ##    They will be compiled into shared library (although this would also work
19545 ##    with static libraries
19546 ##  - The main program (and possibly other packages that do not belong to any
19547 ##    csc is put in the top level directory (where the Makefile is).
19548 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
19549 ##                    \_ second_csc (sources) __ lib (will contain the library)
19550 ##                    \_ @dots{}
19551 ## Although this Makefile is build for shared library, it is easy to modify
19552 ## to build partial link objects instead (modify the lines with -shared and
19553 ## gnatlink below)
19554 ##
19555 ## With this makefile, you can change any file in the system or add any new
19556 ## file, and everything will be recompiled correctly (only the relevant shared
19557 ## objects will be recompiled, and the main program will be re-linked).
19558
19559 # The list of computer software component for your project. This might be
19560 # generated automatically.
19561 CSC_LIST=aa bb cc
19562
19563 # Name of the main program (no extension)
19564 MAIN=main
19565
19566 # If we need to build objects with -fPIC, uncomment the following line
19567 #NEED_FPIC=-fPIC
19568
19569 # The following variable should give the directory containing libgnat.so
19570 # You can get this directory through 'gnatls -v'. This is usually the last
19571 # directory in the Object_Path.
19572 GLIB=@dots{}
19573
19574 # The directories for the libraries
19575 # (This macro expands the list of CSC to the list of shared libraries, you
19576 # could simply use the expanded form:
19577 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19578 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19579
19580 $@{MAIN@}: objects $@{LIB_DIR@}
19581     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19582     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19583
19584 objects::
19585     # recompile the sources
19586     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19587
19588 # Note: In a future version of GNAT, the following commands will be simplified
19589 # by a new tool, gnatmlib
19590 $@{LIB_DIR@}:
19591     mkdir -p $@{dir $@@ @}
19592     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19593     cd $@{dir $@@ @} && cp -f ../*.ali .
19594
19595 # The dependencies for the modules
19596 # Note that we have to force the expansion of *.o, since in some cases
19597 # make won't be able to do it itself.
19598 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19599 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19600 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19601
19602 # Make sure all of the shared libraries are in the path before starting the
19603 # program
19604 run::
19605     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19606
19607 clean::
19608     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19609     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19610     $@{RM@} $@{CSC_LIST:%=%/*.o@}
19611     $@{RM@} *.o *.ali $@{MAIN@}
19612 @end smallexample
19613
19614 @node Automatically Creating a List of Directories
19615 @section Automatically Creating a List of Directories
19616
19617 @noindent
19618 In most makefiles, you will have to specify a list of directories, and
19619 store it in a variable. For small projects, it is often easier to
19620 specify each of them by hand, since you then have full control over what
19621 is the proper order for these directories, which ones should be
19622 included.
19623
19624 However, in larger projects, which might involve hundreds of
19625 subdirectories, it might be more convenient to generate this list
19626 automatically.
19627
19628 The example below presents two methods. The first one, although less
19629 general, gives you more control over the list. It involves wildcard
19630 characters, that are automatically expanded by @command{make}. Its
19631 shortcoming is that you need to explicitly specify some of the
19632 organization of your project, such as for instance the directory tree
19633 depth, whether some directories are found in a separate tree, @enddots{}
19634
19635 The second method is the most general one. It requires an external
19636 program, called @command{find}, which is standard on all Unix systems. All
19637 the directories found under a given root directory will be added to the
19638 list.
19639
19640 @smallexample
19641 @iftex
19642 @leftskip=0cm
19643 @font@heightrm=cmr8
19644 @heightrm
19645 @end iftex
19646 # The examples below are based on the following directory hierarchy:
19647 # All the directories can contain any number of files
19648 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
19649 #                       ->  ab
19650 #                       ->  ac
19651 #                ->  b  ->  ba  ->  baa
19652 #                       ->  bb
19653 #                       ->  bc
19654 # This Makefile creates a variable called DIRS, that can be reused any time
19655 # you need this list (see the other examples in this section)
19656
19657 # The root of your project's directory hierarchy
19658 ROOT_DIRECTORY=.
19659
19660 ####
19661 # First method: specify explicitly the list of directories
19662 # This allows you to specify any subset of all the directories you need.
19663 ####
19664
19665 DIRS := a/aa/ a/ab/ b/ba/
19666
19667 ####
19668 # Second method: use wildcards
19669 # Note that the argument(s) to wildcard below should end with a '/'.
19670 # Since wildcards also return file names, we have to filter them out
19671 # to avoid duplicate directory names.
19672 # We thus use make's @code{dir} and @code{sort} functions.
19673 # It sets DIRs to the following value (note that the directories aaa and baa
19674 # are not given, unless you change the arguments to wildcard).
19675 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19676 ####
19677
19678 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19679                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19680
19681 ####
19682 # Third method: use an external program
19683 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19684 # This is the most complete command: it sets DIRs to the following value:
19685 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19686 ####
19687
19688 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19689
19690 @end smallexample
19691
19692 @node Generating the Command Line Switches
19693 @section Generating the Command Line Switches
19694
19695 @noindent
19696 Once you have created the list of directories as explained in the
19697 previous section (@pxref{Automatically Creating a List of Directories}),
19698 you can easily generate the command line arguments to pass to gnatmake.
19699
19700 For the sake of completeness, this example assumes that the source path
19701 is not the same as the object path, and that you have two separate lists
19702 of directories.
19703
19704 @smallexample
19705 # see "Automatically creating a list of directories" to create
19706 # these variables
19707 SOURCE_DIRS=
19708 OBJECT_DIRS=
19709
19710 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19711 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19712
19713 all:
19714         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19715 @end smallexample
19716
19717 @node Overcoming Command Line Length Limits
19718 @section Overcoming Command Line Length Limits
19719
19720 @noindent
19721 One problem that might be encountered on big projects is that many
19722 operating systems limit the length of the command line. It is thus hard to give
19723 gnatmake the list of source and object directories.
19724
19725 This example shows how you can set up environment variables, which will
19726 make @command{gnatmake} behave exactly as if the directories had been
19727 specified on the command line, but have a much higher length limit (or
19728 even none on most systems).
19729
19730 It assumes that you have created a list of directories in your Makefile,
19731 using one of the methods presented in
19732 @ref{Automatically Creating a List of Directories}.
19733 For the sake of completeness, we assume that the object
19734 path (where the ALI files are found) is different from the sources patch.
19735
19736 Note a small trick in the Makefile below: for efficiency reasons, we
19737 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19738 expanded immediately by @code{make}. This way we overcome the standard
19739 make behavior which is to expand the variables only when they are
19740 actually used.
19741
19742 On Windows, if you are using the standard Windows command shell, you must
19743 replace colons with semicolons in the assignments to these variables.
19744
19745 @smallexample
19746 @iftex
19747 @leftskip=0cm
19748 @font@heightrm=cmr8
19749 @heightrm
19750 @end iftex
19751 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19752 # This is the same thing as putting the -I arguments on the command line.
19753 # (the equivalent of using -aI on the command line would be to define
19754 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19755 # You can of course have different values for these variables.
19756 #
19757 # Note also that we need to keep the previous values of these variables, since
19758 # they might have been set before running 'make' to specify where the GNAT
19759 # library is installed.
19760
19761 # see "Automatically creating a list of directories" to create these
19762 # variables
19763 SOURCE_DIRS=
19764 OBJECT_DIRS=
19765
19766 empty:=
19767 space:=$@{empty@} $@{empty@}
19768 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19769 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19770 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19771 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19772 export ADA_INCLUDE_PATH
19773 export ADA_OBJECT_PATH
19774
19775 all:
19776         gnatmake main_unit
19777 @end smallexample
19778 @end ifclear
19779
19780 @node Memory Management Issues
19781 @chapter Memory Management Issues
19782
19783 @noindent
19784 This chapter describes some useful memory pools provided in the GNAT library
19785 and in particular the GNAT Debug Pool facility, which can be used to detect
19786 incorrect uses of access values (including ``dangling references'').
19787 @ifclear vms
19788 It also describes the @command{gnatmem} tool, which can be used to track down
19789 ``memory leaks''.
19790 @end ifclear
19791
19792 @menu
19793 * Some Useful Memory Pools::
19794 * The GNAT Debug Pool Facility::
19795 @ifclear vms
19796 * The gnatmem Tool::
19797 @end ifclear
19798 @end menu
19799
19800 @node Some Useful Memory Pools
19801 @section Some Useful Memory Pools
19802 @findex Memory Pool
19803 @cindex storage, pool
19804
19805 @noindent
19806 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19807 storage pool. Allocations use the standard system call @code{malloc} while
19808 deallocations use the standard system call @code{free}. No reclamation is
19809 performed when the pool goes out of scope. For performance reasons, the
19810 standard default Ada allocators/deallocators do not use any explicit storage
19811 pools but if they did, they could use this storage pool without any change in
19812 behavior. That is why this storage pool is used  when the user
19813 manages to make the default implicit allocator explicit as in this example:
19814 @smallexample @c ada
19815    type T1 is access Something;
19816     -- no Storage pool is defined for T2
19817    type T2 is access Something_Else;
19818    for T2'Storage_Pool use T1'Storage_Pool;
19819    -- the above is equivalent to
19820    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19821 @end smallexample
19822
19823 @noindent
19824 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19825 pool. The allocation strategy is similar to @code{Pool_Local}'s
19826 except that the all
19827 storage allocated with this pool is reclaimed when the pool object goes out of
19828 scope. This pool provides a explicit mechanism similar to the implicit one
19829 provided by several Ada 83 compilers for allocations performed through a local
19830 access type and whose purpose was to reclaim memory when exiting the
19831 scope of a given local access. As an example, the following program does not
19832 leak memory even though it does not perform explicit deallocation:
19833
19834 @smallexample @c ada
19835 with System.Pool_Local;
19836 procedure Pooloc1 is
19837    procedure Internal is
19838       type A is access Integer;
19839       X : System.Pool_Local.Unbounded_Reclaim_Pool;
19840       for A'Storage_Pool use X;
19841       v : A;
19842    begin
19843       for I in  1 .. 50 loop
19844          v := new Integer;
19845       end loop;
19846    end Internal;
19847 begin
19848    for I in  1 .. 100 loop
19849       Internal;
19850    end loop;
19851 end Pooloc1;
19852 @end smallexample
19853
19854 @noindent
19855 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19856 @code{Storage_Size} is specified for an access type.
19857 The whole storage for the pool is
19858 allocated at once, usually on the stack at the point where the access type is
19859 elaborated. It is automatically reclaimed when exiting the scope where the
19860 access type is defined. This package is not intended to be used directly by the
19861 user and it is implicitly used for each such declaration:
19862
19863 @smallexample @c ada
19864    type T1 is access Something;
19865    for T1'Storage_Size use 10_000;
19866 @end smallexample
19867
19868 @node The GNAT Debug Pool Facility
19869 @section The GNAT Debug Pool Facility
19870 @findex Debug Pool
19871 @cindex storage, pool, memory corruption
19872
19873 @noindent
19874 The use of unchecked deallocation and unchecked conversion can easily
19875 lead to incorrect memory references. The problems generated by such
19876 references are usually difficult to tackle because the symptoms can be
19877 very remote from the origin of the problem. In such cases, it is
19878 very helpful to detect the problem as early as possible. This is the
19879 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19880
19881 In order to use the GNAT specific debugging pool, the user must
19882 associate a debug pool object with each of the access types that may be
19883 related to suspected memory problems. See Ada Reference Manual 13.11.
19884 @smallexample @c ada
19885 type Ptr is access Some_Type;
19886 Pool : GNAT.Debug_Pools.Debug_Pool;
19887 for Ptr'Storage_Pool use Pool;
19888 @end smallexample
19889
19890 @noindent
19891 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19892 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19893 allow the user to redefine allocation and deallocation strategies. They
19894 also provide a checkpoint for each dereference, through the use of
19895 the primitive operation @code{Dereference} which is implicitly called at
19896 each dereference of an access value.
19897
19898 Once an access type has been associated with a debug pool, operations on
19899 values of the type may raise four distinct exceptions,
19900 which correspond to four potential kinds of memory corruption:
19901 @itemize @bullet
19902 @item
19903 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19904 @item
19905 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19906 @item
19907 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19908 @item
19909 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19910 @end itemize
19911
19912 @noindent
19913 For types associated with a Debug_Pool, dynamic allocation is performed using
19914 the standard GNAT allocation routine. References to all allocated chunks of
19915 memory are kept in an internal dictionary. Several deallocation strategies are
19916 provided, whereupon the user can choose to release the memory to the system,
19917 keep it allocated for further invalid access checks, or fill it with an easily
19918 recognizable pattern for debug sessions. The memory pattern is the old IBM
19919 hexadecimal convention: @code{16#DEADBEEF#}.
19920
19921 See the documentation in the file g-debpoo.ads for more information on the
19922 various strategies.
19923
19924 Upon each dereference, a check is made that the access value denotes a
19925 properly allocated memory location. Here is a complete example of use of
19926 @code{Debug_Pools}, that includes typical instances of  memory corruption:
19927 @smallexample @c ada
19928 @iftex
19929 @leftskip=0cm
19930 @end iftex
19931 with Gnat.Io; use Gnat.Io;
19932 with Unchecked_Deallocation;
19933 with Unchecked_Conversion;
19934 with GNAT.Debug_Pools;
19935 with System.Storage_Elements;
19936 with Ada.Exceptions; use Ada.Exceptions;
19937 procedure Debug_Pool_Test is
19938
19939    type T is access Integer;
19940    type U is access all T;
19941
19942    P : GNAT.Debug_Pools.Debug_Pool;
19943    for T'Storage_Pool use P;
19944
19945    procedure Free is new Unchecked_Deallocation (Integer, T);
19946    function UC is new Unchecked_Conversion (U, T);
19947    A, B : aliased T;
19948
19949    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
19950
19951 begin
19952    Info (P);
19953    A := new Integer;
19954    B := new Integer;
19955    B := A;
19956    Info (P);
19957    Free (A);
19958    begin
19959       Put_Line (Integer'Image(B.all));
19960    exception
19961       when E : others => Put_Line ("raised: " & Exception_Name (E));
19962    end;
19963    begin
19964       Free (B);
19965    exception
19966       when E : others => Put_Line ("raised: " & Exception_Name (E));
19967    end;
19968    B := UC(A'Access);
19969    begin
19970       Put_Line (Integer'Image(B.all));
19971    exception
19972       when E : others => Put_Line ("raised: " & Exception_Name (E));
19973    end;
19974    begin
19975       Free (B);
19976    exception
19977       when E : others => Put_Line ("raised: " & Exception_Name (E));
19978    end;
19979    Info (P);
19980 end Debug_Pool_Test;
19981 @end smallexample
19982
19983 @noindent
19984 The debug pool mechanism provides the following precise diagnostics on the
19985 execution of this erroneous program:
19986 @smallexample
19987 Debug Pool info:
19988   Total allocated bytes :  0
19989   Total deallocated bytes :  0
19990   Current Water Mark:  0
19991   High Water Mark:  0
19992
19993 Debug Pool info:
19994   Total allocated bytes :  8
19995   Total deallocated bytes :  0
19996   Current Water Mark:  8
19997   High Water Mark:  8
19998
19999 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
20000 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
20001 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
20002 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
20003 Debug Pool info:
20004   Total allocated bytes :  8
20005   Total deallocated bytes :  4
20006   Current Water Mark:  4
20007   High Water Mark:  8
20008 @end smallexample
20009
20010 @ifclear vms
20011 @node The gnatmem Tool
20012 @section The @command{gnatmem} Tool
20013 @findex gnatmem
20014
20015 @noindent
20016 The @code{gnatmem} utility monitors dynamic allocation and
20017 deallocation activity in a program, and displays information about
20018 incorrect deallocations and possible sources of memory leaks.
20019 It is designed to work in association with a static runtime library
20020 only and in this context provides three types of information:
20021 @itemize @bullet
20022 @item
20023 General information concerning memory management, such as the total
20024 number of allocations and deallocations, the amount of allocated
20025 memory and the high water mark, i.e.@: the largest amount of allocated
20026 memory in the course of program execution.
20027
20028 @item
20029 Backtraces for all incorrect deallocations, that is to say deallocations
20030 which do not correspond to a valid allocation.
20031
20032 @item
20033 Information on each allocation that is potentially the origin of a memory
20034 leak.
20035 @end itemize
20036
20037 @menu
20038 * Running gnatmem::
20039 * Switches for gnatmem::
20040 * Example of gnatmem Usage::
20041 @end menu
20042
20043 @node Running gnatmem
20044 @subsection Running @code{gnatmem}
20045
20046 @noindent
20047 @code{gnatmem} makes use of the output created by the special version of
20048 allocation and deallocation routines that record call information. This
20049 allows to obtain accurate dynamic memory usage history at a minimal cost to
20050 the execution speed. Note however, that @code{gnatmem} is not supported on
20051 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
20052 Solaris and Windows NT/2000/XP (x86).
20053
20054 @noindent
20055 The @code{gnatmem} command has the form
20056
20057 @smallexample
20058    $ gnatmem @ovar{switches} user_program
20059 @end smallexample
20060
20061 @noindent
20062 The program must have been linked with the instrumented version of the
20063 allocation and deallocation routines. This is done by linking with the
20064 @file{libgmem.a} library. For correct symbolic backtrace information,
20065 the user program should be compiled with debugging options
20066 (see @ref{Switches for gcc}). For example to build @file{my_program}:
20067
20068 @smallexample
20069 $ gnatmake -g my_program -largs -lgmem
20070 @end smallexample
20071
20072 @noindent
20073 As library @file{libgmem.a} contains an alternate body for package
20074 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
20075 when an executable is linked with library @file{libgmem.a}. It is then not
20076 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
20077
20078 @noindent
20079 When @file{my_program} is executed, the file @file{gmem.out} is produced.
20080 This file contains information about all allocations and deallocations
20081 performed by the program. It is produced by the instrumented allocations and
20082 deallocations routines and will be used by @code{gnatmem}.
20083
20084 In order to produce symbolic backtrace information for allocations and
20085 deallocations performed by the GNAT run-time library, you need to use a
20086 version of that library that has been compiled with the @option{-g} switch
20087 (see @ref{Rebuilding the GNAT Run-Time Library}).
20088
20089 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
20090 examine. If the location of @file{gmem.out} file was not explicitly supplied by
20091 @option{-i} switch, gnatmem will assume that this file can be found in the
20092 current directory. For example, after you have executed @file{my_program},
20093 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
20094
20095 @smallexample
20096 $ gnatmem my_program
20097 @end smallexample
20098
20099 @noindent
20100 This will produce the output with the following format:
20101
20102 *************** debut cc
20103 @smallexample
20104 $ gnatmem my_program
20105
20106 Global information
20107 ------------------
20108    Total number of allocations        :  45
20109    Total number of deallocations      :   6
20110    Final Water Mark (non freed mem)   :  11.29 Kilobytes
20111    High Water Mark                    :  11.40 Kilobytes
20112
20113 .
20114 .
20115 .
20116 Allocation Root # 2
20117 -------------------
20118  Number of non freed allocations    :  11
20119  Final Water Mark (non freed mem)   :   1.16 Kilobytes
20120  High Water Mark                    :   1.27 Kilobytes
20121  Backtrace                          :
20122    my_program.adb:23 my_program.alloc
20123 .
20124 .
20125 .
20126 @end smallexample
20127
20128 The first block of output gives general information. In this case, the
20129 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
20130 Unchecked_Deallocation routine occurred.
20131
20132 @noindent
20133 Subsequent paragraphs display  information on all allocation roots.
20134 An allocation root is a specific point in the execution of the program
20135 that generates some dynamic allocation, such as a ``@code{@b{new}}''
20136 construct. This root is represented by an execution backtrace (or subprogram
20137 call stack). By default the backtrace depth for allocations roots is 1, so
20138 that a root corresponds exactly to a source location. The backtrace can
20139 be made deeper, to make the root more specific.
20140
20141 @node Switches for gnatmem
20142 @subsection Switches for @code{gnatmem}
20143
20144 @noindent
20145 @code{gnatmem} recognizes the following switches:
20146
20147 @table @option
20148
20149 @item -q
20150 @cindex @option{-q} (@code{gnatmem})
20151 Quiet. Gives the minimum output needed to identify the origin of the
20152 memory leaks. Omits statistical information.
20153
20154 @item @var{N}
20155 @cindex @var{N} (@code{gnatmem})
20156 N is an integer literal (usually between 1 and 10) which controls the
20157 depth of the backtraces defining allocation root. The default value for
20158 N is 1. The deeper the backtrace, the more precise the localization of
20159 the root. Note that the total number of roots can depend on this
20160 parameter. This parameter must be specified @emph{before} the name of the
20161 executable to be analyzed, to avoid ambiguity.
20162
20163 @item -b n
20164 @cindex @option{-b} (@code{gnatmem})
20165 This switch has the same effect as just depth parameter.
20166
20167 @item -i @var{file}
20168 @cindex @option{-i} (@code{gnatmem})
20169 Do the @code{gnatmem} processing starting from @file{file}, rather than
20170 @file{gmem.out} in the current directory.
20171
20172 @item -m n
20173 @cindex @option{-m} (@code{gnatmem})
20174 This switch causes @code{gnatmem} to mask the allocation roots that have less
20175 than n leaks. The default value is 1. Specifying the value of 0 will allow to
20176 examine even the roots that didn't result in leaks.
20177
20178 @item -s order
20179 @cindex @option{-s} (@code{gnatmem})
20180 This switch causes @code{gnatmem} to sort the allocation roots according to the
20181 specified order of sort criteria, each identified by a single letter. The
20182 currently supported criteria are @code{n, h, w} standing respectively for
20183 number of unfreed allocations, high watermark, and final watermark
20184 corresponding to a specific root. The default order is @code{nwh}.
20185
20186 @end table
20187
20188 @node Example of gnatmem Usage
20189 @subsection Example of @code{gnatmem} Usage
20190
20191 @noindent
20192 The following example shows the use of @code{gnatmem}
20193 on a simple memory-leaking program.
20194 Suppose that we have the following Ada program:
20195
20196 @smallexample @c ada
20197 @group
20198 @cartouche
20199 with Unchecked_Deallocation;
20200 procedure Test_Gm is
20201
20202    type T is array (1..1000) of Integer;
20203    type Ptr is access T;
20204    procedure Free is new Unchecked_Deallocation (T, Ptr);
20205    A : Ptr;
20206
20207    procedure My_Alloc is
20208    begin
20209       A := new T;
20210    end My_Alloc;
20211
20212    procedure My_DeAlloc is
20213       B : Ptr := A;
20214    begin
20215       Free (B);
20216    end My_DeAlloc;
20217
20218 begin
20219    My_Alloc;
20220    for I in 1 .. 5 loop
20221       for J in I .. 5 loop
20222          My_Alloc;
20223       end loop;
20224       My_Dealloc;
20225    end loop;
20226 end;
20227 @end cartouche
20228 @end group
20229 @end smallexample
20230
20231 @noindent
20232 The program needs to be compiled with debugging option and linked with
20233 @code{gmem} library:
20234
20235 @smallexample
20236 $ gnatmake -g test_gm -largs -lgmem
20237 @end smallexample
20238
20239 @noindent
20240 Then we execute the program as usual:
20241
20242 @smallexample
20243 $ test_gm
20244 @end smallexample
20245
20246 @noindent
20247 Then @code{gnatmem} is invoked simply with
20248 @smallexample
20249 $ gnatmem test_gm
20250 @end smallexample
20251
20252 @noindent
20253 which produces the following output (result may vary on different platforms):
20254
20255 @smallexample
20256 Global information
20257 ------------------
20258    Total number of allocations        :  18
20259    Total number of deallocations      :   5
20260    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20261    High Water Mark                    :  56.90 Kilobytes
20262
20263 Allocation Root # 1
20264 -------------------
20265  Number of non freed allocations    :  11
20266  Final Water Mark (non freed mem)   :  42.97 Kilobytes
20267  High Water Mark                    :  46.88 Kilobytes
20268  Backtrace                          :
20269    test_gm.adb:11 test_gm.my_alloc
20270
20271 Allocation Root # 2
20272 -------------------
20273  Number of non freed allocations    :   1
20274  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20275  High Water Mark                    :  10.02 Kilobytes
20276  Backtrace                          :
20277    s-secsta.adb:81 system.secondary_stack.ss_init
20278
20279 Allocation Root # 3
20280 -------------------
20281  Number of non freed allocations    :   1
20282  Final Water Mark (non freed mem)   :  12 Bytes
20283  High Water Mark                    :  12 Bytes
20284  Backtrace                          :
20285    s-secsta.adb:181 system.secondary_stack.ss_init
20286 @end smallexample
20287
20288 @noindent
20289 Note that the GNAT run time contains itself a certain number of
20290 allocations that have no  corresponding deallocation,
20291 as shown here for root #2 and root
20292 #3. This is a normal behavior when the number of non-freed allocations
20293 is one, it allocates dynamic data structures that the run time needs for
20294 the complete lifetime of the program. Note also that there is only one
20295 allocation root in the user program with a single line back trace:
20296 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
20297 program shows that 'My_Alloc' is called at 2 different points in the
20298 source (line 21 and line 24). If those two allocation roots need to be
20299 distinguished, the backtrace depth parameter can be used:
20300
20301 @smallexample
20302 $ gnatmem 3 test_gm
20303 @end smallexample
20304
20305 @noindent
20306 which will give the following output:
20307
20308 @smallexample
20309 Global information
20310 ------------------
20311    Total number of allocations        :  18
20312    Total number of deallocations      :   5
20313    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20314    High Water Mark                    :  56.90 Kilobytes
20315
20316 Allocation Root # 1
20317 -------------------
20318  Number of non freed allocations    :  10
20319  Final Water Mark (non freed mem)   :  39.06 Kilobytes
20320  High Water Mark                    :  42.97 Kilobytes
20321  Backtrace                          :
20322    test_gm.adb:11 test_gm.my_alloc
20323    test_gm.adb:24 test_gm
20324    b_test_gm.c:52 main
20325
20326 Allocation Root # 2
20327 -------------------
20328  Number of non freed allocations    :   1
20329  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20330  High Water Mark                    :  10.02 Kilobytes
20331  Backtrace                          :
20332    s-secsta.adb:81  system.secondary_stack.ss_init
20333    s-secsta.adb:283 <system__secondary_stack___elabb>
20334    b_test_gm.c:33   adainit
20335
20336 Allocation Root # 3
20337 -------------------
20338  Number of non freed allocations    :   1
20339  Final Water Mark (non freed mem)   :   3.91 Kilobytes
20340  High Water Mark                    :   3.91 Kilobytes
20341  Backtrace                          :
20342    test_gm.adb:11 test_gm.my_alloc
20343    test_gm.adb:21 test_gm
20344    b_test_gm.c:52 main
20345
20346 Allocation Root # 4
20347 -------------------
20348  Number of non freed allocations    :   1
20349  Final Water Mark (non freed mem)   :  12 Bytes
20350  High Water Mark                    :  12 Bytes
20351  Backtrace                          :
20352    s-secsta.adb:181 system.secondary_stack.ss_init
20353    s-secsta.adb:283 <system__secondary_stack___elabb>
20354    b_test_gm.c:33   adainit
20355 @end smallexample
20356
20357 @noindent
20358 The allocation root #1 of the first example has been split in 2 roots #1
20359 and #3 thanks to the more precise associated backtrace.
20360
20361 @end ifclear
20362
20363 @node Stack Related Facilities
20364 @chapter Stack Related Facilities
20365
20366 @noindent
20367 This chapter describes some useful tools associated with stack
20368 checking and analysis. In
20369 particular, it deals with dynamic and static stack usage measurements.
20370
20371 @menu
20372 * Stack Overflow Checking::
20373 * Static Stack Usage Analysis::
20374 * Dynamic Stack Usage Analysis::
20375 @end menu
20376
20377 @node Stack Overflow Checking
20378 @section Stack Overflow Checking
20379 @cindex Stack Overflow Checking
20380 @cindex -fstack-check
20381
20382 @noindent
20383 For most operating systems, @command{gcc} does not perform stack overflow
20384 checking by default. This means that if the main environment task or
20385 some other task exceeds the available stack space, then unpredictable
20386 behavior will occur. Most native systems offer some level of protection by
20387 adding a guard page at the end of each task stack. This mechanism is usually
20388 not enough for dealing properly with stack overflow situations because
20389 a large local variable could ``jump'' above the guard page.
20390 Furthermore, when the
20391 guard page is hit, there may not be any space left on the stack for executing
20392 the exception propagation code. Enabling stack checking avoids
20393 such situations.
20394
20395 To activate stack checking, compile all units with the gcc option
20396 @option{-fstack-check}. For example:
20397
20398 @smallexample
20399 gcc -c -fstack-check package1.adb
20400 @end smallexample
20401
20402 @noindent
20403 Units compiled with this option will generate extra instructions to check
20404 that any use of the stack (for procedure calls or for declaring local
20405 variables in declare blocks) does not exceed the available stack space.
20406 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20407
20408 For declared tasks, the stack size is controlled by the size
20409 given in an applicable @code{Storage_Size} pragma or by the value specified
20410 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20411 the default size as defined in the GNAT runtime otherwise.
20412
20413 For the environment task, the stack size depends on
20414 system defaults and is unknown to the compiler. Stack checking
20415 may still work correctly if a fixed
20416 size stack is allocated, but this cannot be guaranteed.
20417 @ifclear vms
20418 To ensure that a clean exception is signalled for stack
20419 overflow, set the environment variable
20420 @env{GNAT_STACK_LIMIT} to indicate the maximum
20421 stack area that can be used, as in:
20422 @cindex GNAT_STACK_LIMIT
20423
20424 @smallexample
20425 SET GNAT_STACK_LIMIT 1600
20426 @end smallexample
20427
20428 @noindent
20429 The limit is given in kilobytes, so the above declaration would
20430 set the stack limit of the environment task to 1.6 megabytes.
20431 Note that the only purpose of this usage is to limit the amount
20432 of stack used by the environment task. If it is necessary to
20433 increase the amount of stack for the environment task, then this
20434 is an operating systems issue, and must be addressed with the
20435 appropriate operating systems commands.
20436 @end ifclear
20437 @ifset vms
20438 To have a fixed size stack in the environment task, the stack must be put
20439 in the P0 address space and its size specified.  Use these switches to
20440 create a p0 image:
20441
20442 @smallexample
20443 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20444 @end smallexample
20445
20446 @noindent
20447 The quotes are required to keep case.  The number after @samp{STACK=} is the
20448 size of the environmental task stack in pagelets (512 bytes).  In this example
20449 the stack size is about 2 megabytes.
20450
20451 @noindent
20452 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20453 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
20454 more details about the @option{/p0image} qualifier and the @option{stack}
20455 option.
20456 @end ifset
20457
20458 @node Static Stack Usage Analysis
20459 @section Static Stack Usage Analysis
20460 @cindex Static Stack Usage Analysis
20461 @cindex -fstack-usage
20462
20463 @noindent
20464 A unit compiled with @option{-fstack-usage} will generate an extra file
20465 that specifies
20466 the maximum amount of stack used, on a per-function basis.
20467 The file has the same
20468 basename as the target object file with a @file{.su} extension.
20469 Each line of this file is made up of three fields:
20470
20471 @itemize
20472 @item
20473 The name of the function.
20474 @item
20475 A number of bytes.
20476 @item
20477 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20478 @end itemize
20479
20480 The second field corresponds to the size of the known part of the function
20481 frame.
20482
20483 The qualifier @code{static} means that the function frame size
20484 is purely static.
20485 It usually means that all local variables have a static size.
20486 In this case, the second field is a reliable measure of the function stack
20487 utilization.
20488
20489 The qualifier @code{dynamic} means that the function frame size is not static.
20490 It happens mainly when some local variables have a dynamic size. When this
20491 qualifier appears alone, the second field is not a reliable measure
20492 of the function stack analysis. When it is qualified with  @code{bounded}, it
20493 means that the second field is a reliable maximum of the function stack
20494 utilization.
20495
20496 @node Dynamic Stack Usage Analysis
20497 @section Dynamic Stack Usage Analysis
20498
20499 @noindent
20500 It is possible to measure the maximum amount of stack used by a task, by
20501 adding a switch to @command{gnatbind}, as:
20502
20503 @smallexample
20504 $ gnatbind -u0 file
20505 @end smallexample
20506
20507 @noindent
20508 With this option, at each task termination, its stack usage is  output on
20509 @file{stderr}.
20510 It is not always convenient to output the stack usage when the program
20511 is still running. Hence, it is possible to delay this output until program
20512 termination. for a given number of tasks specified as the argument of the
20513 @option{-u} option. For instance:
20514
20515 @smallexample
20516 $ gnatbind -u100 file
20517 @end smallexample
20518
20519 @noindent
20520 will buffer the stack usage information of the first 100 tasks to terminate and
20521 output this info at program termination. Results are displayed in four
20522 columns:
20523
20524 @noindent
20525 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
20526
20527 @noindent
20528 where:
20529
20530 @table @emph
20531 @item Index
20532 is a number associated with each task.
20533
20534 @item Task Name
20535 is the name of the task analyzed.
20536
20537 @item Stack Size
20538 is the maximum size for the stack.
20539
20540 @item Stack Usage
20541 is the measure done by the stack analyzer. In order to prevent overflow, the stack
20542 is not entirely analyzed, and it's not possible to know exactly how
20543 much has actually been used. The report thus contains the theoretical stack usage
20544 (Value) and the possible variation (Variation) around this value.
20545
20546 @end table
20547
20548 @noindent
20549 The environment task stack, e.g., the stack that contains the main unit, is
20550 only processed when the environment variable GNAT_STACK_LIMIT is set.
20551
20552
20553 @c *********************************
20554 @c *            GNATCHECK          *
20555 @c *********************************
20556 @node Verifying Properties Using gnatcheck
20557 @chapter Verifying Properties Using @command{gnatcheck}
20558 @findex gnatcheck
20559 @cindex @command{gnatcheck}
20560
20561 @noindent
20562 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20563 of Ada source files according to a given set of semantic rules.
20564 @cindex ASIS
20565
20566 In order to check compliance with a given rule, @command{gnatcheck} has to
20567 semantically analyze the Ada sources.
20568 Therefore, checks can only be performed on
20569 legal Ada units. Moreover, when a unit depends semantically upon units located
20570 outside the current directory, the source search path has to be provided when
20571 calling @command{gnatcheck}, either through a specified project file or
20572 through @command{gnatcheck} switches as described below.
20573
20574 A number of rules are predefined in @command{gnatcheck} and are described
20575 later in this chapter.
20576 You can also add new rules, by modifying the @command{gnatcheck} code and
20577 rebuilding the tool. In order to add a simple rule making some local checks,
20578 a small amount of straightforward ASIS-based programming is usually needed.
20579
20580 Project support for @command{gnatcheck} is provided by the GNAT
20581 driver (see @ref{The GNAT Driver and Project Files}).
20582
20583 Invoking @command{gnatcheck} on the command line has the form:
20584
20585 @smallexample
20586 $ gnatcheck @ovar{switches}  @{@var{filename}@}
20587       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20588       @r{[}-cargs @var{gcc_switches}@r{]} @r{[}-rules @var{rule_options}@r{]}
20589 @end smallexample
20590
20591 @noindent
20592 where
20593 @itemize @bullet
20594 @item
20595 @var{switches} specify the general tool options
20596
20597 @item
20598 Each @var{filename} is the name (including the extension) of a source
20599 file to process. ``Wildcards'' are allowed, and
20600 the file name may contain path information.
20601
20602 @item
20603 Each @var{arg_list_filename} is the name (including the extension) of a text
20604 file containing the names of the source files to process, separated by spaces
20605 or line breaks.
20606
20607 @item
20608 @var{gcc_switches} is a list of switches for
20609 @command{gcc}. They will be passed on to all compiler invocations made by
20610 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20611 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20612 and use the @option{-gnatec} switch to set the configuration file.
20613
20614 @item
20615 @var{rule_options} is a list of options for controlling a set of
20616 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20617 @end itemize
20618
20619 @noindent
20620 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be supplied.
20621
20622 @menu
20623 * Format of the Report File::
20624 * General gnatcheck Switches::
20625 * gnatcheck Rule Options::
20626 * Adding the Results of Compiler Checks to gnatcheck Output::
20627 * Project-Wide Checks::
20628 * Predefined Rules::
20629 @end menu
20630
20631 @node Format of the Report File
20632 @section Format of the Report File
20633 @cindex Report file (for @code{gnatcheck})
20634
20635 @noindent
20636 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20637 rule violations.
20638 It also creates a text file  that
20639 contains the complete report of the last gnatcheck run. By default this file is
20640 named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the current
20641 directory, @option{^-o^/OUTPUT^} option can be used to change the name and/or
20642 location of the report file. This report contains:
20643 @itemize @bullet
20644 @item a list of the Ada source files being checked,
20645 @item a list of enabled and disabled rules,
20646 @item a list of the diagnostic messages, ordered in three different ways
20647 and collected in three separate
20648 sections. Section 1 contains the raw list of diagnostic messages. It
20649 corresponds to the output going to @file{stdout}. Section 2 contains
20650 messages ordered by rules.
20651 Section 3 contains messages ordered by source files.
20652 @end itemize
20653
20654 @node General gnatcheck Switches
20655 @section General @command{gnatcheck} Switches
20656
20657 @noindent
20658 The following switches control the general @command{gnatcheck} behavior
20659
20660 @table @option
20661 @c !sort!
20662 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20663 @item ^-a^/ALL^
20664 Process all units including those with read-only ALI files such as
20665 those from GNAT Run-Time library.
20666
20667 @ifclear vms
20668 @ignore
20669 @cindex @option{-d} (@command{gnatcheck})
20670 @item -d
20671 Debug mode
20672 @end ignore
20673
20674 @cindex @option{-dd} (@command{gnatcheck})
20675 @item -dd
20676 Progress indicator mode (for use in GPS)
20677 @end ifclear
20678
20679 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20680 @item ^-h^/HELP^
20681 List the predefined and user-defined rules. For more details see
20682 @ref{Predefined Rules}.
20683
20684 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20685 @item ^-l^/LOCS^
20686 Use full source locations references in the report file. For a construct from
20687 a generic instantiation a full source location is a chain from the location
20688 of this construct in the generic unit to the place where this unit is
20689 instantiated.
20690
20691 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
20692 @item ^-log^/LOG^
20693 Duplicate all the output sent to Stderr into a log file. The log file is
20694 named @var{gnatcheck.log} and is located in the current directory.
20695
20696 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20697 @item ^-m@i{nnn}^/DIAGNOSTIC_LIMIT=@i{nnn}^
20698 Maximum number of diagnoses to be sent to Stdout, @i{nnn} from o@dots{}1000,
20699 the default value is 500. Zero means that there is no limitation on
20700 the number of diagnostic messages to be printed into Stdout.
20701
20702 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20703 @item ^-q^/QUIET^
20704 Quiet mode. All the diagnoses about rule violations are placed in the
20705 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
20706
20707 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20708 @item ^-s^/SHORT^
20709 Short format of the report file (no version information, no list of applied
20710 rules, no list of checked sources is included)
20711
20712 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
20713 @item ^-s1^/COMPILER_STYLE^
20714 Include the compiler-style section in the report file
20715
20716 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
20717 @item ^-s2^/BY_RULES^
20718 Include the section containing diagnoses ordered by rules in the report file
20719
20720 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
20721 @item ^-s3^/BY_FILES_BY_RULES^
20722 Include the section containing diagnoses ordered by files and then by rules
20723 in the report file
20724
20725 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
20726 @item ^-t^/TIME^
20727 Print out execution time.
20728
20729 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20730 @item ^-v^/VERBOSE^
20731 Verbose mode; @command{gnatcheck} generates version information and then
20732 a trace of sources being processed.
20733
20734 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
20735 @item ^-o ^/OUTPUT=^@var{report_file}
20736 Set name of report file file to @var{report_file} .
20737
20738 @end table
20739
20740 @noindent
20741 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20742 @option{^-s2^/BY_RULES^} or
20743 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20744 then the  @command{gnatcheck} report file will only contain sections
20745 explicitly denoted by these options.
20746
20747 @node gnatcheck Rule Options
20748 @section @command{gnatcheck} Rule Options
20749
20750 @noindent
20751 The following options control the processing performed by
20752 @command{gnatcheck}.
20753
20754 @table @option
20755 @cindex @option{+ALL} (@command{gnatcheck})
20756 @item +ALL
20757 Turn all the rule checks ON.
20758
20759 @cindex @option{-ALL} (@command{gnatcheck})
20760 @item -ALL
20761 Turn all the rule checks OFF.
20762
20763 @cindex @option{+R} (@command{gnatcheck})
20764 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20765 Turn on the check for a specified rule with the specified parameter, if any.
20766 @var{rule_id} must be the identifier of one of the currently implemented rules
20767 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20768 are not case-sensitive. The @var{param} item must
20769 be a string representing a valid parameter(s) for the specified rule.
20770 If it contains any space characters then this string must be enclosed in
20771 quotation marks.
20772
20773 @cindex @option{-R} (@command{gnatcheck})
20774 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20775 Turn off the check for a specified rule with the specified parameter, if any.
20776
20777 @cindex @option{-from} (@command{gnatcheck})
20778 @item -from=@var{rule_option_filename}
20779 Read the rule options from the text file @var{rule_option_filename}, referred as
20780 ``rule file'' below.
20781
20782 @end table
20783
20784 @noindent
20785 The default behavior is that all the rule checks are disabled.
20786
20787 A rule file is a text file containing a set of rule options.
20788 @cindex Rule file (for @code{gnatcheck})
20789 The file may contain empty lines and Ada-style comments (comment
20790 lines and end-of-line comments). The rule file has free format; that is,
20791 you do not have to start a new rule option on a new line.
20792
20793 A rule file may contain other @option{-from=@var{rule_option_filename}}
20794 options, each such option being replaced with the content of the
20795 corresponding rule file during the rule files processing. In case a
20796 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20797 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20798 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20799 the processing of rule files is interrupted and a part of their content
20800 is ignored.
20801
20802
20803 @node Adding the Results of Compiler Checks to gnatcheck Output
20804 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20805
20806 @noindent
20807 The @command{gnatcheck} tool can include in the generated diagnostic messages
20808 and in
20809 the report file the results of the checks performed by the compiler. Though
20810 disabled by default, this effect may be obtained by using @option{+R} with
20811 the following rule identifiers and parameters:
20812
20813 @table @option
20814 @item Restrictions
20815 To record restrictions violations (that are performed by the compiler if the
20816 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20817 use the rule named
20818 @code{Restrictions} with the same parameters as pragma
20819 @code{Restrictions} or @code{Restriction_Warnings}.
20820
20821 @item Style_Checks
20822 To record compiler style checks(@pxref{Style Checking}), use the rule named
20823 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
20824 which enables all the standard style checks that corresponds to @option{-gnatyy}
20825 GNAT style check option, or a string that has exactly the same
20826 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
20827 @code{Style_Checks} (for further information about this pragma,
20828 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}). For example,
20829 @code{+RStyle_Checks:O} rule option activates and adds to @command{gnatcheck}
20830 output the compiler style check that corresponds to
20831 @code{-gnatyO} style check option.
20832
20833 @item Warnings
20834 To record compiler warnings (@pxref{Warning Message Control}), use the rule
20835 named @code{Warnings} with a parameter that is a valid
20836 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
20837 (for further information about this pragma, @pxref{Pragma Warnings,,,
20838 gnat_rm, GNAT Reference Manual}). Note, that in case of gnatcheck
20839 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20840 all the specific warnings, but not suppresses the warning mode,
20841 and 'e' parameter, corresponding to @option{-gnatwe} that means
20842 "treat warnings as errors", does not have any effect.
20843
20844 @end table
20845
20846 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20847 option with the corresponding restriction name as a parameter. @code{-R} is
20848 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20849 warnings and style checks, use the corresponding warning and style options.
20850
20851 @node Project-Wide Checks
20852 @section Project-Wide Checks
20853 @cindex Project-wide checks (for @command{gnatcheck})
20854
20855 @noindent
20856 In order to perform checks on all units of a given project, you can use
20857 the GNAT driver along with the @option{-P} option:
20858 @smallexample
20859    gnat check -Pproj -rules -from=my_rules
20860 @end smallexample
20861
20862 @noindent
20863 If the project @code{proj} depends upon other projects, you can perform
20864 checks on the project closure using the @option{-U} option:
20865 @smallexample
20866    gnat check -Pproj -U -rules -from=my_rules
20867 @end smallexample
20868
20869 @noindent
20870 Finally, if not all the units are relevant to a particular main
20871 program in the project closure, you can perform checks for the set
20872 of units needed to create a given main program (unit closure) using
20873 the @option{-U} option followed by the name of the main unit:
20874 @smallexample
20875    gnat check -Pproj -U main -rules -from=my_rules
20876 @end smallexample
20877
20878
20879 @node Predefined Rules
20880 @section Predefined Rules
20881 @cindex Predefined rules (for @command{gnatcheck})
20882
20883 @ignore
20884 @c (Jan 2007) Since the global rules are still under development and are not
20885 @c documented, there is no point in explaining the difference between
20886 @c global and local rules
20887 @noindent
20888 A rule in @command{gnatcheck} is either local or global.
20889 A @emph{local rule} is a rule that applies to a well-defined section
20890 of a program and that can be checked by analyzing only this section.
20891 A @emph{global rule} requires analysis of some global properties of the
20892 whole program (mostly related to the program call graph).
20893 As of @value{NOW}, the implementation of global rules should be
20894 considered to be at a preliminary stage. You can use the
20895 @option{+GLOBAL} option to enable all the global rules, and the
20896 @option{-GLOBAL} rule option to disable all the global rules.
20897
20898 All the global rules in the list below are
20899 so indicated by marking them ``GLOBAL''.
20900 This +GLOBAL and -GLOBAL options are not
20901 included in the list of gnatcheck options above, because at the moment they
20902 are considered as a temporary debug options.
20903
20904 @command{gnatcheck} performs rule checks for generic
20905 instances only for global rules.  This limitation may be relaxed in a later
20906 release.
20907 @end ignore
20908
20909 @noindent
20910 The following subsections document the rules implemented in
20911 @command{gnatcheck}.
20912 The subsection title is the same as the rule identifier, which may be
20913 used as a parameter of the @option{+R} or @option{-R} options.
20914
20915
20916 @menu
20917 * Abstract_Type_Declarations::
20918 * Anonymous_Arrays::
20919 * Anonymous_Subtypes::
20920 * Blocks::
20921 * Boolean_Relational_Operators::
20922 @ignore
20923 * Ceiling_Violations::
20924 @end ignore
20925 * Controlled_Type_Declarations::
20926 * Declarations_In_Blocks::
20927 * Default_Parameters::
20928 * Discriminated_Records::
20929 * Enumeration_Ranges_In_CASE_Statements::
20930 * Exceptions_As_Control_Flow::
20931 * Exits_From_Conditional_Loops::
20932 * EXIT_Statements_With_No_Loop_Name::
20933 * Expanded_Loop_Exit_Names::
20934 * Explicit_Full_Discrete_Ranges::
20935 * Float_Equality_Checks::
20936 * Forbidden_Pragmas::
20937 * Function_Style_Procedures::
20938 * Generics_In_Subprograms::
20939 * GOTO_Statements::
20940 * Implicit_IN_Mode_Parameters::
20941 * Implicit_SMALL_For_Fixed_Point_Types::
20942 * Improperly_Located_Instantiations::
20943 * Improper_Returns::
20944 * Library_Level_Subprograms::
20945 * Local_Packages::
20946 @ignore
20947 * Improperly_Called_Protected_Entries::
20948 @end ignore
20949 * Metrics::
20950 * Misnamed_Identifiers::
20951 * Multiple_Entries_In_Protected_Definitions::
20952 * Name_Clashes::
20953 * Non_Qualified_Aggregates::
20954 * Non_Short_Circuit_Operators::
20955 * Non_SPARK_Attributes::
20956 * Non_Tagged_Derived_Types::
20957 * Non_Visible_Exceptions::
20958 * Numeric_Literals::
20959 * OTHERS_In_Aggregates::
20960 * OTHERS_In_CASE_Statements::
20961 * OTHERS_In_Exception_Handlers::
20962 * Outer_Loop_Exits::
20963 * Overloaded_Operators::
20964 * Overly_Nested_Control_Structures::
20965 * Parameters_Out_Of_Order::
20966 * Positional_Actuals_For_Defaulted_Generic_Parameters::
20967 * Positional_Actuals_For_Defaulted_Parameters::
20968 * Positional_Components::
20969 * Positional_Generic_Parameters::
20970 * Positional_Parameters::
20971 * Predefined_Numeric_Types::
20972 * Raising_External_Exceptions::
20973 * Raising_Predefined_Exceptions::
20974 * Separate_Numeric_Error_Handlers::
20975 @ignore
20976 * Recursion::
20977 * Side_Effect_Functions::
20978 @end ignore
20979 * Slices::
20980 * Unassigned_OUT_Parameters::
20981 * Uncommented_BEGIN_In_Package_Bodies::
20982 * Unconditional_Exits::
20983 * Unconstrained_Array_Returns::
20984 * Universal_Ranges::
20985 * Unnamed_Blocks_And_Loops::
20986 @ignore
20987 * Unused_Subprograms::
20988 @end ignore
20989 * USE_PACKAGE_Clauses::
20990 * Volatile_Objects_Without_Address_Clauses::
20991 @end menu
20992
20993
20994 @node Abstract_Type_Declarations
20995 @subsection @code{Abstract_Type_Declarations}
20996 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
20997
20998 @noindent
20999 Flag all declarations of abstract types. For an abstract private
21000 type, both the private and full type declarations are flagged.
21001
21002 This rule has no parameters.
21003
21004
21005 @node Anonymous_Arrays
21006 @subsection @code{Anonymous_Arrays}
21007 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
21008
21009 @noindent
21010 Flag all anonymous array type definitions (by Ada semantics these can only
21011 occur in object declarations).
21012
21013 This rule has no parameters.
21014
21015 @node Anonymous_Subtypes
21016 @subsection @code{Anonymous_Subtypes}
21017 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
21018
21019 @noindent
21020 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
21021 any instance of a subtype indication with a constraint, other than one
21022 that occurs immediately within a subtype declaration. Any use of a range
21023 other than as a constraint used immediately within a subtype declaration
21024 is considered as an anonymous subtype.
21025
21026 An effect of this rule is that @code{for} loops such as the following are
21027 flagged (since @code{1..N} is formally a ``range''):
21028
21029 @smallexample @c ada
21030 for I in 1 .. N loop
21031    @dots{}
21032 end loop;
21033 @end smallexample
21034
21035 @noindent
21036 Declaring an explicit subtype solves the problem:
21037
21038 @smallexample @c ada
21039 subtype S is Integer range 1..N;
21040 @dots{}
21041 for I in S loop
21042    @dots{}
21043 end loop;
21044 @end smallexample
21045
21046 @noindent
21047 This rule has no parameters.
21048
21049 @node Blocks
21050 @subsection @code{Blocks}
21051 @cindex @code{Blocks} rule (for @command{gnatcheck})
21052
21053 @noindent
21054 Flag each block statement.
21055
21056 This rule has no parameters.
21057
21058 @node Boolean_Relational_Operators
21059 @subsection @code{Boolean_Relational_Operators}
21060 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
21061
21062 @noindent
21063 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
21064 ``>='', ``='' and ``/='') for the predefined Boolean type.
21065 (This rule is useful in enforcing the SPARK language restrictions.)
21066
21067 Calls to predefined relational operators of any type derived from
21068 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
21069 with these designators, and uses of operators that are renamings
21070 of the predefined relational operators for @code{Standard.Boolean},
21071 are likewise not detected.
21072
21073 This rule has no parameters.
21074
21075 @ignore
21076 @node Ceiling_Violations
21077 @subsection @code{Ceiling_Violations} (under construction, GLOBAL)
21078 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
21079
21080 @noindent
21081 Flag invocations of a protected operation by a task whose priority exceeds
21082 the protected object's ceiling.
21083
21084 As of @value{NOW}, this rule has the following limitations:
21085
21086 @itemize @bullet
21087
21088 @item
21089  We consider only pragmas Priority and Interrupt_Priority as means to define
21090   a task/protected operation priority. We do not consider the effect of using
21091   Ada.Dynamic_Priorities.Set_Priority procedure;
21092
21093 @item
21094  We consider only base task priorities, and no priority inheritance. That is,
21095   we do not make a difference between calls issued during task activation and
21096   execution of the sequence of statements from task body;
21097
21098 @item
21099  Any situation when the priority of protected operation caller is set by a
21100   dynamic expression (that is, the corresponding Priority or
21101   Interrupt_Priority pragma has a non-static expression as an argument) we
21102   treat as a priority inconsistency (and, therefore, detect this situation).
21103 @end itemize
21104
21105 @noindent
21106 At the moment the notion of the main subprogram is not implemented in
21107 gnatcheck, so any pragma Priority in a library level subprogram body (in case
21108 if this subprogram can be a main subprogram of a partition) changes the
21109 priority of an environment task. So if we have more then one such pragma in
21110 the set of processed sources, the pragma that is processed last, defines the
21111 priority of an environment task.
21112
21113 This rule has no parameters.
21114 @end ignore
21115
21116 @node Controlled_Type_Declarations
21117 @subsection @code{Controlled_Type_Declarations}
21118 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
21119
21120 @noindent
21121 Flag all declarations of controlled types. A declaration of a private type
21122 is flagged if its full declaration declares a controlled type. A declaration
21123 of a derived type is flagged if its ancestor type is controlled. Subtype
21124 declarations are not checked. A declaration of a type that itself is not a
21125 descendant of a type declared in @code{Ada.Finalization} but has a controlled
21126 component is not checked.
21127
21128 This rule has no parameters.
21129
21130
21131
21132 @node Declarations_In_Blocks
21133 @subsection @code{Declarations_In_Blocks}
21134 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
21135
21136 @noindent
21137 Flag all block statements containing local declarations. A @code{declare}
21138 block with an empty @i{declarative_part} or with a @i{declarative part}
21139 containing only pragmas and/or @code{use} clauses is not flagged.
21140
21141 This rule has no parameters.
21142
21143
21144 @node Default_Parameters
21145 @subsection @code{Default_Parameters}
21146 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
21147
21148 @noindent
21149 Flag all default expressions for subprogram parameters. Parameter
21150 declarations of formal and generic subprograms are also checked.
21151
21152 This rule has no parameters.
21153
21154
21155 @node Discriminated_Records
21156 @subsection @code{Discriminated_Records}
21157 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
21158
21159 @noindent
21160 Flag all declarations of record types with discriminants. Only the
21161 declarations of record and record extension types are checked. Incomplete,
21162 formal, private, derived and private extension type declarations are not
21163 checked. Task and protected type declarations also are not checked.
21164
21165 This rule has no parameters.
21166
21167
21168 @node Enumeration_Ranges_In_CASE_Statements
21169 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
21170 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
21171
21172 @noindent
21173 Flag each use of a range of enumeration literals as a choice in a
21174 @code{case} statement.
21175 All forms for specifying a range (explicit ranges
21176 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
21177 An enumeration range is
21178 flagged even if contains exactly one enumeration value or no values at all. A
21179 type derived from an enumeration type is considered as an enumeration type.
21180
21181 This rule helps prevent maintenance problems arising from adding an
21182 enumeration value to a type and having it implicitly handled by an existing
21183 @code{case} statement with an enumeration range that includes the new literal.
21184
21185 This rule has no parameters.
21186
21187
21188 @node Exceptions_As_Control_Flow
21189 @subsection @code{Exceptions_As_Control_Flow}
21190 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
21191
21192 @noindent
21193 Flag each place where an exception is explicitly raised and handled in the
21194 same subprogram body. A @code{raise} statement in an exception handler,
21195 package body, task body or entry body is not flagged.
21196
21197 The rule has no parameters.
21198
21199 @node Exits_From_Conditional_Loops
21200 @subsection @code{Exits_From_Conditional_Loops}
21201 @cindex @code{Exits_From_Conditional_Loops} (for @command{gnatcheck})
21202
21203 @noindent
21204 Flag any exit statement if it transfers the control out of a @code{for} loop
21205 or a @code{while} loop. This includes cases when the @code{exit} statement
21206 applies to a @code{FOR} or @code{while} loop, and cases when it is enclosed
21207 in some @code{for} or @code{while} loop, but transfers the control from some
21208 outer (inconditional) @code{loop} statement.
21209
21210 The rule has no parameters.
21211
21212
21213 @node EXIT_Statements_With_No_Loop_Name
21214 @subsection @code{EXIT_Statements_With_No_Loop_Name}
21215 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
21216
21217 @noindent
21218 Flag each @code{exit} statement that does not specify the name of the loop
21219 being exited.
21220
21221 The rule has no parameters.
21222
21223
21224 @node Expanded_Loop_Exit_Names
21225 @subsection @code{Expanded_Loop_Exit_Names}
21226 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
21227
21228 @noindent
21229 Flag all expanded loop names in @code{exit} statements.
21230
21231 This rule has no parameters.
21232
21233 @node Explicit_Full_Discrete_Ranges
21234 @subsection @code{Explicit_Full_Discrete_Ranges}
21235 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
21236
21237 @noindent
21238 Flag each discrete range that has the form @code{A'First .. A'Last}.
21239
21240 This rule has no parameters.
21241
21242 @node Float_Equality_Checks
21243 @subsection @code{Float_Equality_Checks}
21244 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
21245
21246 @noindent
21247 Flag all calls to the predefined equality operations for floating-point types.
21248 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
21249 User-defined equality operations are not flagged, nor are ``@code{=}''
21250 and ``@code{/=}'' operations for fixed-point types.
21251
21252 This rule has no parameters.
21253
21254
21255 @node Forbidden_Pragmas
21256 @subsection @code{Forbidden_Pragmas}
21257 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
21258
21259 @noindent
21260 Flag each use of the specified pragmas.  The pragmas to be detected
21261 are named in the rule's  parameters.
21262
21263 This rule has the following parameters:
21264
21265 @itemize @bullet
21266 @item For the @option{+R} option
21267
21268 @table @asis
21269 @item @emph{Pragma_Name}
21270 Adds the specified pragma to the set of pragmas to be
21271 checked and sets the checks for all the specified pragmas
21272 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
21273 does not correspond to any pragma name defined in the Ada
21274 standard or to the name of a GNAT-specific pragma defined
21275 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21276 Manual}, it is treated as the name of unknown pragma.
21277
21278 @item @code{GNAT}
21279 All the GNAT-specific pragmas are detected; this sets
21280 the checks for all the specified pragmas ON.
21281
21282 @item @code{ALL}
21283 All pragmas are detected; this sets the rule ON.
21284 @end table
21285
21286 @item For the @option{-R} option
21287 @table @asis
21288 @item @emph{Pragma_Name}
21289 Removes the specified pragma from the set of pragmas to be
21290 checked without affecting checks for
21291 other pragmas. @emph{Pragma_Name} is treated as a name
21292 of a pragma. If it does not correspond to any pragma
21293 defined in the Ada standard or to any name defined in
21294 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21295 this option is treated as turning OFF detection of all unknown pragmas.
21296
21297 @item GNAT
21298 Turn OFF detection of all GNAT-specific pragmas
21299
21300 @item ALL
21301 Clear the list of the pragmas to be detected and
21302 turn the rule OFF.
21303 @end table
21304 @end itemize
21305
21306 @noindent
21307 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
21308 the syntax of an Ada identifier and therefore can not be considered
21309 as a pragma name, a diagnostic message is generated and the corresponding
21310 parameter is ignored.
21311
21312 When more then one parameter is given in the same rule option, the parameters
21313 must be separated by a comma.
21314
21315 If more then one option for this rule is specified for the @command{gnatcheck}
21316 call, a new option overrides the previous one(s).
21317
21318 The @option{+R} option with no parameters turns the rule ON with the set of
21319 pragmas to be detected defined by the previous rule options.
21320 (By default this set is empty, so if the only option specified for the rule is
21321 @option{+RForbidden_Pragmas} (with
21322 no parameter), then the rule is enabled, but it does not detect anything).
21323 The @option{-R} option with no parameter turns the rule OFF, but it does not
21324 affect the set of pragmas to be detected.
21325
21326
21327
21328
21329 @node Function_Style_Procedures
21330 @subsection @code{Function_Style_Procedures}
21331 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
21332
21333 @noindent
21334 Flag each procedure that can be rewritten as a function. A procedure can be
21335 converted into a function if it has exactly one parameter of mode @code{out}
21336 and no parameters of mode @code{in out}. Procedure declarations,
21337 formal procedure declarations, and generic procedure declarations are always
21338 checked. Procedure
21339 bodies and body stubs are flagged only if they do not have corresponding
21340 separate declarations. Procedure renamings and procedure instantiations are
21341 not flagged.
21342
21343 If a procedure can be rewritten as a function, but its @code{out} parameter is
21344 of a limited type, it is not flagged.
21345
21346 Protected procedures are not flagged. Null procedures also are not flagged.
21347
21348 This rule has no parameters.
21349
21350
21351 @node Generics_In_Subprograms
21352 @subsection @code{Generics_In_Subprograms}
21353 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21354
21355 @noindent
21356 Flag each declaration of a generic unit in a subprogram. Generic
21357 declarations in the bodies of generic subprograms are also flagged.
21358 A generic unit nested in another generic unit is not flagged.
21359 If a generic unit is
21360 declared in a local package that is declared in a subprogram body, the
21361 generic unit is flagged.
21362
21363 This rule has no parameters.
21364
21365
21366 @node GOTO_Statements
21367 @subsection @code{GOTO_Statements}
21368 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21369
21370 @noindent
21371 Flag each occurrence of a @code{goto} statement.
21372
21373 This rule has no parameters.
21374
21375
21376 @node Implicit_IN_Mode_Parameters
21377 @subsection @code{Implicit_IN_Mode_Parameters}
21378 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21379
21380 @noindent
21381 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21382 Note that @code{access} parameters, although they technically behave
21383 like @code{in} parameters, are not flagged.
21384
21385 This rule has no parameters.
21386
21387
21388 @node Implicit_SMALL_For_Fixed_Point_Types
21389 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21390 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21391
21392 @noindent
21393 Flag each fixed point type declaration that lacks an explicit
21394 representation  clause to define its @code{'Small} value.
21395 Since @code{'Small} can be  defined only for ordinary fixed point types,
21396 decimal fixed point type declarations are not checked.
21397
21398 This rule has no parameters.
21399
21400
21401 @node Improperly_Located_Instantiations
21402 @subsection @code{Improperly_Located_Instantiations}
21403 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21404
21405 @noindent
21406 Flag all generic instantiations in library-level package specs
21407 (including library generic packages) and in all subprogram bodies.
21408
21409 Instantiations in task and entry bodies are not flagged. Instantiations in the
21410 bodies of protected subprograms are flagged.
21411
21412 This rule has no parameters.
21413
21414
21415
21416 @node Improper_Returns
21417 @subsection @code{Improper_Returns}
21418 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21419
21420 @noindent
21421 Flag each explicit @code{return} statement in procedures, and
21422 multiple @code{return} statements in functions.
21423 Diagnostic messages are generated for all @code{return} statements
21424 in a procedure (thus each procedure must be written so that it
21425 returns implicitly at the end of its statement part),
21426 and for all @code{return} statements in a function after the first one.
21427 This rule supports the stylistic convention that each subprogram
21428 should have no more than one point of normal return.
21429
21430 This rule has no parameters.
21431
21432
21433 @node Library_Level_Subprograms
21434 @subsection @code{Library_Level_Subprograms}
21435 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21436
21437 @noindent
21438 Flag all library-level subprograms (including generic subprogram instantiations).
21439
21440 This rule has no parameters.
21441
21442
21443 @node Local_Packages
21444 @subsection @code{Local_Packages}
21445 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21446
21447 @noindent
21448 Flag all local packages declared in package and generic package
21449 specs.
21450 Local packages in bodies are not flagged.
21451
21452 This rule has no parameters.
21453
21454 @ignore
21455 @node Improperly_Called_Protected_Entries
21456 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21457 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21458
21459 @noindent
21460 Flag each protected entry that can be called from more than one task.
21461
21462 This rule has no parameters.
21463 @end ignore
21464
21465 @node Metrics
21466 @subsection @code{Metrics}
21467 @cindex @code{Metrics} rule (for @command{gnatcheck})
21468
21469 @noindent
21470 There is a set of checks based on computing a metric value and comparing the
21471 result with the specified upper (or lower, depending on a specific metric)
21472 value specified for a given metric. A construct is flagged if a given metric
21473 is applicable (can be computed) for it and the computed value is greater
21474 then (lover then) the specified upper (lower) bound.
21475
21476 The name of any metric-based rule consists of the prefix @code{Metrics_}
21477 followed by the name of the corresponding metric (see the table below).
21478 For @option{+R} option, each metric-based rule has a numeric parameter
21479 specifying the bound (integer or real, depending on a metric), @option{-R}
21480 option for metric rules does not have a parameter.
21481
21482 The following table shows the metric names for that the corresponding
21483 metrics-based checks are supported by gnatcheck, including the
21484 constraint that must be satisfied by the bound that is specified for the check
21485 and what bound - upper (U) or lower (L) - should be specified.
21486
21487 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21488 @ifnothtml
21489 @headitem Check Name @tab Description @tab Bounds Value
21490 @end ifnothtml
21491 @ifhtml
21492 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21493 @end ifhtml
21494 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21495 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21496 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21497 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21498 @end multitable
21499
21500 @noindent
21501 The meaning and the computed values for all these metrics are exactly
21502 the same as for the corresponding metrics in @command{gnatmetric}.
21503
21504 @emph{Example:} the rule
21505 @smallexample
21506 +RMetrics_Cyclomatic_Complexity : 7
21507 @end smallexample
21508 @noindent
21509 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21510
21511 To turn OFF the check for cyclomatic complexity metric, use the following option:
21512 @smallexample
21513 -RMetrics_Cyclomatic_Complexity
21514 @end smallexample
21515
21516 @node Misnamed_Identifiers
21517 @subsection @code{Misnamed_Identifiers}
21518 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21519
21520 @noindent
21521 Flag the declaration of each identifier that does not have a suffix
21522 corresponding to the kind of entity being declared.
21523 The following declarations are checked:
21524
21525 @itemize @bullet
21526 @item
21527 type declarations
21528
21529 @item
21530 subtype declarations
21531
21532 @item
21533 constant declarations (but not number declarations)
21534
21535 @item
21536 package renaming declarations (but not generic package renaming
21537 declarations)
21538 @end itemize
21539
21540 @noindent
21541 This rule may have parameters. When used without parameters, the rule enforces
21542 the following checks:
21543
21544 @itemize @bullet
21545 @item
21546 type-defining names end with @code{_T}, unless the type is an access type,
21547 in which case the suffix must be @code{_A}
21548 @item
21549 constant names end with @code{_C}
21550 @item
21551 names defining package renamings end with @code{_R}
21552 @end itemize
21553
21554 @noindent
21555 For a private or incomplete type declaration the following checks are
21556 made for the defining name suffix:
21557
21558 @itemize @bullet
21559 @item
21560 For an incomplete type declaration: if the corresponding full type
21561 declaration is available, the defining identifier from the full type
21562 declaration is checked, but the defining identifier from the incomplete type
21563 declaration is not; otherwise the defining identifier from the incomplete
21564 type declaration is checked against the suffix specified for type
21565 declarations.
21566
21567 @item
21568 For a private type declaration (including private extensions),  the defining
21569 identifier from the private type declaration is checked against the type
21570 suffix (even if the corresponding full declaration is an access type
21571 declaration), and the defining identifier from the corresponding full type
21572 declaration is not checked.
21573 @end itemize
21574
21575 @noindent
21576 For a deferred constant, the defining name in the corresponding full constant
21577 declaration is not checked.
21578
21579 Defining names of formal types are not checked.
21580
21581 The rule may have the following parameters:
21582
21583 @itemize @bullet
21584 @item
21585 For the @option{+R} option:
21586 @table @code
21587 @item Default
21588 Sets the default listed above for all the names to be checked.
21589
21590 @item Type_Suffix=@emph{string}
21591 Specifies the suffix for a type name.
21592
21593 @item Access_Suffix=@emph{string}
21594 Specifies the suffix for an access type name. If
21595 this parameter is set, it overrides for access
21596 types the suffix set by the @code{Type_Suffix} parameter.
21597 For access types, @emph{string} may have the following format:
21598 @emph{suffix1(suffix2)}. That means that an access type name
21599 should have the @emph{suffix1} suffix except for the case when
21600 the designated type is also an access type, in this case the
21601 type name should have the @emph{suffix1 & suffix2} suffix.
21602
21603 @item Class_Access_Suffix=@emph{string}
21604 Specifies the suffix for the name of an access type that points to some class-wide
21605 type. If this parameter is set, it overrides for such access
21606 types the suffix set by the @code{Type_Suffix} or @code{Access_Suffix}
21607 parameter.
21608
21609 @item Class_Subtype_Suffix=@emph{string}
21610 Specifies the suffix for the name of a subtype that denotes a class-wide type.
21611
21612 @item Constant_Suffix=@emph{string}
21613 Specifies the suffix for a constant name.
21614
21615 @item Renaming_Suffix=@emph{string}
21616 Specifies the suffix for a package renaming name.
21617 @end table
21618
21619 @item
21620 For the @option{-R} option:
21621 @table @code
21622 @item All_Suffixes
21623 Remove all the suffixes specified for the
21624 identifier suffix checks, whether by default or
21625 as specified by other rule parameters. All the
21626 checks for this rule are disabled as a result.
21627
21628 @item Type_Suffix
21629 Removes the suffix specified for types. This
21630 disables checks for types but does not disable
21631 any other checks for this rule (including the
21632 check for access type names if @code{Access_Suffix} is
21633 set).
21634
21635 @item Access_Suffix
21636 Removes the suffix specified for access types.
21637 This disables checks for access type names but
21638 does not disable any other checks for this rule.
21639 If @code{Type_Suffix} is set, access type names are
21640 checked as ordinary type names.
21641
21642 @item Class_Access_Suffix
21643 Removes the suffix specified for access types pointing to class-wide
21644 type. This disables specific checks for names of access types pointing to
21645 class-wide types but does not disable any other checks for this rule.
21646 If @code{Type_Suffix} is set, access type names are
21647 checked as ordinary type names. If @code{Access_Suffix} is set, these
21648 access types are checked as any other access type name.
21649
21650 @item Class_Subtype_Suffix=@emph{string}
21651 Removes the suffix specified for subtype names.
21652 This disables checks for subtype names but
21653 does not disable any other checks for this rule.
21654
21655 @item Constant_Suffix
21656 Removes the suffix specified for constants. This
21657 disables checks for constant names but does not
21658 disable any other checks for this rule.
21659
21660 @item Renaming_Suffix
21661 Removes the suffix specified for package
21662 renamings. This disables checks for package
21663 renamings but does not disable any other checks
21664 for this rule.
21665 @end table
21666 @end itemize
21667
21668 @noindent
21669 If more than one parameter is used, parameters must be separated by commas.
21670
21671 If more than one  option is specified for the @command{gnatcheck} invocation,
21672 a new option overrides the previous one(s).
21673
21674 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
21675 checks for all the
21676 name suffixes specified by previous options used for this rule.
21677
21678 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
21679 all the checks but keeps
21680 all the suffixes specified by previous options used for this rule.
21681
21682 The @emph{string} value must be a valid suffix for an Ada identifier (after
21683 trimming all the leading and trailing space characters, if any).
21684 Parameters are not case sensitive, except the @emph{string} part.
21685
21686 If any error is detected in a rule parameter, the parameter is ignored.
21687 In such a case the options that are set for the rule are not
21688 specified.
21689
21690
21691
21692 @node Multiple_Entries_In_Protected_Definitions
21693 @subsection @code{Multiple_Entries_In_Protected_Definitions}
21694 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
21695
21696 @noindent
21697 Flag each protected definition (i.e., each protected object/type declaration)
21698 that defines more than one entry.
21699 Diagnostic messages are generated for all the entry declarations
21700 except the first one. An entry family is counted as one entry. Entries from
21701 the private part of the protected definition are also checked.
21702
21703 This rule has no parameters.
21704
21705 @node Name_Clashes
21706 @subsection @code{Name_Clashes}
21707 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
21708
21709 @noindent
21710 Check that certain names are not used as defining identifiers. To activate
21711 this rule, you need to supply a reference to the dictionary file(s) as a rule
21712 parameter(s) (more then one dictionary file can be specified). If no
21713 dictionary file is set, this rule will not cause anything to be flagged.
21714 Only defining occurrences, not references, are checked.
21715 The check is not case-sensitive.
21716
21717 This rule is enabled by default, but without setting any corresponding
21718 dictionary file(s); thus the default effect is to do no checks.
21719
21720 A dictionary file is a plain text file. The maximum line length for this file
21721 is 1024 characters.  If the line is longer then this limit, extra characters
21722 are ignored.
21723
21724 Each line can be either an empty line, a comment line, or a line containing
21725 a list of identifiers separated by space or HT characters.
21726 A comment is an Ada-style comment (from @code{--} to end-of-line).
21727 Identifiers must follow the Ada syntax for identifiers.
21728 A line containing one or more identifiers may end with a comment.
21729
21730 @node Non_Qualified_Aggregates
21731 @subsection @code{Non_Qualified_Aggregates}
21732 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
21733
21734 @noindent
21735 Flag each non-qualified aggregate.
21736 A non-qualified aggregate is an
21737 aggregate that is not the expression of a qualified expression. A
21738 string literal is not considered an aggregate, but an array
21739 aggregate of a string type is considered as a normal aggregate.
21740 Aggregates of anonymous array types are not flagged.
21741
21742 This rule has no parameters.
21743
21744
21745 @node Non_Short_Circuit_Operators
21746 @subsection @code{Non_Short_Circuit_Operators}
21747 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
21748
21749 @noindent
21750 Flag all calls to predefined @code{and} and @code{or} operators for
21751 any boolean type. Calls to
21752 user-defined @code{and} and @code{or} and to operators defined by renaming
21753 declarations are not flagged. Calls to predefined @code{and} and @code{or}
21754 operators for modular types or boolean array types are not flagged.
21755
21756 This rule has no parameters.
21757
21758
21759
21760 @node Non_SPARK_Attributes
21761 @subsection @code{Non_SPARK_Attributes}
21762 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
21763
21764 @noindent
21765 The SPARK language defines the following subset of Ada 95 attribute
21766 designators as those that can be used in SPARK programs. The use of
21767 any other attribute is flagged.
21768
21769 @itemize @bullet
21770 @item @code{'Adjacent}
21771 @item @code{'Aft}
21772 @item @code{'Base}
21773 @item @code{'Ceiling}
21774 @item @code{'Component_Size}
21775 @item @code{'Compose}
21776 @item @code{'Copy_Sign}
21777 @item @code{'Delta}
21778 @item @code{'Denorm}
21779 @item @code{'Digits}
21780 @item @code{'Exponent}
21781 @item @code{'First}
21782 @item @code{'Floor}
21783 @item @code{'Fore}
21784 @item @code{'Fraction}
21785 @item @code{'Last}
21786 @item @code{'Leading_Part}
21787 @item @code{'Length}
21788 @item @code{'Machine}
21789 @item @code{'Machine_Emax}
21790 @item @code{'Machine_Emin}
21791 @item @code{'Machine_Mantissa}
21792 @item @code{'Machine_Overflows}
21793 @item @code{'Machine_Radix}
21794 @item @code{'Machine_Rounds}
21795 @item @code{'Max}
21796 @item @code{'Min}
21797 @item @code{'Model}
21798 @item @code{'Model_Emin}
21799 @item @code{'Model_Epsilon}
21800 @item @code{'Model_Mantissa}
21801 @item @code{'Model_Small}
21802 @item @code{'Modulus}
21803 @item @code{'Pos}
21804 @item @code{'Pred}
21805 @item @code{'Range}
21806 @item @code{'Remainder}
21807 @item @code{'Rounding}
21808 @item @code{'Safe_First}
21809 @item @code{'Safe_Last}
21810 @item @code{'Scaling}
21811 @item @code{'Signed_Zeros}
21812 @item @code{'Size}
21813 @item @code{'Small}
21814 @item @code{'Succ}
21815 @item @code{'Truncation}
21816 @item @code{'Unbiased_Rounding}
21817 @item @code{'Val}
21818 @item @code{'Valid}
21819 @end itemize
21820
21821 @noindent
21822 This rule has no parameters.
21823
21824
21825 @node Non_Tagged_Derived_Types
21826 @subsection @code{Non_Tagged_Derived_Types}
21827 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
21828
21829 @noindent
21830 Flag all derived type declarations that do not have a record extension part.
21831
21832 This rule has no parameters.
21833
21834
21835
21836 @node Non_Visible_Exceptions
21837 @subsection @code{Non_Visible_Exceptions}
21838 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
21839
21840 @noindent
21841 Flag constructs leading to the possibility of propagating an exception
21842 out of the scope in which the exception is declared.
21843 Two cases are detected:
21844
21845 @itemize @bullet
21846 @item
21847 An exception declaration in a subprogram body, task body or block
21848 statement is flagged if the body or statement does not contain a handler for
21849 that exception or a handler with an @code{others} choice.
21850
21851 @item
21852 A @code{raise} statement in an exception handler of a subprogram body,
21853 task body or block statement is flagged if it (re)raises a locally
21854 declared exception.  This may occur under the following circumstances:
21855 @itemize @minus
21856 @item
21857 it explicitly raises a locally declared exception, or
21858 @item
21859 it does not specify an exception name (i.e., it is simply @code{raise;})
21860 and the enclosing handler contains a locally declared exception in its
21861 exception choices.
21862 @end itemize
21863 @end itemize
21864
21865 @noindent
21866 Renamings of local exceptions are not flagged.
21867
21868 This rule has no parameters.
21869
21870
21871 @node Numeric_Literals
21872 @subsection @code{Numeric_Literals}
21873 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
21874
21875 @noindent
21876 Flag each use of a numeric literal in an index expression, and in any
21877 circumstance except for the following:
21878
21879 @itemize @bullet
21880 @item
21881 a literal occurring in the initialization expression for a constant
21882 declaration or a named number declaration, or
21883
21884 @item
21885 an integer literal that is less than or equal to a value
21886 specified by the @option{N} rule parameter.
21887 @end itemize
21888
21889 @noindent
21890 This rule may have the following parameters for the @option{+R} option:
21891
21892 @table @asis
21893 @item @emph{N}
21894 @emph{N} is an integer literal used as the maximal value that is not flagged
21895 (i.e., integer literals not exceeding this value are allowed)
21896
21897 @item @code{ALL}
21898 All integer literals are flagged
21899 @end table
21900
21901 @noindent
21902 If no parameters are set, the maximum unflagged value is 1.
21903
21904 The last specified check limit (or the fact that there is no limit at
21905 all) is used when multiple @option{+R} options appear.
21906
21907 The @option{-R} option for this rule has no parameters.
21908 It disables the rule but retains the last specified maximum unflagged value.
21909 If the @option{+R} option subsequently appears, this value is used as the
21910 threshold for the check.
21911
21912
21913 @node OTHERS_In_Aggregates
21914 @subsection @code{OTHERS_In_Aggregates}
21915 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
21916
21917 @noindent
21918 Flag each use of an @code{others} choice in extension aggregates.
21919 In record and array aggregates, an @code{others} choice is flagged unless
21920 it is used to refer to all components, or to all but one component.
21921
21922 If, in case of a named array aggregate, there are two associations, one
21923 with an @code{others} choice and another with a discrete range, the
21924 @code{others} choice is flagged even if the discrete range specifies
21925 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
21926
21927 This rule has no parameters.
21928
21929 @node OTHERS_In_CASE_Statements
21930 @subsection @code{OTHERS_In_CASE_Statements}
21931 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
21932
21933 @noindent
21934 Flag any use of an @code{others} choice in a @code{case} statement.
21935
21936 This rule has no parameters.
21937
21938 @node OTHERS_In_Exception_Handlers
21939 @subsection @code{OTHERS_In_Exception_Handlers}
21940 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
21941
21942 @noindent
21943 Flag any use of an @code{others} choice in an exception handler.
21944
21945 This rule has no parameters.
21946
21947
21948 @node Outer_Loop_Exits
21949 @subsection @code{Outer_Loop_Exits}
21950 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
21951
21952 @noindent
21953 Flag each @code{exit} statement containing a loop name that is not the name
21954 of the immediately enclosing @code{loop} statement.
21955
21956 This rule has no parameters.
21957
21958
21959 @node Overloaded_Operators
21960 @subsection @code{Overloaded_Operators}
21961 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
21962
21963 @noindent
21964 Flag each function declaration that overloads an operator symbol.
21965 A function body is checked only if the body does not have a
21966 separate spec. Formal functions are also checked. For a
21967 renaming declaration, only renaming-as-declaration is checked
21968
21969 This rule has no parameters.
21970
21971
21972 @node Overly_Nested_Control_Structures
21973 @subsection @code{Overly_Nested_Control_Structures}
21974 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
21975
21976 @noindent
21977 Flag each control structure whose nesting level exceeds the value provided
21978 in the rule parameter.
21979
21980 The control structures checked are the following:
21981
21982 @itemize @bullet
21983 @item    @code{if} statement
21984 @item    @code{case} statement
21985 @item    @code{loop} statement
21986 @item    Selective accept statement
21987 @item    Timed entry call statement
21988 @item    Conditional entry call
21989 @item    Asynchronous select statement
21990 @end itemize
21991
21992 @noindent
21993 The rule has the following parameter for the @option{+R} option:
21994
21995 @table @emph
21996 @item N
21997 Positive integer specifying the maximal control structure nesting
21998 level that is not flagged
21999 @end table
22000
22001 @noindent
22002 If the parameter for the @option{+R} option is not specified or
22003 if it is not a positive integer, @option{+R} option is ignored.
22004
22005 If more then one  option is specified for the gnatcheck call, the later option and
22006 new parameter override the previous one(s).
22007
22008
22009 @node Parameters_Out_Of_Order
22010 @subsection @code{Parameters_Out_Of_Order}
22011 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
22012
22013 @noindent
22014 Flag each subprogram and entry declaration whose formal parameters are not
22015 ordered according to the following scheme:
22016
22017 @itemize @bullet
22018
22019 @item @code{in} and @code{access} parameters first,
22020 then @code{in out} parameters,
22021 and then @code{out} parameters;
22022
22023 @item for @code{in} mode, parameters with default initialization expressions
22024 occur last
22025 @end itemize
22026
22027 @noindent
22028 Only the first violation of the described order is flagged.
22029
22030 The following constructs are checked:
22031
22032 @itemize @bullet
22033 @item   subprogram declarations (including null procedures);
22034 @item   generic subprogram declarations;
22035 @item   formal subprogram declarations;
22036 @item   entry declarations;
22037 @item   subprogram bodies and subprogram body stubs that do not
22038 have separate specifications
22039 @end itemize
22040
22041 @noindent
22042 Subprogram renamings are not checked.
22043
22044 This rule has no parameters.
22045
22046
22047 @node Positional_Actuals_For_Defaulted_Generic_Parameters
22048 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
22049 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
22050
22051 @noindent
22052 Flag each generic actual parameter corresponding to a generic formal
22053 parameter with a default initialization, if positional notation is used.
22054
22055 This rule has no parameters.
22056
22057 @node Positional_Actuals_For_Defaulted_Parameters
22058 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
22059 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
22060
22061 @noindent
22062 Flag each actual parameter to a subprogram or entry call where the
22063 corresponding formal parameter has a default expression, if positional
22064 notation is used.
22065
22066 This rule has no parameters.
22067
22068 @node Positional_Components
22069 @subsection @code{Positional_Components}
22070 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
22071
22072 @noindent
22073 Flag each array, record and extension aggregate that includes positional
22074 notation.
22075
22076 This rule has no parameters.
22077
22078
22079 @node Positional_Generic_Parameters
22080 @subsection @code{Positional_Generic_Parameters}
22081 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
22082
22083 @noindent
22084 Flag each instantiation using positional parameter notation.
22085
22086 This rule has no parameters.
22087
22088
22089 @node Positional_Parameters
22090 @subsection @code{Positional_Parameters}
22091 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
22092
22093 @noindent
22094 Flag each subprogram or entry call using positional parameter notation,
22095 except for the following:
22096
22097 @itemize @bullet
22098 @item
22099 Invocations of prefix or infix operators are not flagged
22100 @item
22101 If the called subprogram or entry has only one formal parameter,
22102 the call is not flagged;
22103 @item
22104 If a subprogram call uses the @emph{Object.Operation} notation, then
22105 @itemize @minus
22106 @item
22107 the first parameter (that is, @emph{Object}) is not flagged;
22108 @item
22109 if the called subprogram has only two parameters, the second parameter
22110 of the call is not flagged;
22111 @end itemize
22112 @end itemize
22113
22114 @noindent
22115 This rule has no parameters.
22116
22117
22118
22119
22120 @node Predefined_Numeric_Types
22121 @subsection @code{Predefined_Numeric_Types}
22122 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
22123
22124 @noindent
22125 Flag each explicit use of the name of any numeric type or subtype defined
22126 in package @code{Standard}.
22127
22128 The rationale for this rule is to detect when the
22129 program may depend on platform-specific characteristics of the implementation
22130 of the predefined numeric types. Note that this rule is over-pessimistic;
22131 for example, a program that uses @code{String} indexing
22132 likely needs a variable of type @code{Integer}.
22133 Another example is the flagging of predefined numeric types with explicit
22134 constraints:
22135
22136 @smallexample @c ada
22137     subtype My_Integer is Integer range Left .. Right;
22138     Vy_Var : My_Integer;
22139 @end smallexample
22140
22141 @noindent
22142 This rule detects only numeric types and subtypes defined in
22143 @code{Standard}. The use of numeric types and subtypes defined in other
22144 predefined packages (such as @code{System.Any_Priority} or
22145 @code{Ada.Text_IO.Count}) is not flagged
22146
22147 This rule has no parameters.
22148
22149
22150
22151 @node Raising_External_Exceptions
22152 @subsection @code{Raising_External_Exceptions}
22153 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
22154
22155 @noindent
22156 Flag any @code{raise} statement, in a program unit declared in a library
22157 package or in a generic library package, for an exception that is
22158 neither a predefined exception nor an exception that is also declared (or
22159 renamed) in the visible part of the package.
22160
22161 This rule has no parameters.
22162
22163
22164
22165 @node Raising_Predefined_Exceptions
22166 @subsection @code{Raising_Predefined_Exceptions}
22167 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
22168
22169 @noindent
22170 Flag each @code{raise} statement that raises a predefined exception
22171 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
22172 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
22173
22174 This rule has no parameters.
22175
22176 @node Separate_Numeric_Error_Handlers
22177 @subsection @code{Separate_Numeric_Error_Handlers}
22178 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
22179
22180 @noindent
22181 Flags each exception handler that contains a choice for
22182 the predefined @code{Constraint_Error} exception, but does not contain
22183 the choice for the predefined @code{Numeric_Error} exception, or
22184 that contains the choice for @code{Numeric_Error}, but does not contain the
22185 choice for @code{Constraint_Error}.
22186
22187 This rule has no parameters.
22188
22189 @ignore
22190 @node Recursion
22191 @subsection @code{Recursion} (under construction, GLOBAL)
22192 @cindex @code{Recursion} rule (for @command{gnatcheck})
22193
22194 @noindent
22195 Flag recursive subprograms (cycles in the call graph). Declarations, and not
22196 calls, of recursive subprograms are detected.
22197
22198 This rule has no parameters.
22199 @end ignore
22200
22201 @ignore
22202 @node Side_Effect_Functions
22203 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
22204 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
22205
22206 @noindent
22207 Flag functions with side effects.
22208
22209 We define a side effect as changing any data object that is not local for the
22210 body of this function.
22211
22212 At the moment, we do NOT consider a side effect any input-output operations
22213 (changing a state or a content of any file).
22214
22215 We do not consider protected functions for this rule (???)
22216
22217 There are the following sources of side effect:
22218
22219 @enumerate
22220 @item Explicit (or direct) side-effect:
22221
22222 @itemize @bullet
22223 @item
22224 direct assignment to a non-local variable;
22225
22226 @item
22227 direct call to an entity that is known to change some data object that is
22228      not local for the body of this function (Note, that if F1 calls F2 and F2
22229      does have a side effect, this does not automatically mean that F1 also
22230      have a side effect, because it may be the case that F2 is declared in
22231      F1's body and it changes some data object that is global for F2, but
22232      local for F1);
22233 @end itemize
22234
22235 @item Indirect side-effect:
22236 @itemize @bullet
22237 @item
22238 Subprogram calls implicitly issued by:
22239 @itemize @bullet
22240 @item
22241 computing initialization expressions from type declarations as a part
22242          of object elaboration or allocator evaluation;
22243 @item
22244 computing implicit parameters of subprogram or entry calls or generic
22245          instantiations;
22246 @end itemize
22247
22248 @item
22249 activation of a task that change some non-local data object (directly or
22250      indirectly);
22251
22252 @item
22253 elaboration code of a package that is a result of a package instantiation;
22254
22255 @item
22256 controlled objects;
22257 @end itemize
22258
22259 @item Situations when we can suspect a side-effect, but the full static check
22260 is either impossible or too hard:
22261 @itemize @bullet
22262 @item
22263 assignment to access variables or to the objects pointed by access
22264      variables;
22265
22266 @item
22267 call to a subprogram pointed by access-to-subprogram value
22268
22269 @item
22270 dispatching calls;
22271 @end itemize
22272 @end enumerate
22273
22274 @noindent
22275 This rule has no parameters.
22276 @end ignore
22277
22278 @node Slices
22279 @subsection @code{Slices}
22280 @cindex @code{Slices} rule (for @command{gnatcheck})
22281
22282 @noindent
22283 Flag all uses of array slicing
22284
22285 This rule has no parameters.
22286
22287
22288 @node Unassigned_OUT_Parameters
22289 @subsection @code{Unassigned_OUT_Parameters}
22290 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
22291
22292 @noindent
22293 Flags procedures' @code{out} parameters that are not assigned, and
22294 identifies the contexts in which the assignments are missing.
22295
22296 An @code{out} parameter is flagged in the statements in the procedure
22297 body's handled sequence of statements (before the procedure body's
22298 @code{exception} part, if any) if this sequence of statements contains
22299 no assignments to the parameter.
22300
22301 An @code{out} parameter is flagged in an exception handler in the exception
22302 part of the procedure body's handled sequence of statements if the handler
22303 contains no assignment to the parameter.
22304
22305 Bodies of generic procedures are also considered.
22306
22307 The following are treated as assignments to an @code{out} parameter:
22308
22309 @itemize @bullet
22310 @item
22311 an assignment statement, with the parameter or some component as the target;
22312
22313 @item
22314 passing the parameter (or one of its components) as an @code{out} or
22315 @code{in out} parameter.
22316 @end itemize
22317
22318 @noindent
22319 This rule does not have any parameters.
22320
22321
22322
22323 @node Uncommented_BEGIN_In_Package_Bodies
22324 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
22325 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
22326
22327 @noindent
22328 Flags each package body with declarations and a statement part that does not
22329 include a trailing comment on the line containing the @code{begin} keyword;
22330 this trailing comment needs to specify the package name and nothing else.
22331 The @code{begin} is not flagged if the package body does not
22332 contain any declarations.
22333
22334 If the @code{begin} keyword is placed on the
22335 same line as the last declaration or the first statement, it is flagged
22336 independently of whether the line contains a trailing comment. The
22337 diagnostic message is attached to the line containing the first statement.
22338
22339 This rule has no parameters.
22340
22341 @node Unconditional_Exits
22342 @subsection @code{Unconditional_Exits}
22343 @cindex @code{Unconditional_Exits} rule (for @command{gnatcheck})
22344
22345 @noindent
22346 Flag unconditional @code{exit} statements.
22347
22348 This rule has no parameters.
22349
22350 @node Unconstrained_Array_Returns
22351 @subsection @code{Unconstrained_Array_Returns}
22352 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
22353
22354 @noindent
22355 Flag each function returning an unconstrained array. Function declarations,
22356 function bodies (and body stubs) having no separate specifications,
22357 and generic function instantiations are checked.
22358 Generic function declarations, function calls and function renamings are
22359 not checked.
22360
22361 This rule has no parameters.
22362
22363 @node Universal_Ranges
22364 @subsection @code{Universal_Ranges}
22365 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
22366
22367 @noindent
22368 Flag discrete ranges that are a part of an index constraint, constrained
22369 array definition, or @code{for}-loop parameter specification, and whose bounds
22370 are both of type @i{universal_integer}. Ranges that have at least one
22371 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
22372 or an expression of non-universal type) are not flagged.
22373
22374 This rule has no parameters.
22375
22376
22377 @node Unnamed_Blocks_And_Loops
22378 @subsection @code{Unnamed_Blocks_And_Loops}
22379 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
22380
22381 @noindent
22382 Flag each unnamed block statement and loop statement.
22383
22384 The rule has no parameters.
22385
22386
22387
22388 @ignore
22389 @node Unused_Subprograms
22390 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22391 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22392
22393 @noindent
22394 Flag all unused subprograms.
22395
22396 This rule has no parameters.
22397 @end ignore
22398
22399
22400
22401
22402 @node USE_PACKAGE_Clauses
22403 @subsection @code{USE_PACKAGE_Clauses}
22404 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22405
22406 @noindent
22407 Flag all @code{use} clauses for packages; @code{use type} clauses are
22408 not flagged.
22409
22410 This rule has no parameters.
22411
22412
22413
22414 @node Volatile_Objects_Without_Address_Clauses
22415 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22416 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22417
22418 @noindent
22419 Flag each volatile object that does not have an address clause.
22420
22421 The following check is made: if the pragma @code{Volatile} is applied to a
22422 data object or to its type, then an address clause must
22423 be supplied for this object.
22424
22425 This rule does not check the components of data objects,
22426 array components that are volatile as a result of the pragma
22427 @code{Volatile_Components}, or objects that are volatile because
22428 they are atomic as a result of pragmas @code{Atomic} or
22429 @code{Atomic_Components}.
22430
22431 Only variable declarations, and not constant declarations, are checked.
22432
22433 This rule has no parameters.
22434
22435
22436 @c *********************************
22437 @node Creating Sample Bodies Using gnatstub
22438 @chapter Creating Sample Bodies Using @command{gnatstub}
22439 @findex gnatstub
22440
22441 @noindent
22442 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
22443 for library unit declarations.
22444
22445 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
22446 driver (see @ref{The GNAT Driver and Project Files}).
22447
22448 To create a body stub, @command{gnatstub} has to compile the library
22449 unit declaration. Therefore, bodies can be created only for legal
22450 library units. Moreover, if a library unit depends semantically upon
22451 units located outside the current directory, you have to provide
22452 the source search path when calling @command{gnatstub}, see the description
22453 of @command{gnatstub} switches below.
22454
22455 By default, all the program unit body stubs generated by @code{gnatstub}
22456 raise the predefined @code{Program_Error} exception, which will catch
22457 accidental calls of generated stubs. This behavior can be changed with
22458 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
22459
22460 @menu
22461 * Running gnatstub::
22462 * Switches for gnatstub::
22463 @end menu
22464
22465 @node Running gnatstub
22466 @section Running @command{gnatstub}
22467
22468 @noindent
22469 @command{gnatstub} has the command-line interface of the form
22470
22471 @smallexample
22472 $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
22473 @end smallexample
22474
22475 @noindent
22476 where
22477 @table @var
22478 @item filename
22479 is the name of the source file that contains a library unit declaration
22480 for which a body must be created. The file name may contain the path
22481 information.
22482 The file name does not have to follow the GNAT file name conventions. If the
22483 name
22484 does not follow GNAT file naming conventions, the name of the body file must
22485 be provided
22486 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
22487 If the file name follows the GNAT file naming
22488 conventions and the name of the body file is not provided,
22489 @command{gnatstub}
22490 creates the name
22491 of the body file from the argument file name by replacing the @file{.ads}
22492 suffix
22493 with the @file{.adb} suffix.
22494
22495 @item directory
22496 indicates the directory in which the body stub is to be placed (the default
22497 is the
22498 current directory)
22499
22500 @item switches
22501 is an optional sequence of switches as described in the next section
22502 @end table
22503
22504 @node Switches for gnatstub
22505 @section Switches for @command{gnatstub}
22506
22507 @table @option
22508 @c !sort!
22509
22510 @item ^-f^/FULL^
22511 @cindex @option{^-f^/FULL^} (@command{gnatstub})
22512 If the destination directory already contains a file with the name of the
22513 body file
22514 for the argument spec file, replace it with the generated body stub.
22515
22516 @item ^-hs^/HEADER=SPEC^
22517 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
22518 Put the comment header (i.e., all the comments preceding the
22519 compilation unit) from the source of the library unit declaration
22520 into the body stub.
22521
22522 @item ^-hg^/HEADER=GENERAL^
22523 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
22524 Put a sample comment header into the body stub.
22525
22526 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
22527 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
22528 Use the content of the file as the comment header for a generated body stub.
22529
22530 @ifclear vms
22531 @item -IDIR
22532 @cindex @option{-IDIR} (@command{gnatstub})
22533 @itemx -I-
22534 @cindex @option{-I-} (@command{gnatstub})
22535 @end ifclear
22536 @ifset vms
22537 @item /NOCURRENT_DIRECTORY
22538 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
22539 @end ifset
22540 ^These switches have ^This switch has^ the same meaning as in calls to
22541 @command{gcc}.
22542 ^They define ^It defines ^ the source search path in the call to
22543 @command{gcc} issued
22544 by @command{gnatstub} to compile an argument source file.
22545
22546 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
22547 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
22548 This switch has the same meaning as in calls to @command{gcc}.
22549 It defines the additional configuration file to be passed to the call to
22550 @command{gcc} issued
22551 by @command{gnatstub} to compile an argument source file.
22552
22553 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
22554 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
22555 (@var{n} is a non-negative integer). Set the maximum line length in the
22556 body stub to @var{n}; the default is 79. The maximum value that can be
22557 specified is 32767. Note that in the special case of configuration
22558 pragma files, the maximum is always 32767 regardless of whether or
22559 not this switch appears.
22560
22561 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
22562 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
22563 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
22564 the generated body sample to @var{n}.
22565 The default indentation is 3.
22566
22567 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
22568 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
22569 Order local bodies alphabetically. (By default local bodies are ordered
22570 in the same way as the corresponding local specs in the argument spec file.)
22571
22572 @item ^-i^/INDENTATION=^@var{n}
22573 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
22574 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
22575
22576 @item ^-k^/TREE_FILE=SAVE^
22577 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
22578 Do not remove the tree file (i.e., the snapshot of the compiler internal
22579 structures used by @command{gnatstub}) after creating the body stub.
22580
22581 @item ^-l^/LINE_LENGTH=^@var{n}
22582 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
22583 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
22584
22585 @item ^--no-exception^/NO_EXCEPTION^
22586 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
22587 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
22588 This is not always possible for function stubs.
22589
22590 @item ^-o ^/BODY=^@var{body-name}
22591 @cindex @option{^-o^/BODY^} (@command{gnatstub})
22592 Body file name.  This should be set if the argument file name does not
22593 follow
22594 the GNAT file naming
22595 conventions. If this switch is omitted the default name for the body will be
22596 obtained
22597 from the argument file name according to the GNAT file naming conventions.
22598
22599 @item ^-q^/QUIET^
22600 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
22601 Quiet mode: do not generate a confirmation when a body is
22602 successfully created, and do not generate a message when a body is not
22603 required for an
22604 argument unit.
22605
22606 @item ^-r^/TREE_FILE=REUSE^
22607 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
22608 Reuse the tree file (if it exists) instead of creating it.  Instead of
22609 creating the tree file for the library unit declaration, @command{gnatstub}
22610 tries to find it in the current directory and use it for creating
22611 a body. If the tree file is not found, no body is created. This option
22612 also implies @option{^-k^/SAVE^}, whether or not
22613 the latter is set explicitly.
22614
22615 @item ^-t^/TREE_FILE=OVERWRITE^
22616 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
22617 Overwrite the existing tree file.  If the current directory already
22618 contains the file which, according to the GNAT file naming rules should
22619 be considered as a tree file for the argument source file,
22620 @command{gnatstub}
22621 will refuse to create the tree file needed to create a sample body
22622 unless this option is set.
22623
22624 @item ^-v^/VERBOSE^
22625 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
22626 Verbose mode: generate version information.
22627
22628 @end table
22629
22630 @c *********************************
22631 @node Generating Ada Bindings for C and C++ headers
22632 @chapter Generating Ada Bindings for C and C++ headers
22633 @findex binding
22634
22635 @noindent
22636 GNAT now comes with a new experimental binding generator for C and C++
22637 headers which is intended to do 95% of the tedious work of generating
22638 Ada specs from C or C++ header files. Note that this still is a work in
22639 progress, not designed to generate 100% correct Ada specs.
22640
22641 The code generated is using the Ada 2005 syntax, which makes it
22642 easier to interface with other languages than previous versions of Ada.
22643
22644 @menu
22645 * Running the binding generator::
22646 * Generating bindings for C++ headers::
22647 * Switches::
22648 @end menu
22649
22650 @node Running the binding generator
22651 @section Running the binding generator
22652
22653 @noindent
22654 The binding generator is part of the @command{gcc} compiler and can be
22655 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
22656 spec files for the header files specified on the command line, and all
22657 header files needed by these files transitivitely. For example:
22658
22659 @smallexample
22660 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
22661 $ gcc -c -gnat05 *.ads
22662 @end smallexample
22663
22664 will generate, under GNU/Linux, the following files: @file{time_h.ads},
22665 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
22666 correspond to the files @file{/usr/include/time.h},
22667 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
22668 mode these Ada specs.
22669
22670 The @code{-C} switch tells @command{gcc} to extract comments from headers,
22671 and will attempt to generate corresponding Ada comments.
22672
22673 If you want to generate a single Ada file and not the transitive closure, you
22674 can use instead the @option{-fdump-ada-spec-slim} switch.
22675
22676 Note that we recommend when possible to use the @command{g++} driver to
22677 generate bindings, even for most C headers, since this will in general
22678 generate better Ada specs. For generating bindings for C++ headers, it is
22679 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
22680 is equivalent in this case. If @command{g++} cannot work on your C headers
22681 because of incompatibilities between C and C++, then you can fallback to
22682 @command{gcc} instead.
22683
22684 For an example of better bindings generated from the C++ front-end,
22685 the name of the parameters (when available) are actually ignored by the C
22686 front-end. Consider the following C header:
22687
22688 @smallexample
22689 extern void foo (int variable);
22690 @end smallexample
22691
22692 with the C front-end, @code{variable} is ignored, and the above is handled as:
22693
22694 @smallexample
22695 extern void foo (int);
22696 @end smallexample
22697
22698 generating a generic:
22699
22700 @smallexample
22701 procedure foo (param1 : int);
22702 @end smallexample
22703
22704 with the C++ front-end, the name is available, and we generate:
22705
22706 @smallexample
22707 procedure foo (variable : int);
22708 @end smallexample
22709
22710 In some cases, the generated bindings will be more complete or more meaningful
22711 when defining some macros, which you can do via the @option{-D} switch. This
22712 is for example the case with @file{Xlib.h} under GNU/Linux:
22713
22714 @smallexample
22715 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
22716 @end smallexample
22717
22718 The above will generate more complete bindings than a straight call without
22719 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
22720
22721 In other cases, it is not possible to parse a header file in a stand alone
22722 manner, because other include files need to be included first. In this
22723 case, the solution is to create a small header file including the needed
22724 @code{#include} and possible @code{#define} directives. For example, to
22725 generate Ada bindings for @file{readline/readline.h}, you need to first
22726 include @file{stdio.h}, so you can create a file with the following two
22727 lines in e.g. @file{readline1.h}:
22728
22729 @smallexample
22730 #include <stdio.h>
22731 #include <readline/readline.h>
22732 @end smallexample
22733
22734 and then generate Ada bindings from this file:
22735
22736 @smallexample
22737 $ g++ -c -fdump-ada-spec readline1.h
22738 @end smallexample
22739
22740 @node Generating bindings for C++ headers
22741 @section Generating bindings for C++ headers
22742
22743 @noindent
22744 Generating bindings for C++ headers is done using the same options, always
22745 with the @command{g++} compiler.
22746
22747 In this mode, C++ classes will be mapped to Ada tagged types, constructors
22748 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
22749 multiple inheritance of abstract classes will be mapped to Ada interfaces
22750 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
22751 information on interfacing to C++).
22752
22753 For example, given the following C++ header file:
22754
22755 @smallexample
22756 @group
22757 @cartouche
22758 class Carnivore @{
22759 public:
22760    virtual int Number_Of_Teeth () = 0;
22761 @};
22762
22763 class Domestic @{
22764 public:
22765    virtual void Set_Owner (char* Name) = 0;
22766 @};
22767
22768 class Animal @{
22769 public:
22770   int Age_Count;
22771   virtual void Set_Age (int New_Age);
22772 @};
22773
22774 class Dog : Animal, Carnivore, Domestic @{
22775  public:
22776   int  Tooth_Count;
22777   char *Owner;
22778
22779   virtual int  Number_Of_Teeth ();
22780   virtual void Set_Owner (char* Name);
22781
22782   Dog();
22783 @};
22784 @end cartouche
22785 @end group
22786 @end smallexample
22787
22788 The corresponding Ada code is generated:
22789
22790 @smallexample @c ada
22791 @group
22792 @cartouche
22793   package Class_Carnivore is
22794     type Carnivore is limited interface;
22795     pragma Import (CPP, Carnivore);
22796
22797     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
22798   end;
22799   use Class_Carnivore;
22800
22801   package Class_Domestic is
22802     type Domestic is limited interface;
22803     pragma Import (CPP, Domestic);
22804
22805     procedure Set_Owner
22806       (this : access Domestic;
22807        Name : Interfaces.C.Strings.chars_ptr) is abstract;
22808   end;
22809   use Class_Domestic;
22810
22811   package Class_Animal is
22812     type Animal is tagged limited record
22813       Age_Count : aliased int;
22814     end record;
22815     pragma Import (CPP, Animal);
22816
22817     procedure Set_Age (this : access Animal; New_Age : int);
22818     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
22819   end;
22820   use Class_Animal;
22821
22822   package Class_Dog is
22823     type Dog is new Animal and Carnivore and Domestic with record
22824       Tooth_Count : aliased int;
22825       Owner : Interfaces.C.Strings.chars_ptr;
22826     end record;
22827     pragma Import (CPP, Dog);
22828
22829     function Number_Of_Teeth (this : access Dog) return int;
22830     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
22831
22832     procedure Set_Owner
22833       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
22834     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
22835
22836     function New_Dog return Dog;
22837     pragma CPP_Constructor (New_Dog);
22838     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
22839   end;
22840   use Class_Dog;
22841 @end cartouche
22842 @end group
22843 @end smallexample
22844
22845 @node Switches
22846 @section Switches
22847
22848 @table @option
22849 @item -fdump-ada-spec
22850 @cindex @option{-fdump-ada-spec} (@command{gcc})
22851 Generate Ada spec files for the given header files transitively (including
22852 all header files that these headers depend upon).
22853
22854 @item -fdump-ada-spec-slim
22855 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
22856 Generate Ada spec files for the header files specified on the command line
22857 only.
22858
22859 @item -C
22860 @cindex @option{-C} (@command{gcc})
22861 Extract comments from headers and generate Ada comments in the Ada spec files.
22862 @end table
22863
22864 @node Other Utility Programs
22865 @chapter Other Utility Programs
22866
22867 @noindent
22868 This chapter discusses some other utility programs available in the Ada
22869 environment.
22870
22871 @menu
22872 * Using Other Utility Programs with GNAT::
22873 * The External Symbol Naming Scheme of GNAT::
22874 * Converting Ada Files to html with gnathtml::
22875 * Installing gnathtml::
22876 @ifset vms
22877 * LSE::
22878 * Profiling::
22879 @end ifset
22880 @end menu
22881
22882 @node Using Other Utility Programs with GNAT
22883 @section Using Other Utility Programs with GNAT
22884
22885 @noindent
22886 The object files generated by GNAT are in standard system format and in
22887 particular the debugging information uses this format. This means
22888 programs generated by GNAT can be used with existing utilities that
22889 depend on these formats.
22890
22891 @ifclear vms
22892 In general, any utility program that works with C will also often work with
22893 Ada programs generated by GNAT. This includes software utilities such as
22894 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
22895 as Purify.
22896 @end ifclear
22897
22898 @node The External Symbol Naming Scheme of GNAT
22899 @section The External Symbol Naming Scheme of GNAT
22900
22901 @noindent
22902 In order to interpret the output from GNAT, when using tools that are
22903 originally intended for use with other languages, it is useful to
22904 understand the conventions used to generate link names from the Ada
22905 entity names.
22906
22907 All link names are in all lowercase letters. With the exception of library
22908 procedure names, the mechanism used is simply to use the full expanded
22909 Ada name with dots replaced by double underscores. For example, suppose
22910 we have the following package spec:
22911
22912 @smallexample @c ada
22913 @group
22914 @cartouche
22915 package QRS is
22916    MN : Integer;
22917 end QRS;
22918 @end cartouche
22919 @end group
22920 @end smallexample
22921
22922 @noindent
22923 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
22924 the corresponding link name is @code{qrs__mn}.
22925 @findex Export
22926 Of course if a @code{pragma Export} is used this may be overridden:
22927
22928 @smallexample @c ada
22929 @group
22930 @cartouche
22931 package Exports is
22932    Var1 : Integer;
22933    pragma Export (Var1, C, External_Name => "var1_name");
22934    Var2 : Integer;
22935    pragma Export (Var2, C, Link_Name => "var2_link_name");
22936 end Exports;
22937 @end cartouche
22938 @end group
22939 @end smallexample
22940
22941 @noindent
22942 In this case, the link name for @var{Var1} is whatever link name the
22943 C compiler would assign for the C function @var{var1_name}. This typically
22944 would be either @var{var1_name} or @var{_var1_name}, depending on operating
22945 system conventions, but other possibilities exist. The link name for
22946 @var{Var2} is @var{var2_link_name}, and this is not operating system
22947 dependent.
22948
22949 @findex _main
22950 One exception occurs for library level procedures. A potential ambiguity
22951 arises between the required name @code{_main} for the C main program,
22952 and the name we would otherwise assign to an Ada library level procedure
22953 called @code{Main} (which might well not be the main program).
22954
22955 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
22956 names. So if we have a library level procedure such as
22957
22958 @smallexample @c ada
22959 @group
22960 @cartouche
22961 procedure Hello (S : String);
22962 @end cartouche
22963 @end group
22964 @end smallexample
22965
22966 @noindent
22967 the external name of this procedure will be @var{_ada_hello}.
22968
22969
22970 @node Converting Ada Files to html with gnathtml
22971 @section Converting Ada Files to HTML with @code{gnathtml}
22972
22973 @noindent
22974 This @code{Perl} script allows Ada source files to be browsed using
22975 standard Web browsers. For installation procedure, see the section
22976 @xref{Installing gnathtml}.
22977
22978 Ada reserved keywords are highlighted in a bold font and Ada comments in
22979 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
22980 switch to suppress the generation of cross-referencing information, user
22981 defined variables and types will appear in a different color; you will
22982 be able to click on any identifier and go to its declaration.
22983
22984 The command line is as follow:
22985 @smallexample
22986 $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
22987 @end smallexample
22988
22989 @noindent
22990 You can pass it as many Ada files as you want. @code{gnathtml} will generate
22991 an html file for every ada file, and a global file called @file{index.htm}.
22992 This file is an index of every identifier defined in the files.
22993
22994 The available ^switches^options^ are the following ones:
22995
22996 @table @option
22997 @item -83
22998 @cindex @option{-83} (@code{gnathtml})
22999 Only the Ada 83 subset of keywords will be highlighted.
23000
23001 @item -cc @var{color}
23002 @cindex @option{-cc} (@code{gnathtml})
23003 This option allows you to change the color used for comments. The default
23004 value is green. The color argument can be any name accepted by html.
23005
23006 @item -d
23007 @cindex @option{-d} (@code{gnathtml})
23008 If the Ada files depend on some other files (for instance through
23009 @code{with} clauses, the latter files will also be converted to html.
23010 Only the files in the user project will be converted to html, not the files
23011 in the run-time library itself.
23012
23013 @item -D
23014 @cindex @option{-D} (@code{gnathtml})
23015 This command is the same as @option{-d} above, but @command{gnathtml} will
23016 also look for files in the run-time library, and generate html files for them.
23017
23018 @item -ext @var{extension}
23019 @cindex @option{-ext} (@code{gnathtml})
23020 This option allows you to change the extension of the generated HTML files.
23021 If you do not specify an extension, it will default to @file{htm}.
23022
23023 @item -f
23024 @cindex @option{-f} (@code{gnathtml})
23025 By default, gnathtml will generate html links only for global entities
23026 ('with'ed units, global variables and types,@dots{}).  If you specify
23027 @option{-f} on the command line, then links will be generated for local
23028 entities too.
23029
23030 @item -l @var{number}
23031 @cindex @option{-l} (@code{gnathtml})
23032 If this ^switch^option^ is provided and @var{number} is not 0, then
23033 @code{gnathtml} will number the html files every @var{number} line.
23034
23035 @item -I @var{dir}
23036 @cindex @option{-I} (@code{gnathtml})
23037 Specify a directory to search for library files (@file{.ALI} files) and
23038 source files. You can provide several -I switches on the command line,
23039 and the directories will be parsed in the order of the command line.
23040
23041 @item -o @var{dir}
23042 @cindex @option{-o} (@code{gnathtml})
23043 Specify the output directory for html files. By default, gnathtml will
23044 saved the generated html files in a subdirectory named @file{html/}.
23045
23046 @item -p @var{file}
23047 @cindex @option{-p} (@code{gnathtml})
23048 If you are using Emacs and the most recent Emacs Ada mode, which provides
23049 a full Integrated Development Environment for compiling, checking,
23050 running and debugging applications, you may use @file{.gpr} files
23051 to give the directories where Emacs can find sources and object files.
23052
23053 Using this ^switch^option^, you can tell gnathtml to use these files.
23054 This allows you to get an html version of your application, even if it
23055 is spread over multiple directories.
23056
23057 @item -sc @var{color}
23058 @cindex @option{-sc} (@code{gnathtml})
23059 This ^switch^option^ allows you to change the color used for symbol
23060 definitions.
23061 The default value is red. The color argument can be any name accepted by html.
23062
23063 @item -t @var{file}
23064 @cindex @option{-t} (@code{gnathtml})
23065 This ^switch^option^ provides the name of a file. This file contains a list of
23066 file names to be converted, and the effect is exactly as though they had
23067 appeared explicitly on the command line. This
23068 is the recommended way to work around the command line length limit on some
23069 systems.
23070
23071 @end table
23072
23073 @node Installing gnathtml
23074 @section Installing @code{gnathtml}
23075
23076 @noindent
23077 @code{Perl} needs to be installed on your machine to run this script.
23078 @code{Perl} is freely available for almost every architecture and
23079 Operating System via the Internet.
23080
23081 On Unix systems, you  may want to modify  the  first line of  the script
23082 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
23083 is. The syntax of this line is:
23084 @smallexample
23085 #!full_path_name_to_perl
23086 @end smallexample
23087
23088 @noindent
23089 Alternatively, you may run the script using the following command line:
23090
23091 @smallexample
23092 $ perl gnathtml.pl @ovar{switches} @var{files}
23093 @end smallexample
23094
23095 @ifset vms
23096 @node LSE
23097 @section LSE
23098 @findex LSE
23099
23100 @noindent
23101 The GNAT distribution provides an Ada 95 template for the HP Language
23102 Sensitive Editor (LSE), a component of DECset. In order to
23103 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
23104
23105 @node Profiling
23106 @section Profiling
23107 @findex PCA
23108
23109 @noindent
23110 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
23111 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
23112 the collection phase with the /DEBUG qualifier.
23113
23114 @smallexample
23115 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
23116 $ DEFINE LIB$DEBUG PCA$COLLECTOR
23117 $ RUN/DEBUG <PROGRAM_NAME>
23118 @end smallexample
23119 @noindent
23120 @end ifset
23121
23122 @ifclear vms
23123 @c ******************************
23124 @node Code Coverage and Profiling
23125 @chapter Code Coverage and Profiling
23126 @cindex Code Coverage
23127 @cindex Profiling
23128
23129 @noindent
23130 This chapter describes how to use @code{gcov} - coverage testing tool - and
23131 @code{gprof} - profiler tool - on your Ada programs.
23132
23133 @menu
23134 * Code Coverage of Ada Programs using gcov::
23135 * Profiling an Ada Program using gprof::
23136 @end menu
23137
23138 @node Code Coverage of Ada Programs using gcov
23139 @section Code Coverage of Ada Programs using gcov
23140 @cindex gcov
23141 @cindex -fprofile-arcs
23142 @cindex -ftest-coverage
23143 @cindex -coverage
23144 @cindex Code Coverage
23145
23146 @noindent
23147 @code{gcov} is a test coverage program: it analyzes the execution of a given
23148 program on selected tests, to help you determine the portions of the program
23149 that are still untested.
23150
23151 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
23152 User's Guide. You can refer to this documentation for a more complete
23153 description.
23154
23155 This chapter provides a quick startup guide, and
23156 details some Gnat-specific features.
23157
23158 @menu
23159 * Quick startup guide::
23160 * Gnat specifics::
23161 @end menu
23162
23163 @node Quick startup guide
23164 @subsection Quick startup guide
23165
23166 In order to perform coverage analysis of a program using @code{gcov}, 3
23167 steps are needed:
23168
23169 @itemize @bullet
23170 @item
23171 Code instrumentation during the compilation process
23172 @item
23173 Execution of the instrumented program
23174 @item
23175 Execution of the @code{gcov} tool to generate the result.
23176 @end itemize
23177
23178 The code instrumentation needed by gcov is created at the object level:
23179 The source code is not modified in any way, because the instrumentation code is
23180 inserted by gcc during the compilation process. To compile your code with code
23181 coverage activated, you need to recompile your whole project using the
23182 switches
23183 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
23184 @code{-fprofile-arcs}.
23185
23186 @smallexample
23187 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
23188    -largs -fprofile-arcs
23189 @end smallexample
23190
23191 This compilation process will create @file{.gcno} files together with
23192 the usual object files.
23193
23194 Once the program is compiled with coverage instrumentation, you can
23195 run it as many times as needed - on portions of a test suite for
23196 example. The first execution will produce @file{.gcda} files at the
23197 same location as the @file{.gcno} files.  The following executions
23198 will update those files, so that a cumulative result of the covered
23199 portions of the program is generated.
23200
23201 Finally, you need to call the @code{gcov} tool. The different options of
23202 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
23203
23204 This will create annotated source files with a @file{.gcov} extension:
23205 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
23206
23207 @node Gnat specifics
23208 @subsection Gnat specifics
23209
23210 Because Ada semantics, portions of the source code may be shared among
23211 several object files. This is the case for example when generics are
23212 involved, when inlining is active  or when declarations generate  initialisation
23213 calls. In order to take
23214 into account this shared code, you need to call @code{gcov} on all
23215 source files of the tested program at once.
23216
23217 The list of source files might exceed the system's maximum command line
23218 length. In order to bypass this limitation, a new mechanism has been
23219 implemented in @code{gcov}: you can now list all your project's files into a
23220 text file, and provide this file to gcov as a parameter,  preceded by a @@
23221 (e.g. @samp{gcov @@mysrclist.txt}).
23222
23223 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
23224 not supported as there can be unresolved symbols during the final link.
23225
23226 @node Profiling an Ada Program using gprof
23227 @section Profiling an Ada Program using gprof
23228 @cindex gprof
23229 @cindex -pg
23230 @cindex Profiling
23231
23232 @noindent
23233 This section is not meant to be an exhaustive documentation of @code{gprof}.
23234 Full documentation for it can be found in the GNU Profiler User's Guide
23235 documentation that is part of this GNAT distribution.
23236
23237 Profiling a program helps determine the parts of a program that are executed
23238 most often, and are therefore the most time-consuming.
23239
23240 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
23241 better handle Ada programs and multitasking.
23242 It is currently supported on the following platforms
23243 @itemize @bullet
23244 @item
23245 linux x86/x86_64
23246 @item
23247 solaris sparc/sparc64/x86
23248 @item
23249 windows x86
23250 @end itemize
23251
23252 @noindent
23253 In order to profile a program using @code{gprof}, 3 steps are needed:
23254
23255 @itemize @bullet
23256 @item
23257 Code instrumentation, requiring a full recompilation of the project with the
23258 proper switches.
23259 @item
23260 Execution of the program under the analysis conditions, i.e. with the desired
23261 input.
23262 @item
23263 Analysis of the results using the @code{gprof} tool.
23264 @end itemize
23265
23266 @noindent
23267 The following sections detail the different steps, and indicate how
23268 to interpret the results:
23269 @menu
23270 * Compilation for profiling::
23271 * Program execution::
23272 * Running gprof::
23273 * Interpretation of profiling results::
23274 @end menu
23275
23276 @node Compilation for profiling
23277 @subsection Compilation for profiling
23278 @cindex -pg
23279 @cindex Profiling
23280
23281 In order to profile a program the first step is to tell the compiler
23282 to generate the necessary profiling information. The compiler switch to be used
23283 is @code{-pg}, which must be added to other compilation switches. This
23284 switch needs to be specified both during compilation and link stages, and can
23285 be specified once when using gnatmake:
23286
23287 @smallexample
23288 gnatmake -f -pg -P my_project
23289 @end smallexample
23290
23291 @noindent
23292 Note that only the objects that were compiled with the @samp{-pg} switch will be
23293 profiled; if you need to profile your whole project, use the
23294 @samp{-f} gnatmake switch to force full recompilation.
23295
23296 @node Program execution
23297 @subsection Program execution
23298
23299 @noindent
23300 Once the program has been compiled for profiling, you can run it as usual.
23301
23302 The only constraint imposed by profiling is that the program must terminate
23303 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
23304 properly analyzed.
23305
23306 Once the program completes execution, a data file called @file{gmon.out} is
23307 generated in the directory where the program was launched from. If this file
23308 already exists, it will be overwritten.
23309
23310 @node Running gprof
23311 @subsection Running gprof
23312
23313 @noindent
23314 The @code{gprof} tool is called as follow:
23315
23316 @smallexample
23317 gprof my_prog gmon.out
23318 @end smallexample
23319
23320 @noindent
23321 or simpler:
23322
23323 @smallexample
23324 gprof my_prog
23325 @end smallexample
23326
23327 @noindent
23328 The complete form of the gprof command line is the following:
23329
23330 @smallexample
23331 gprof [^switches^options^] [executable [data-file]]
23332 @end smallexample
23333
23334 @noindent
23335 @code{gprof} supports numerous ^switch^options^. The order of these
23336 ^switch^options^ does not matter. The full list of options can be found in
23337 the GNU Profiler User's Guide documentation that comes with this documentation.
23338
23339 The following is the subset of those switches that is most relevant:
23340
23341 @table @option
23342
23343 @item --demangle[=@var{style}]
23344 @itemx --no-demangle
23345 @cindex @option{--demangle} (@code{gprof})
23346 These options control whether symbol names should be demangled when
23347 printing output.  The default is to demangle C++ symbols.  The
23348 @code{--no-demangle} option may be used to turn off demangling. Different
23349 compilers have different mangling styles.  The optional demangling style
23350 argument can be used to choose an appropriate demangling style for your
23351 compiler, in particular Ada symbols generated by GNAT can be demangled using
23352 @code{--demangle=gnat}.
23353
23354 @item -e @var{function_name}
23355 @cindex @option{-e} (@code{gprof})
23356 The @samp{-e @var{function}} option tells @code{gprof} not to print
23357 information about the function @var{function_name} (and its
23358 children@dots{}) in the call graph.  The function will still be listed
23359 as a child of any functions that call it, but its index number will be
23360 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
23361 given; only one @var{function_name} may be indicated with each @samp{-e}
23362 option.
23363
23364 @item -E @var{function_name}
23365 @cindex @option{-E} (@code{gprof})
23366 The @code{-E @var{function}} option works like the @code{-e} option, but
23367 execution time spent in the function (and children who were not called from
23368 anywhere else), will not be used to compute the percentages-of-time for
23369 the call graph.  More than one @samp{-E} option may be given; only one
23370 @var{function_name} may be indicated with each @samp{-E} option.
23371
23372 @item -f @var{function_name}
23373 @cindex @option{-f} (@code{gprof})
23374 The @samp{-f @var{function}} option causes @code{gprof} to limit the
23375 call graph to the function @var{function_name} and its children (and
23376 their children@dots{}).  More than one @samp{-f} option may be given;
23377 only one @var{function_name} may be indicated with each @samp{-f}
23378 option.
23379
23380 @item -F @var{function_name}
23381 @cindex @option{-F} (@code{gprof})
23382 The @samp{-F @var{function}} option works like the @code{-f} option, but
23383 only time spent in the function and its children (and their
23384 children@dots{}) will be used to determine total-time and
23385 percentages-of-time for the call graph.  More than one @samp{-F} option
23386 may be given; only one @var{function_name} may be indicated with each
23387 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
23388
23389 @end table
23390
23391 @node Interpretation of profiling results
23392 @subsection Interpretation of profiling results
23393
23394 @noindent
23395
23396 The results of the profiling analysis are represented by two arrays: the
23397 'flat profile' and the 'call graph'. Full documentation of those outputs
23398 can be found in the GNU Profiler User's Guide.
23399
23400 The flat profile shows the time spent in each function of the program, and how
23401 many time it has been called. This allows you to locate easily the most
23402 time-consuming functions.
23403
23404 The call graph shows, for each subprogram, the subprograms that call it,
23405 and the subprograms that it calls. It also provides an estimate of the time
23406 spent in each of those callers/called subprograms.
23407 @end ifclear
23408
23409 @c ******************************
23410 @node Running and Debugging Ada Programs
23411 @chapter Running and Debugging Ada Programs
23412 @cindex Debugging
23413
23414 @noindent
23415 This chapter discusses how to debug Ada programs.
23416 @ifset vms
23417 It applies to GNAT on the Alpha OpenVMS platform;
23418 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
23419 since HP has implemented Ada support in the OpenVMS debugger on I64.
23420 @end ifset
23421
23422 An incorrect Ada program may be handled in three ways by the GNAT compiler:
23423
23424 @enumerate
23425 @item
23426 The illegality may be a violation of the static semantics of Ada. In
23427 that case GNAT diagnoses the constructs in the program that are illegal.
23428 It is then a straightforward matter for the user to modify those parts of
23429 the program.
23430
23431 @item
23432 The illegality may be a violation of the dynamic semantics of Ada. In
23433 that case the program compiles and executes, but may generate incorrect
23434 results, or may terminate abnormally with some exception.
23435
23436 @item
23437 When presented with a program that contains convoluted errors, GNAT
23438 itself may terminate abnormally without providing full diagnostics on
23439 the incorrect user program.
23440 @end enumerate
23441
23442 @menu
23443 * The GNAT Debugger GDB::
23444 * Running GDB::
23445 * Introduction to GDB Commands::
23446 * Using Ada Expressions::
23447 * Calling User-Defined Subprograms::
23448 * Using the Next Command in a Function::
23449 * Ada Exceptions::
23450 * Ada Tasks::
23451 * Debugging Generic Units::
23452 * GNAT Abnormal Termination or Failure to Terminate::
23453 * Naming Conventions for GNAT Source Files::
23454 * Getting Internal Debugging Information::
23455 * Stack Traceback::
23456 @end menu
23457
23458 @cindex Debugger
23459 @findex gdb
23460
23461 @node The GNAT Debugger GDB
23462 @section The GNAT Debugger GDB
23463
23464 @noindent
23465 @code{GDB} is a general purpose, platform-independent debugger that
23466 can be used to debug mixed-language programs compiled with @command{gcc},
23467 and in particular is capable of debugging Ada programs compiled with
23468 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
23469 complex Ada data structures.
23470
23471 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
23472 @ifset vms
23473 located in the GNU:[DOCS] directory,
23474 @end ifset
23475 for full details on the usage of @code{GDB}, including a section on
23476 its usage on programs. This manual should be consulted for full
23477 details. The section that follows is a brief introduction to the
23478 philosophy and use of @code{GDB}.
23479
23480 When GNAT programs are compiled, the compiler optionally writes debugging
23481 information into the generated object file, including information on
23482 line numbers, and on declared types and variables. This information is
23483 separate from the generated code. It makes the object files considerably
23484 larger, but it does not add to the size of the actual executable that
23485 will be loaded into memory, and has no impact on run-time performance. The
23486 generation of debug information is triggered by the use of the
23487 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
23488 used to carry out the compilations. It is important to emphasize that
23489 the use of these options does not change the generated code.
23490
23491 The debugging information is written in standard system formats that
23492 are used by many tools, including debuggers and profilers. The format
23493 of the information is typically designed to describe C types and
23494 semantics, but GNAT implements a translation scheme which allows full
23495 details about Ada types and variables to be encoded into these
23496 standard C formats. Details of this encoding scheme may be found in
23497 the file exp_dbug.ads in the GNAT source distribution. However, the
23498 details of this encoding are, in general, of no interest to a user,
23499 since @code{GDB} automatically performs the necessary decoding.
23500
23501 When a program is bound and linked, the debugging information is
23502 collected from the object files, and stored in the executable image of
23503 the program. Again, this process significantly increases the size of
23504 the generated executable file, but it does not increase the size of
23505 the executable program itself. Furthermore, if this program is run in
23506 the normal manner, it runs exactly as if the debug information were
23507 not present, and takes no more actual memory.
23508
23509 However, if the program is run under control of @code{GDB}, the
23510 debugger is activated.  The image of the program is loaded, at which
23511 point it is ready to run.  If a run command is given, then the program
23512 will run exactly as it would have if @code{GDB} were not present. This
23513 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
23514 entirely non-intrusive until a breakpoint is encountered.  If no
23515 breakpoint is ever hit, the program will run exactly as it would if no
23516 debugger were present. When a breakpoint is hit, @code{GDB} accesses
23517 the debugging information and can respond to user commands to inspect
23518 variables, and more generally to report on the state of execution.
23519
23520 @c **************
23521 @node Running GDB
23522 @section Running GDB
23523
23524 @noindent
23525 This section describes how to initiate the debugger.
23526 @c The above sentence is really just filler, but it was otherwise
23527 @c clumsy to get the first paragraph nonindented given the conditional
23528 @c nature of the description
23529
23530 @ifclear vms
23531 The debugger can be launched from a @code{GPS} menu or
23532 directly from the command line. The description below covers the latter use.
23533 All the commands shown can be used in the @code{GPS} debug console window,
23534 but there are usually more GUI-based ways to achieve the same effect.
23535 @end ifclear
23536
23537 The command to run @code{GDB} is
23538
23539 @smallexample
23540 $ ^gdb program^GDB PROGRAM^
23541 @end smallexample
23542
23543 @noindent
23544 where @code{^program^PROGRAM^} is the name of the executable file. This
23545 activates the debugger and results in a prompt for debugger commands.
23546 The simplest command is simply @code{run}, which causes the program to run
23547 exactly as if the debugger were not present. The following section
23548 describes some of the additional commands that can be given to @code{GDB}.
23549
23550 @c *******************************
23551 @node Introduction to GDB Commands
23552 @section Introduction to GDB Commands
23553
23554 @noindent
23555 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
23556 Debugging with GDB, gdb, Debugging with GDB},
23557 @ifset vms
23558 located in the GNU:[DOCS] directory,
23559 @end ifset
23560 for extensive documentation on the use
23561 of these commands, together with examples of their use. Furthermore,
23562 the command @command{help} invoked from within GDB activates a simple help
23563 facility which summarizes the available commands and their options.
23564 In this section we summarize a few of the most commonly
23565 used commands to give an idea of what @code{GDB} is about. You should create
23566 a simple program with debugging information and experiment with the use of
23567 these @code{GDB} commands on the program as you read through the
23568 following section.
23569
23570 @table @code
23571 @item set args @var{arguments}
23572 The @var{arguments} list above is a list of arguments to be passed to
23573 the program on a subsequent run command, just as though the arguments
23574 had been entered on a normal invocation of the program. The @code{set args}
23575 command is not needed if the program does not require arguments.
23576
23577 @item run
23578 The @code{run} command causes execution of the program to start from
23579 the beginning. If the program is already running, that is to say if
23580 you are currently positioned at a breakpoint, then a prompt will ask
23581 for confirmation that you want to abandon the current execution and
23582 restart.
23583
23584 @item breakpoint @var{location}
23585 The breakpoint command sets a breakpoint, that is to say a point at which
23586 execution will halt and @code{GDB} will await further
23587 commands. @var{location} is
23588 either a line number within a file, given in the format @code{file:linenumber},
23589 or it is the name of a subprogram. If you request that a breakpoint be set on
23590 a subprogram that is overloaded, a prompt will ask you to specify on which of
23591 those subprograms you want to breakpoint. You can also
23592 specify that all of them should be breakpointed. If the program is run
23593 and execution encounters the breakpoint, then the program
23594 stops and @code{GDB} signals that the breakpoint was encountered by
23595 printing the line of code before which the program is halted.
23596
23597 @item breakpoint exception @var{name}
23598 A special form of the breakpoint command which breakpoints whenever
23599 exception @var{name} is raised.
23600 If @var{name} is omitted,
23601 then a breakpoint will occur when any exception is raised.
23602
23603 @item print @var{expression}
23604 This will print the value of the given expression. Most simple
23605 Ada expression formats are properly handled by @code{GDB}, so the expression
23606 can contain function calls, variables, operators, and attribute references.
23607
23608 @item continue
23609 Continues execution following a breakpoint, until the next breakpoint or the
23610 termination of the program.
23611
23612 @item step
23613 Executes a single line after a breakpoint. If the next statement
23614 is a subprogram call, execution continues into (the first statement of)
23615 the called subprogram.
23616
23617 @item next
23618 Executes a single line. If this line is a subprogram call, executes and
23619 returns from the call.
23620
23621 @item list
23622 Lists a few lines around the current source location. In practice, it
23623 is usually more convenient to have a separate edit window open with the
23624 relevant source file displayed. Successive applications of this command
23625 print subsequent lines. The command can be given an argument which is a
23626 line number, in which case it displays a few lines around the specified one.
23627
23628 @item backtrace
23629 Displays a backtrace of the call chain. This command is typically
23630 used after a breakpoint has occurred, to examine the sequence of calls that
23631 leads to the current breakpoint. The display includes one line for each
23632 activation record (frame) corresponding to an active subprogram.
23633
23634 @item up
23635 At a breakpoint, @code{GDB} can display the values of variables local
23636 to the current frame. The command @code{up} can be used to
23637 examine the contents of other active frames, by moving the focus up
23638 the stack, that is to say from callee to caller, one frame at a time.
23639
23640 @item down
23641 Moves the focus of @code{GDB} down from the frame currently being
23642 examined to the frame of its callee (the reverse of the previous command),
23643
23644 @item frame @var{n}
23645 Inspect the frame with the given number. The value 0 denotes the frame
23646 of the current breakpoint, that is to say the top of the call stack.
23647
23648 @end table
23649
23650 @noindent
23651 The above list is a very short introduction to the commands that
23652 @code{GDB} provides. Important additional capabilities, including conditional
23653 breakpoints, the ability to execute command sequences on a breakpoint,
23654 the ability to debug at the machine instruction level and many other
23655 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
23656 Debugging with GDB}.  Note that most commands can be abbreviated
23657 (for example, c for continue, bt for backtrace).
23658
23659 @node Using Ada Expressions
23660 @section Using Ada Expressions
23661 @cindex Ada expressions
23662
23663 @noindent
23664 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
23665 extensions. The philosophy behind the design of this subset is
23666
23667 @itemize @bullet
23668 @item
23669 That @code{GDB} should provide basic literals and access to operations for
23670 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
23671 leaving more sophisticated computations to subprograms written into the
23672 program (which therefore may be called from @code{GDB}).
23673
23674 @item
23675 That type safety and strict adherence to Ada language restrictions
23676 are not particularly important to the @code{GDB} user.
23677
23678 @item
23679 That brevity is important to the @code{GDB} user.
23680 @end itemize
23681
23682 @noindent
23683 Thus, for brevity, the debugger acts as if there were
23684 implicit @code{with} and @code{use} clauses in effect for all user-written
23685 packages, thus making it unnecessary to fully qualify most names with
23686 their packages, regardless of context. Where this causes ambiguity,
23687 @code{GDB} asks the user's intent.
23688
23689 For details on the supported Ada syntax, see @ref{Top,, Debugging with
23690 GDB, gdb, Debugging with GDB}.
23691
23692 @node Calling User-Defined Subprograms
23693 @section Calling User-Defined Subprograms
23694
23695 @noindent
23696 An important capability of @code{GDB} is the ability to call user-defined
23697 subprograms while debugging. This is achieved simply by entering
23698 a subprogram call statement in the form:
23699
23700 @smallexample
23701 call subprogram-name (parameters)
23702 @end smallexample
23703
23704 @noindent
23705 The keyword @code{call} can be omitted in the normal case where the
23706 @code{subprogram-name} does not coincide with any of the predefined
23707 @code{GDB} commands.
23708
23709 The effect is to invoke the given subprogram, passing it the
23710 list of parameters that is supplied. The parameters can be expressions and
23711 can include variables from the program being debugged. The
23712 subprogram must be defined
23713 at the library level within your program, and @code{GDB} will call the
23714 subprogram within the environment of your program execution (which
23715 means that the subprogram is free to access or even modify variables
23716 within your program).
23717
23718 The most important use of this facility is in allowing the inclusion of
23719 debugging routines that are tailored to particular data structures
23720 in your program. Such debugging routines can be written to provide a suitably
23721 high-level description of an abstract type, rather than a low-level dump
23722 of its physical layout. After all, the standard
23723 @code{GDB print} command only knows the physical layout of your
23724 types, not their abstract meaning. Debugging routines can provide information
23725 at the desired semantic level and are thus enormously useful.
23726
23727 For example, when debugging GNAT itself, it is crucial to have access to
23728 the contents of the tree nodes used to represent the program internally.
23729 But tree nodes are represented simply by an integer value (which in turn
23730 is an index into a table of nodes).
23731 Using the @code{print} command on a tree node would simply print this integer
23732 value, which is not very useful. But the PN routine (defined in file
23733 treepr.adb in the GNAT sources) takes a tree node as input, and displays
23734 a useful high level representation of the tree node, which includes the
23735 syntactic category of the node, its position in the source, the integers
23736 that denote descendant nodes and parent node, as well as varied
23737 semantic information. To study this example in more detail, you might want to
23738 look at the body of the PN procedure in the stated file.
23739
23740 @node Using the Next Command in a Function
23741 @section Using the Next Command in a Function
23742
23743 @noindent
23744 When you use the @code{next} command in a function, the current source
23745 location will advance to the next statement as usual. A special case
23746 arises in the case of a @code{return} statement.
23747
23748 Part of the code for a return statement is the ``epilog'' of the function.
23749 This is the code that returns to the caller. There is only one copy of
23750 this epilog code, and it is typically associated with the last return
23751 statement in the function if there is more than one return. In some
23752 implementations, this epilog is associated with the first statement
23753 of the function.
23754
23755 The result is that if you use the @code{next} command from a return
23756 statement that is not the last return statement of the function you
23757 may see a strange apparent jump to the last return statement or to
23758 the start of the function. You should simply ignore this odd jump.
23759 The value returned is always that from the first return statement
23760 that was stepped through.
23761
23762 @node Ada Exceptions
23763 @section Breaking on Ada Exceptions
23764 @cindex Exceptions
23765
23766 @noindent
23767 You can set breakpoints that trip when your program raises
23768 selected exceptions.
23769
23770 @table @code
23771 @item break exception
23772 Set a breakpoint that trips whenever (any task in the) program raises
23773 any exception.
23774
23775 @item break exception @var{name}
23776 Set a breakpoint that trips whenever (any task in the) program raises
23777 the exception @var{name}.
23778
23779 @item break exception unhandled
23780 Set a breakpoint that trips whenever (any task in the) program raises an
23781 exception for which there is no handler.
23782
23783 @item info exceptions
23784 @itemx info exceptions @var{regexp}
23785 The @code{info exceptions} command permits the user to examine all defined
23786 exceptions within Ada programs. With a regular expression, @var{regexp}, as
23787 argument, prints out only those exceptions whose name matches @var{regexp}.
23788 @end table
23789
23790 @node Ada Tasks
23791 @section Ada Tasks
23792 @cindex Tasks
23793
23794 @noindent
23795 @code{GDB} allows the following task-related commands:
23796
23797 @table @code
23798 @item info tasks
23799 This command shows a list of current Ada tasks, as in the following example:
23800
23801 @smallexample
23802 @iftex
23803 @leftskip=0cm
23804 @end iftex
23805 (gdb) info tasks
23806   ID       TID P-ID   Thread Pri State                 Name
23807    1   8088000   0   807e000  15 Child Activation Wait main_task
23808    2   80a4000   1   80ae000  15 Accept/Select Wait    b
23809    3   809a800   1   80a4800  15 Child Activation Wait a
23810 *  4   80ae800   3   80b8000  15 Running               c
23811 @end smallexample
23812
23813 @noindent
23814 In this listing, the asterisk before the first task indicates it to be the
23815 currently running task. The first column lists the task ID that is used
23816 to refer to tasks in the following commands.
23817
23818 @item break @var{linespec} task @var{taskid}
23819 @itemx break @var{linespec} task @var{taskid} if @dots{}
23820 @cindex Breakpoints and tasks
23821 These commands are like the @code{break @dots{} thread @dots{}}.
23822 @var{linespec} specifies source lines.
23823
23824 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
23825 to specify that you only want @code{GDB} to stop the program when a
23826 particular Ada task reaches this breakpoint. @var{taskid} is one of the
23827 numeric task identifiers assigned by @code{GDB}, shown in the first
23828 column of the @samp{info tasks} display.
23829
23830 If you do not specify @samp{task @var{taskid}} when you set a
23831 breakpoint, the breakpoint applies to @emph{all} tasks of your
23832 program.
23833
23834 You can use the @code{task} qualifier on conditional breakpoints as
23835 well; in this case, place @samp{task @var{taskid}} before the
23836 breakpoint condition (before the @code{if}).
23837
23838 @item task @var{taskno}
23839 @cindex Task switching
23840
23841 This command allows to switch to the task referred by @var{taskno}. In
23842 particular, This allows to browse the backtrace of the specified
23843 task. It is advised to switch back to the original task before
23844 continuing execution otherwise the scheduling of the program may be
23845 perturbed.
23846 @end table
23847
23848 @noindent
23849 For more detailed information on the tasking support,
23850 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
23851
23852 @node Debugging Generic Units
23853 @section Debugging Generic Units
23854 @cindex Debugging Generic Units
23855 @cindex Generics
23856
23857 @noindent
23858 GNAT always uses code expansion for generic instantiation. This means that
23859 each time an instantiation occurs, a complete copy of the original code is
23860 made, with appropriate substitutions of formals by actuals.
23861
23862 It is not possible to refer to the original generic entities in
23863 @code{GDB}, but it is always possible to debug a particular instance of
23864 a generic, by using the appropriate expanded names. For example, if we have
23865
23866 @smallexample @c ada
23867 @group
23868 @cartouche
23869 procedure g is
23870
23871    generic package k is
23872       procedure kp (v1 : in out integer);
23873    end k;
23874
23875    package body k is
23876       procedure kp (v1 : in out integer) is
23877       begin
23878          v1 := v1 + 1;
23879       end kp;
23880    end k;
23881
23882    package k1 is new k;
23883    package k2 is new k;
23884
23885    var : integer := 1;
23886
23887 begin
23888    k1.kp (var);
23889    k2.kp (var);
23890    k1.kp (var);
23891    k2.kp (var);
23892 end;
23893 @end cartouche
23894 @end group
23895 @end smallexample
23896
23897 @noindent
23898 Then to break on a call to procedure kp in the k2 instance, simply
23899 use the command:
23900
23901 @smallexample
23902 (gdb) break g.k2.kp
23903 @end smallexample
23904
23905 @noindent
23906 When the breakpoint occurs, you can step through the code of the
23907 instance in the normal manner and examine the values of local variables, as for
23908 other units.
23909
23910 @node GNAT Abnormal Termination or Failure to Terminate
23911 @section GNAT Abnormal Termination or Failure to Terminate
23912 @cindex GNAT Abnormal Termination or Failure to Terminate
23913
23914 @noindent
23915 When presented with programs that contain serious errors in syntax
23916 or semantics,
23917 GNAT may on rare occasions  experience problems in operation, such
23918 as aborting with a
23919 segmentation fault or illegal memory access, raising an internal
23920 exception, terminating abnormally, or failing to terminate at all.
23921 In such cases, you can activate
23922 various features of GNAT that can help you pinpoint the construct in your
23923 program that is the likely source of the problem.
23924
23925 The following strategies are presented in increasing order of
23926 difficulty, corresponding to your experience in using GNAT and your
23927 familiarity with compiler internals.
23928
23929 @enumerate
23930 @item
23931 Run @command{gcc} with the @option{-gnatf}. This first
23932 switch causes all errors on a given line to be reported. In its absence,
23933 only the first error on a line is displayed.
23934
23935 The @option{-gnatdO} switch causes errors to be displayed as soon as they
23936 are encountered, rather than after compilation is terminated. If GNAT
23937 terminates prematurely or goes into an infinite loop, the last error
23938 message displayed may help to pinpoint the culprit.
23939
23940 @item
23941 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
23942 mode, @command{gcc} produces ongoing information about the progress of the
23943 compilation and provides the name of each procedure as code is
23944 generated. This switch allows you to find which Ada procedure was being
23945 compiled when it encountered a code generation problem.
23946
23947 @item
23948 @cindex @option{-gnatdc} switch
23949 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
23950 switch that does for the front-end what @option{^-v^VERBOSE^} does
23951 for the back end. The system prints the name of each unit,
23952 either a compilation unit or nested unit, as it is being analyzed.
23953 @item
23954 Finally, you can start
23955 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
23956 front-end of GNAT, and can be run independently (normally it is just
23957 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
23958 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
23959 @code{where} command is the first line of attack; the variable
23960 @code{lineno} (seen by @code{print lineno}), used by the second phase of
23961 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
23962 which the execution stopped, and @code{input_file name} indicates the name of
23963 the source file.
23964 @end enumerate
23965
23966 @node Naming Conventions for GNAT Source Files
23967 @section Naming Conventions for GNAT Source Files
23968
23969 @noindent
23970 In order to examine the workings of the GNAT system, the following
23971 brief description of its organization may be helpful:
23972
23973 @itemize @bullet
23974 @item
23975 Files with prefix @file{^sc^SC^} contain the lexical scanner.
23976
23977 @item
23978 All files prefixed with @file{^par^PAR^} are components of the parser. The
23979 numbers correspond to chapters of the Ada Reference Manual. For example,
23980 parsing of select statements can be found in @file{par-ch9.adb}.
23981
23982 @item
23983 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
23984 numbers correspond to chapters of the Ada standard. For example, all
23985 issues involving context clauses can be found in @file{sem_ch10.adb}. In
23986 addition, some features of the language require sufficient special processing
23987 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
23988 dynamic dispatching, etc.
23989
23990 @item
23991 All files prefixed with @file{^exp^EXP^} perform normalization and
23992 expansion of the intermediate representation (abstract syntax tree, or AST).
23993 these files use the same numbering scheme as the parser and semantics files.
23994 For example, the construction of record initialization procedures is done in
23995 @file{exp_ch3.adb}.
23996
23997 @item
23998 The files prefixed with @file{^bind^BIND^} implement the binder, which
23999 verifies the consistency of the compilation, determines an order of
24000 elaboration, and generates the bind file.
24001
24002 @item
24003 The files @file{atree.ads} and @file{atree.adb} detail the low-level
24004 data structures used by the front-end.
24005
24006 @item
24007 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
24008 the abstract syntax tree as produced by the parser.
24009
24010 @item
24011 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
24012 all entities, computed during semantic analysis.
24013
24014 @item
24015 Library management issues are dealt with in files with prefix
24016 @file{^lib^LIB^}.
24017
24018 @item
24019 @findex Ada
24020 @cindex Annex A
24021 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
24022 defined in Annex A.
24023
24024 @item
24025 @findex Interfaces
24026 @cindex Annex B
24027 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
24028 defined in Annex B.
24029
24030 @item
24031 @findex System
24032 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
24033 both language-defined children and GNAT run-time routines.
24034
24035 @item
24036 @findex GNAT
24037 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
24038 general-purpose packages, fully documented in their specs. All
24039 the other @file{.c} files are modifications of common @command{gcc} files.
24040 @end itemize
24041
24042 @node Getting Internal Debugging Information
24043 @section Getting Internal Debugging Information
24044
24045 @noindent
24046 Most compilers have internal debugging switches and modes. GNAT
24047 does also, except GNAT internal debugging switches and modes are not
24048 secret. A summary and full description of all the compiler and binder
24049 debug flags are in the file @file{debug.adb}. You must obtain the
24050 sources of the compiler to see the full detailed effects of these flags.
24051
24052 The switches that print the source of the program (reconstructed from
24053 the internal tree) are of general interest for user programs, as are the
24054 options to print
24055 the full internal tree, and the entity table (the symbol table
24056 information). The reconstructed source provides a readable version of the
24057 program after the front-end has completed analysis and  expansion,
24058 and is useful when studying the performance of specific constructs.
24059 For example, constraint checks are indicated, complex aggregates
24060 are replaced with loops and assignments, and tasking primitives
24061 are replaced with run-time calls.
24062
24063 @node Stack Traceback
24064 @section Stack Traceback
24065 @cindex traceback
24066 @cindex stack traceback
24067 @cindex stack unwinding
24068
24069 @noindent
24070 Traceback is a mechanism to display the sequence of subprogram calls that
24071 leads to a specified execution point in a program. Often (but not always)
24072 the execution point is an instruction at which an exception has been raised.
24073 This mechanism is also known as @i{stack unwinding} because it obtains
24074 its information by scanning the run-time stack and recovering the activation
24075 records of all active subprograms. Stack unwinding is one of the most
24076 important tools for program debugging.
24077
24078 The first entry stored in traceback corresponds to the deepest calling level,
24079 that is to say the subprogram currently executing the instruction
24080 from which we want to obtain the traceback.
24081
24082 Note that there is no runtime performance penalty when stack traceback
24083 is enabled, and no exception is raised during program execution.
24084
24085 @menu
24086 * Non-Symbolic Traceback::
24087 * Symbolic Traceback::
24088 @end menu
24089
24090 @node Non-Symbolic Traceback
24091 @subsection Non-Symbolic Traceback
24092 @cindex traceback, non-symbolic
24093
24094 @noindent
24095 Note: this feature is not supported on all platforms. See
24096 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
24097 platforms.
24098
24099 @menu
24100 * Tracebacks From an Unhandled Exception::
24101 * Tracebacks From Exception Occurrences (non-symbolic)::
24102 * Tracebacks From Anywhere in a Program (non-symbolic)::
24103 @end menu
24104
24105 @node Tracebacks From an Unhandled Exception
24106 @subsubsection Tracebacks From an Unhandled Exception
24107
24108 @noindent
24109 A runtime non-symbolic traceback is a list of addresses of call instructions.
24110 To enable this feature you must use the @option{-E}
24111 @code{gnatbind}'s option. With this option a stack traceback is stored as part
24112 of exception information. You can retrieve this information using the
24113 @code{addr2line} tool.
24114
24115 Here is a simple example:
24116
24117 @smallexample @c ada
24118 @cartouche
24119 procedure STB is
24120
24121    procedure P1 is
24122    begin
24123       raise Constraint_Error;
24124    end P1;
24125
24126    procedure P2 is
24127    begin
24128       P1;
24129    end P2;
24130
24131 begin
24132    P2;
24133 end STB;
24134 @end cartouche
24135 @end smallexample
24136
24137 @smallexample
24138 $ gnatmake stb -bargs -E
24139 $ stb
24140
24141 Execution terminated by unhandled exception
24142 Exception name: CONSTRAINT_ERROR
24143 Message: stb.adb:5
24144 Call stack traceback locations:
24145 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24146 @end smallexample
24147
24148 @noindent
24149 As we see the traceback lists a sequence of addresses for the unhandled
24150 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
24151 guess that this exception come from procedure P1. To translate these
24152 addresses into the source lines where the calls appear, the
24153 @code{addr2line} tool, described below, is invaluable. The use of this tool
24154 requires the program to be compiled with debug information.
24155
24156 @smallexample
24157 $ gnatmake -g stb -bargs -E
24158 $ stb
24159
24160 Execution terminated by unhandled exception
24161 Exception name: CONSTRAINT_ERROR
24162 Message: stb.adb:5
24163 Call stack traceback locations:
24164 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24165
24166 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
24167    0x4011f1 0x77e892a4
24168
24169 00401373 at d:/stb/stb.adb:5
24170 0040138B at d:/stb/stb.adb:10
24171 0040139C at d:/stb/stb.adb:14
24172 00401335 at d:/stb/b~stb.adb:104
24173 004011C4 at /build/@dots{}/crt1.c:200
24174 004011F1 at /build/@dots{}/crt1.c:222
24175 77E892A4 in ?? at ??:0
24176 @end smallexample
24177
24178 @noindent
24179 The @code{addr2line} tool has several other useful options:
24180
24181 @table @code
24182 @item --functions
24183 to get the function name corresponding to any location
24184
24185 @item --demangle=gnat
24186 to use the gnat decoding mode for the function names. Note that
24187 for binutils version 2.9.x the option is simply @option{--demangle}.
24188 @end table
24189
24190 @smallexample
24191 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
24192    0x40139c 0x401335 0x4011c4 0x4011f1
24193
24194 00401373 in stb.p1 at d:/stb/stb.adb:5
24195 0040138B in stb.p2 at d:/stb/stb.adb:10
24196 0040139C in stb at d:/stb/stb.adb:14
24197 00401335 in main at d:/stb/b~stb.adb:104
24198 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
24199 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
24200 @end smallexample
24201
24202 @noindent
24203 From this traceback we can see that the exception was raised in
24204 @file{stb.adb} at line 5, which was reached from a procedure call in
24205 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
24206 which contains the call to the main program.
24207 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
24208 and the output will vary from platform to platform.
24209
24210 It is also possible to use @code{GDB} with these traceback addresses to debug
24211 the program. For example, we can break at a given code location, as reported
24212 in the stack traceback:
24213
24214 @smallexample
24215 $ gdb -nw stb
24216 @ifclear vms
24217 @noindent
24218 Furthermore, this feature is not implemented inside Windows DLL. Only
24219 the non-symbolic traceback is reported in this case.
24220 @end ifclear
24221
24222 (gdb) break *0x401373
24223 Breakpoint 1 at 0x401373: file stb.adb, line 5.
24224 @end smallexample
24225
24226 @noindent
24227 It is important to note that the stack traceback addresses
24228 do not change when debug information is included. This is particularly useful
24229 because it makes it possible to release software without debug information (to
24230 minimize object size), get a field report that includes a stack traceback
24231 whenever an internal bug occurs, and then be able to retrieve the sequence
24232 of calls with the same program compiled with debug information.
24233
24234 @node Tracebacks From Exception Occurrences (non-symbolic)
24235 @subsubsection Tracebacks From Exception Occurrences
24236
24237 @noindent
24238 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
24239 The stack traceback is attached to the exception information string, and can
24240 be retrieved in an exception handler within the Ada program, by means of the
24241 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
24242
24243 @smallexample @c ada
24244 with Ada.Text_IO;
24245 with Ada.Exceptions;
24246
24247 procedure STB is
24248
24249    use Ada;
24250    use Ada.Exceptions;
24251
24252    procedure P1 is
24253       K : Positive := 1;
24254    begin
24255       K := K - 1;
24256    exception
24257       when E : others =>
24258          Text_IO.Put_Line (Exception_Information (E));
24259    end P1;
24260
24261    procedure P2 is
24262    begin
24263       P1;
24264    end P2;
24265
24266 begin
24267    P2;
24268 end STB;
24269 @end smallexample
24270
24271 @noindent
24272 This program will output:
24273
24274 @smallexample
24275 $ stb
24276
24277 Exception name: CONSTRAINT_ERROR
24278 Message: stb.adb:12
24279 Call stack traceback locations:
24280 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
24281 @end smallexample
24282
24283 @node Tracebacks From Anywhere in a Program (non-symbolic)
24284 @subsubsection Tracebacks From Anywhere in a Program
24285
24286 @noindent
24287 It is also possible to retrieve a stack traceback from anywhere in a
24288 program. For this you need to
24289 use the @code{GNAT.Traceback} API. This package includes a procedure called
24290 @code{Call_Chain} that computes a complete stack traceback, as well as useful
24291 display procedures described below. It is not necessary to use the
24292 @option{-E gnatbind} option in this case, because the stack traceback mechanism
24293 is invoked explicitly.
24294
24295 @noindent
24296 In the following example we compute a traceback at a specific location in
24297 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
24298 convert addresses to strings:
24299
24300 @smallexample @c ada
24301 with Ada.Text_IO;
24302 with GNAT.Traceback;
24303 with GNAT.Debug_Utilities;
24304
24305 procedure STB is
24306
24307    use Ada;
24308    use GNAT;
24309    use GNAT.Traceback;
24310
24311    procedure P1 is
24312       TB  : Tracebacks_Array (1 .. 10);
24313       --  We are asking for a maximum of 10 stack frames.
24314       Len : Natural;
24315       --  Len will receive the actual number of stack frames returned.
24316    begin
24317       Call_Chain (TB, Len);
24318
24319       Text_IO.Put ("In STB.P1 : ");
24320
24321       for K in 1 .. Len loop
24322          Text_IO.Put (Debug_Utilities.Image (TB (K)));
24323          Text_IO.Put (' ');
24324       end loop;
24325
24326       Text_IO.New_Line;
24327    end P1;
24328
24329    procedure P2 is
24330    begin
24331       P1;
24332    end P2;
24333
24334 begin
24335    P2;
24336 end STB;
24337 @end smallexample
24338
24339 @smallexample
24340 $ gnatmake -g stb
24341 $ stb
24342
24343 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
24344 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
24345 @end smallexample
24346
24347 @noindent
24348 You can then get further information by invoking the @code{addr2line}
24349 tool as described earlier (note that the hexadecimal addresses
24350 need to be specified in C format, with a leading ``0x'').
24351
24352 @node Symbolic Traceback
24353 @subsection Symbolic Traceback
24354 @cindex traceback, symbolic
24355
24356 @noindent
24357 A symbolic traceback is a stack traceback in which procedure names are
24358 associated with each code location.
24359
24360 @noindent
24361 Note that this feature is not supported on all platforms. See
24362 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
24363 list of currently supported platforms.
24364
24365 @noindent
24366 Note that the symbolic traceback requires that the program be compiled
24367 with debug information. If it is not compiled with debug information
24368 only the non-symbolic information will be valid.
24369
24370 @menu
24371 * Tracebacks From Exception Occurrences (symbolic)::
24372 * Tracebacks From Anywhere in a Program (symbolic)::
24373 @end menu
24374
24375 @node Tracebacks From Exception Occurrences (symbolic)
24376 @subsubsection Tracebacks From Exception Occurrences
24377
24378 @smallexample @c ada
24379 with Ada.Text_IO;
24380 with GNAT.Traceback.Symbolic;
24381
24382 procedure STB is
24383
24384    procedure P1 is
24385    begin
24386       raise Constraint_Error;
24387    end P1;
24388
24389    procedure P2 is
24390    begin
24391       P1;
24392    end P2;
24393
24394    procedure P3 is
24395    begin
24396       P2;
24397    end P3;
24398
24399 begin
24400    P3;
24401 exception
24402    when E : others =>
24403       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
24404 end STB;
24405 @end smallexample
24406
24407 @smallexample
24408 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
24409 $ stb
24410
24411 0040149F in stb.p1 at stb.adb:8
24412 004014B7 in stb.p2 at stb.adb:13
24413 004014CF in stb.p3 at stb.adb:18
24414 004015DD in ada.stb at stb.adb:22
24415 00401461 in main at b~stb.adb:168
24416 004011C4 in __mingw_CRTStartup at crt1.c:200
24417 004011F1 in mainCRTStartup at crt1.c:222
24418 77E892A4 in ?? at ??:0
24419 @end smallexample
24420
24421 @noindent
24422 In the above example the ``.\'' syntax in the @command{gnatmake} command
24423 is currently required by @command{addr2line} for files that are in
24424 the current working directory.
24425 Moreover, the exact sequence of linker options may vary from platform
24426 to platform.
24427 The above @option{-largs} section is for Windows platforms. By contrast,
24428 under Unix there is no need for the @option{-largs} section.
24429 Differences across platforms are due to details of linker implementation.
24430
24431 @node Tracebacks From Anywhere in a Program (symbolic)
24432 @subsubsection Tracebacks From Anywhere in a Program
24433
24434 @noindent
24435 It is possible to get a symbolic stack traceback
24436 from anywhere in a program, just as for non-symbolic tracebacks.
24437 The first step is to obtain a non-symbolic
24438 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
24439 information. Here is an example:
24440
24441 @smallexample @c ada
24442 with Ada.Text_IO;
24443 with GNAT.Traceback;
24444 with GNAT.Traceback.Symbolic;
24445
24446 procedure STB is
24447
24448    use Ada;
24449    use GNAT.Traceback;
24450    use GNAT.Traceback.Symbolic;
24451
24452    procedure P1 is
24453       TB  : Tracebacks_Array (1 .. 10);
24454       --  We are asking for a maximum of 10 stack frames.
24455       Len : Natural;
24456       --  Len will receive the actual number of stack frames returned.
24457    begin
24458       Call_Chain (TB, Len);
24459       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
24460    end P1;
24461
24462    procedure P2 is
24463    begin
24464       P1;
24465    end P2;
24466
24467 begin
24468    P2;
24469 end STB;
24470 @end smallexample
24471
24472 @c ******************************
24473 @ifset vms
24474 @node Compatibility with HP Ada
24475 @chapter Compatibility with HP Ada
24476 @cindex Compatibility
24477
24478 @noindent
24479 @cindex DEC Ada
24480 @cindex HP Ada
24481 @cindex Compatibility between GNAT and HP Ada
24482 This chapter compares HP Ada (formerly known as ``DEC Ada'')
24483 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
24484 GNAT is highly compatible
24485 with HP Ada, and it should generally be straightforward to port code
24486 from the HP Ada environment to GNAT. However, there are a few language
24487 and implementation differences of which the user must be aware. These
24488 differences are discussed in this chapter. In
24489 addition, the operating environment and command structure for the
24490 compiler are different, and these differences are also discussed.
24491
24492 For further details on these and other compatibility issues,
24493 see Appendix E of the HP publication
24494 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
24495
24496 Except where otherwise indicated, the description of GNAT for OpenVMS
24497 applies to both the Alpha and I64 platforms.
24498
24499 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
24500 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24501
24502 The discussion in this chapter addresses specifically the implementation
24503 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
24504 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
24505 GNAT always follows the Alpha implementation.
24506
24507 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
24508 attributes are recognized, although only a subset of them can sensibly
24509 be implemented.  The description of pragmas in
24510 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
24511 indicates whether or not they are applicable to non-VMS systems.
24512
24513 @menu
24514 * Ada Language Compatibility::
24515 * Differences in the Definition of Package System::
24516 * Language-Related Features::
24517 * The Package STANDARD::
24518 * The Package SYSTEM::
24519 * Tasking and Task-Related Features::
24520 * Pragmas and Pragma-Related Features::
24521 * Library of Predefined Units::
24522 * Bindings::
24523 * Main Program Definition::
24524 * Implementation-Defined Attributes::
24525 * Compiler and Run-Time Interfacing::
24526 * Program Compilation and Library Management::
24527 * Input-Output::
24528 * Implementation Limits::
24529 * Tools and Utilities::
24530 @end menu
24531
24532 @node Ada Language Compatibility
24533 @section Ada Language Compatibility
24534
24535 @noindent
24536 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
24537 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
24538 with Ada 83, and therefore Ada 83 programs will compile
24539 and run under GNAT with
24540 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
24541 provides details on specific incompatibilities.
24542
24543 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
24544 as well as the pragma @code{ADA_83}, to force the compiler to
24545 operate in Ada 83 mode. This mode does not guarantee complete
24546 conformance to Ada 83, but in practice is sufficient to
24547 eliminate most sources of incompatibilities.
24548 In particular, it eliminates the recognition of the
24549 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
24550 in Ada 83 programs is legal, and handles the cases of packages
24551 with optional bodies, and generics that instantiate unconstrained
24552 types without the use of @code{(<>)}.
24553
24554 @node Differences in the Definition of Package System
24555 @section Differences in the Definition of Package @code{System}
24556
24557 @noindent
24558 An Ada compiler is allowed to add
24559 implementation-dependent declarations to package @code{System}.
24560 In normal mode,
24561 GNAT does not take advantage of this permission, and the version of
24562 @code{System} provided by GNAT exactly matches that defined in the Ada
24563 Reference Manual.
24564
24565 However, HP Ada adds an extensive set of declarations to package
24566 @code{System},
24567 as fully documented in the HP Ada manuals. To minimize changes required
24568 for programs that make use of these extensions, GNAT provides the pragma
24569 @code{Extend_System} for extending the definition of package System. By using:
24570 @cindex pragma @code{Extend_System}
24571 @cindex @code{Extend_System} pragma
24572
24573 @smallexample @c ada
24574 @group
24575 @cartouche
24576 pragma Extend_System (Aux_DEC);
24577 @end cartouche
24578 @end group
24579 @end smallexample
24580
24581 @noindent
24582 the set of definitions in @code{System} is extended to include those in
24583 package @code{System.Aux_DEC}.
24584 @cindex @code{System.Aux_DEC} package
24585 @cindex @code{Aux_DEC} package (child of @code{System})
24586 These definitions are incorporated directly into package @code{System},
24587 as though they had been declared there. For a
24588 list of the declarations added, see the spec of this package,
24589 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
24590 @cindex @file{s-auxdec.ads} file
24591 The pragma @code{Extend_System} is a configuration pragma, which means that
24592 it can be placed in the file @file{gnat.adc}, so that it will automatically
24593 apply to all subsequent compilations. See @ref{Configuration Pragmas},
24594 for further details.
24595
24596 An alternative approach that avoids the use of the non-standard
24597 @code{Extend_System} pragma is to add a context clause to the unit that
24598 references these facilities:
24599
24600 @smallexample @c ada
24601 @cartouche
24602 with System.Aux_DEC;
24603 use  System.Aux_DEC;
24604 @end cartouche
24605 @end smallexample
24606
24607 @noindent
24608 The effect is not quite semantically identical to incorporating
24609 the declarations directly into package @code{System},
24610 but most programs will not notice a difference
24611 unless they use prefix notation (e.g.@: @code{System.Integer_8})
24612 to reference the entities directly in package @code{System}.
24613 For units containing such references,
24614 the prefixes must either be removed, or the pragma @code{Extend_System}
24615 must be used.
24616
24617 @node Language-Related Features
24618 @section Language-Related Features
24619
24620 @noindent
24621 The following sections highlight differences in types,
24622 representations of types, operations, alignment, and
24623 related topics.
24624
24625 @menu
24626 * Integer Types and Representations::
24627 * Floating-Point Types and Representations::
24628 * Pragmas Float_Representation and Long_Float::
24629 * Fixed-Point Types and Representations::
24630 * Record and Array Component Alignment::
24631 * Address Clauses::
24632 * Other Representation Clauses::
24633 @end menu
24634
24635 @node Integer Types and Representations
24636 @subsection Integer Types and Representations
24637
24638 @noindent
24639 The set of predefined integer types is identical in HP Ada and GNAT.
24640 Furthermore the representation of these integer types is also identical,
24641 including the capability of size clauses forcing biased representation.
24642
24643 In addition,
24644 HP Ada for OpenVMS Alpha systems has defined the
24645 following additional integer types in package @code{System}:
24646
24647 @itemize @bullet
24648
24649 @item
24650 @code{INTEGER_8}
24651
24652 @item
24653 @code{INTEGER_16}
24654
24655 @item
24656 @code{INTEGER_32}
24657
24658 @item
24659 @code{INTEGER_64}
24660
24661 @item
24662 @code{LARGEST_INTEGER}
24663 @end itemize
24664
24665 @noindent
24666 In GNAT, the first four of these types may be obtained from the
24667 standard Ada package @code{Interfaces}.
24668 Alternatively, by use of the pragma @code{Extend_System}, identical
24669 declarations can be referenced directly in package @code{System}.
24670 On both GNAT and HP Ada, the maximum integer size is 64 bits.
24671
24672 @node Floating-Point Types and Representations
24673 @subsection Floating-Point Types and Representations
24674 @cindex Floating-Point types
24675
24676 @noindent
24677 The set of predefined floating-point types is identical in HP Ada and GNAT.
24678 Furthermore the representation of these floating-point
24679 types is also identical. One important difference is that the default
24680 representation for HP Ada is @code{VAX_Float}, but the default representation
24681 for GNAT is IEEE.
24682
24683 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
24684 pragma @code{Float_Representation} as described in the HP Ada
24685 documentation.
24686 For example, the declarations:
24687
24688 @smallexample @c ada
24689 @cartouche
24690 type F_Float is digits 6;
24691 pragma Float_Representation (VAX_Float, F_Float);
24692 @end cartouche
24693 @end smallexample
24694
24695 @noindent
24696 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
24697 format.
24698 This set of declarations actually appears in @code{System.Aux_DEC},
24699 which contains
24700 the full set of additional floating-point declarations provided in
24701 the HP Ada version of package @code{System}.
24702 This and similar declarations may be accessed in a user program
24703 by using pragma @code{Extend_System}. The use of this
24704 pragma, and the related pragma @code{Long_Float} is described in further
24705 detail in the following section.
24706
24707 @node Pragmas Float_Representation and Long_Float
24708 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
24709
24710 @noindent
24711 HP Ada provides the pragma @code{Float_Representation}, which
24712 acts as a program library switch to allow control over
24713 the internal representation chosen for the predefined
24714 floating-point types declared in the package @code{Standard}.
24715 The format of this pragma is as follows:
24716
24717 @smallexample @c ada
24718 @cartouche
24719 pragma Float_Representation(VAX_Float | IEEE_Float);
24720 @end cartouche
24721 @end smallexample
24722
24723 @noindent
24724 This pragma controls the representation of floating-point
24725 types as follows:
24726
24727 @itemize @bullet
24728 @item
24729 @code{VAX_Float} specifies that floating-point
24730 types are represented by default with the VAX system hardware types
24731 @code{F-floating}, @code{D-floating}, @code{G-floating}.
24732 Note that the @code{H-floating}
24733 type was available only on VAX systems, and is not available
24734 in either HP Ada or GNAT.
24735
24736 @item
24737 @code{IEEE_Float} specifies that floating-point
24738 types are represented by default with the IEEE single and
24739 double floating-point types.
24740 @end itemize
24741
24742 @noindent
24743 GNAT provides an identical implementation of the pragma
24744 @code{Float_Representation}, except that it functions as a
24745 configuration pragma. Note that the
24746 notion of configuration pragma corresponds closely to the
24747 HP Ada notion of a program library switch.
24748
24749 When no pragma is used in GNAT, the default is @code{IEEE_Float},
24750 which is different
24751 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
24752 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
24753 advisable to change the format of numbers passed to standard library
24754 routines, and if necessary explicit type conversions may be needed.
24755
24756 The use of @code{IEEE_Float} is recommended in GNAT since it is more
24757 efficient, and (given that it conforms to an international standard)
24758 potentially more portable.
24759 The situation in which @code{VAX_Float} may be useful is in interfacing
24760 to existing code and data that expect the use of @code{VAX_Float}.
24761 In such a situation use the predefined @code{VAX_Float}
24762 types in package @code{System}, as extended by
24763 @code{Extend_System}. For example, use @code{System.F_Float}
24764 to specify the 32-bit @code{F-Float} format.
24765
24766 @noindent
24767 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
24768 to allow control over the internal representation chosen
24769 for the predefined type @code{Long_Float} and for floating-point
24770 type declarations with digits specified in the range 7 .. 15.
24771 The format of this pragma is as follows:
24772
24773 @smallexample @c ada
24774 @cartouche
24775 pragma Long_Float (D_FLOAT | G_FLOAT);
24776 @end cartouche
24777 @end smallexample
24778
24779 @node Fixed-Point Types and Representations
24780 @subsection Fixed-Point Types and Representations
24781
24782 @noindent
24783 On HP Ada for OpenVMS Alpha systems, rounding is
24784 away from zero for both positive and negative numbers.
24785 Therefore, @code{+0.5} rounds to @code{1},
24786 and @code{-0.5} rounds to @code{-1}.
24787
24788 On GNAT the results of operations
24789 on fixed-point types are in accordance with the Ada
24790 rules. In particular, results of operations on decimal
24791 fixed-point types are truncated.
24792
24793 @node Record and Array Component Alignment
24794 @subsection Record and Array Component Alignment
24795
24796 @noindent
24797 On HP Ada for OpenVMS Alpha, all non-composite components
24798 are aligned on natural boundaries. For example, 1-byte
24799 components are aligned on byte boundaries, 2-byte
24800 components on 2-byte boundaries, 4-byte components on 4-byte
24801 byte boundaries, and so on. The OpenVMS Alpha hardware
24802 runs more efficiently with naturally aligned data.
24803
24804 On GNAT, alignment rules are compatible
24805 with HP Ada for OpenVMS Alpha.
24806
24807 @node Address Clauses
24808 @subsection Address Clauses
24809
24810 @noindent
24811 In HP Ada and GNAT, address clauses are supported for
24812 objects and imported subprograms.
24813 The predefined type @code{System.Address} is a private type
24814 in both compilers on Alpha OpenVMS, with the same representation
24815 (it is simply a machine pointer). Addition, subtraction, and comparison
24816 operations are available in the standard Ada package
24817 @code{System.Storage_Elements}, or in package @code{System}
24818 if it is extended to include @code{System.Aux_DEC} using a
24819 pragma @code{Extend_System} as previously described.
24820
24821 Note that code that @code{with}'s both this extended package @code{System}
24822 and the package @code{System.Storage_Elements} should not @code{use}
24823 both packages, or ambiguities will result. In general it is better
24824 not to mix these two sets of facilities. The Ada package was
24825 designed specifically to provide the kind of features that HP Ada
24826 adds directly to package @code{System}.
24827
24828 The type @code{System.Address} is a 64-bit integer type in GNAT for
24829 I64 OpenVMS.  For more information,
24830 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24831
24832 GNAT is compatible with HP Ada in its handling of address
24833 clauses, except for some limitations in
24834 the form of address clauses for composite objects with
24835 initialization. Such address clauses are easily replaced
24836 by the use of an explicitly-defined constant as described
24837 in the Ada Reference Manual (13.1(22)). For example, the sequence
24838 of declarations:
24839
24840 @smallexample @c ada
24841 @cartouche
24842 X, Y : Integer := Init_Func;
24843 Q : String (X .. Y) := "abc";
24844 @dots{}
24845 for Q'Address use Compute_Address;
24846 @end cartouche
24847 @end smallexample
24848
24849 @noindent
24850 will be rejected by GNAT, since the address cannot be computed at the time
24851 that @code{Q} is declared. To achieve the intended effect, write instead:
24852
24853 @smallexample @c ada
24854 @group
24855 @cartouche
24856 X, Y : Integer := Init_Func;
24857 Q_Address : constant Address := Compute_Address;
24858 Q : String (X .. Y) := "abc";
24859 @dots{}
24860 for Q'Address use Q_Address;
24861 @end cartouche
24862 @end group
24863 @end smallexample
24864
24865 @noindent
24866 which will be accepted by GNAT (and other Ada compilers), and is also
24867 compatible with Ada 83. A fuller description of the restrictions
24868 on address specifications is found in @ref{Top, GNAT Reference Manual,
24869 About This Guide, gnat_rm, GNAT Reference Manual}.
24870
24871 @node Other Representation Clauses
24872 @subsection Other Representation Clauses
24873
24874 @noindent
24875 GNAT implements in a compatible manner all the representation
24876 clauses supported by HP Ada. In addition, GNAT
24877 implements the representation clause forms that were introduced in Ada 95,
24878 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
24879
24880 @node The Package STANDARD
24881 @section The Package @code{STANDARD}
24882
24883 @noindent
24884 The package @code{STANDARD}, as implemented by HP Ada, is fully
24885 described in the @cite{Ada Reference Manual} and in the
24886 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
24887 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
24888
24889 In addition, HP Ada supports the Latin-1 character set in
24890 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
24891 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
24892 the type @code{WIDE_CHARACTER}.
24893
24894 The floating-point types supported by GNAT are those
24895 supported by HP Ada, but the defaults are different, and are controlled by
24896 pragmas. See @ref{Floating-Point Types and Representations}, for details.
24897
24898 @node The Package SYSTEM
24899 @section The Package @code{SYSTEM}
24900
24901 @noindent
24902 HP Ada provides a specific version of the package
24903 @code{SYSTEM} for each platform on which the language is implemented.
24904 For the complete spec of the package @code{SYSTEM}, see
24905 Appendix F of the @cite{HP Ada Language Reference Manual}.
24906
24907 On HP Ada, the package @code{SYSTEM} includes the following conversion
24908 functions:
24909 @itemize @bullet
24910 @item @code{TO_ADDRESS(INTEGER)}
24911
24912 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
24913
24914 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
24915
24916 @item @code{TO_INTEGER(ADDRESS)}
24917
24918 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
24919
24920 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
24921 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
24922 @end itemize
24923
24924 @noindent
24925 By default, GNAT supplies a version of @code{SYSTEM} that matches
24926 the definition given in the @cite{Ada Reference Manual}.
24927 This
24928 is a subset of the HP system definitions, which is as
24929 close as possible to the original definitions. The only difference
24930 is that the definition of @code{SYSTEM_NAME} is different:
24931
24932 @smallexample @c ada
24933 @cartouche
24934 type Name is (SYSTEM_NAME_GNAT);
24935 System_Name : constant Name := SYSTEM_NAME_GNAT;
24936 @end cartouche
24937 @end smallexample
24938
24939 @noindent
24940 Also, GNAT adds the Ada declarations for
24941 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
24942
24943 However, the use of the following pragma causes GNAT
24944 to extend the definition of package @code{SYSTEM} so that it
24945 encompasses the full set of HP-specific extensions,
24946 including the functions listed above:
24947
24948 @smallexample @c ada
24949 @cartouche
24950 pragma Extend_System (Aux_DEC);
24951 @end cartouche
24952 @end smallexample
24953
24954 @noindent
24955 The pragma @code{Extend_System} is a configuration pragma that
24956 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
24957 Extend_System,,, gnat_rm, GNAT Reference Manual} for further details.
24958
24959 HP Ada does not allow the recompilation of the package
24960 @code{SYSTEM}. Instead HP Ada provides several pragmas
24961 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
24962 to modify values in the package @code{SYSTEM}.
24963 On OpenVMS Alpha systems, the pragma
24964 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
24965 its single argument.
24966
24967 GNAT does permit the recompilation of package @code{SYSTEM} using
24968 the special switch @option{-gnatg}, and this switch can be used if
24969 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
24970 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
24971 or @code{MEMORY_SIZE} by any other means.
24972
24973 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
24974 enumeration literal @code{SYSTEM_NAME_GNAT}.
24975
24976 The definitions provided by the use of
24977
24978 @smallexample @c ada
24979 pragma Extend_System (AUX_Dec);
24980 @end smallexample
24981
24982 @noindent
24983 are virtually identical to those provided by the HP Ada 83 package
24984 @code{SYSTEM}. One important difference is that the name of the
24985 @code{TO_ADDRESS}
24986 function for type @code{UNSIGNED_LONGWORD} is changed to
24987 @code{TO_ADDRESS_LONG}.
24988 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual} for a
24989 discussion of why this change was necessary.
24990
24991 @noindent
24992 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
24993 is in fact
24994 an extension to Ada 83 not strictly compatible with the reference manual.
24995 GNAT, in order to be exactly compatible with the standard,
24996 does not provide this capability. In HP Ada 83, the
24997 point of this definition is to deal with a call like:
24998
24999 @smallexample @c ada
25000 TO_ADDRESS (16#12777#);
25001 @end smallexample
25002
25003 @noindent
25004 Normally, according to Ada 83 semantics, one would expect this to be
25005 ambiguous, since it matches both the @code{INTEGER} and
25006 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
25007 However, in HP Ada 83, there is no ambiguity, since the
25008 definition using @i{universal_integer} takes precedence.
25009
25010 In GNAT, since the version with @i{universal_integer} cannot be supplied,
25011 it is
25012 not possible to be 100% compatible. Since there are many programs using
25013 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
25014 GNAT was
25015 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
25016 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
25017
25018 @smallexample @c ada
25019 function To_Address (X : Integer) return Address;
25020 pragma Pure_Function (To_Address);
25021
25022 function To_Address_Long (X : Unsigned_Longword) return Address;
25023 pragma Pure_Function (To_Address_Long);
25024 @end smallexample
25025
25026 @noindent
25027 This means that programs using @code{TO_ADDRESS} for
25028 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
25029
25030 @node Tasking and Task-Related Features
25031 @section Tasking and Task-Related Features
25032
25033 @noindent
25034 This section compares the treatment of tasking in GNAT
25035 and in HP Ada for OpenVMS Alpha.
25036 The GNAT description applies to both Alpha and I64 OpenVMS.
25037 For detailed information on tasking in
25038 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
25039 relevant run-time reference manual.
25040
25041 @menu
25042 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
25043 * Assigning Task IDs::
25044 * Task IDs and Delays::
25045 * Task-Related Pragmas::
25046 * Scheduling and Task Priority::
25047 * The Task Stack::
25048 * External Interrupts::
25049 @end menu
25050
25051 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25052 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25053
25054 @noindent
25055 On OpenVMS Alpha systems, each Ada task (except a passive
25056 task) is implemented as a single stream of execution
25057 that is created and managed by the kernel. On these
25058 systems, HP Ada tasking support is based on DECthreads,
25059 an implementation of the POSIX standard for threads.
25060
25061 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
25062 code that calls DECthreads routines can be used together.
25063 The interaction between Ada tasks and DECthreads routines
25064 can have some benefits. For example when on OpenVMS Alpha,
25065 HP Ada can call C code that is already threaded.
25066
25067 GNAT uses the facilities of DECthreads,
25068 and Ada tasks are mapped to threads.
25069
25070 @node Assigning Task IDs
25071 @subsection Assigning Task IDs
25072
25073 @noindent
25074 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
25075 the environment task that executes the main program. On
25076 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
25077 that have been created but are not yet activated.
25078
25079 On OpenVMS Alpha systems, task IDs are assigned at
25080 activation. On GNAT systems, task IDs are also assigned at
25081 task creation but do not have the same form or values as
25082 task ID values in HP Ada. There is no null task, and the
25083 environment task does not have a specific task ID value.
25084
25085 @node Task IDs and Delays
25086 @subsection Task IDs and Delays
25087
25088 @noindent
25089 On OpenVMS Alpha systems, tasking delays are implemented
25090 using Timer System Services. The Task ID is used for the
25091 identification of the timer request (the @code{REQIDT} parameter).
25092 If Timers are used in the application take care not to use
25093 @code{0} for the identification, because cancelling such a timer
25094 will cancel all timers and may lead to unpredictable results.
25095
25096 @node Task-Related Pragmas
25097 @subsection Task-Related Pragmas
25098
25099 @noindent
25100 Ada supplies the pragma @code{TASK_STORAGE}, which allows
25101 specification of the size of the guard area for a task
25102 stack. (The guard area forms an area of memory that has no
25103 read or write access and thus helps in the detection of
25104 stack overflow.) On OpenVMS Alpha systems, if the pragma
25105 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
25106 area is created. In the absence of a pragma @code{TASK_STORAGE},
25107 a default guard area is created.
25108
25109 GNAT supplies the following task-related pragmas:
25110
25111 @itemize @bullet
25112 @item  @code{TASK_INFO}
25113
25114 This pragma appears within a task definition and
25115 applies to the task in which it appears. The argument
25116 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
25117
25118 @item  @code{TASK_STORAGE}
25119
25120 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
25121 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
25122 @code{SUPPRESS}, and @code{VOLATILE}.
25123 @end itemize
25124 @node Scheduling and Task Priority
25125 @subsection Scheduling and Task Priority
25126
25127 @noindent
25128 HP Ada implements the Ada language requirement that
25129 when two tasks are eligible for execution and they have
25130 different priorities, the lower priority task does not
25131 execute while the higher priority task is waiting. The HP
25132 Ada Run-Time Library keeps a task running until either the
25133 task is suspended or a higher priority task becomes ready.
25134
25135 On OpenVMS Alpha systems, the default strategy is round-
25136 robin with preemption. Tasks of equal priority take turns
25137 at the processor. A task is run for a certain period of
25138 time and then placed at the tail of the ready queue for
25139 its priority level.
25140
25141 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
25142 which can be used to enable or disable round-robin
25143 scheduling of tasks with the same priority.
25144 See the relevant HP Ada run-time reference manual for
25145 information on using the pragmas to control HP Ada task
25146 scheduling.
25147
25148 GNAT follows the scheduling rules of Annex D (Real-Time
25149 Annex) of the @cite{Ada Reference Manual}. In general, this
25150 scheduling strategy is fully compatible with HP Ada
25151 although it provides some additional constraints (as
25152 fully documented in Annex D).
25153 GNAT implements time slicing control in a manner compatible with
25154 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
25155 are identical to the HP Ada 83 pragma of the same name.
25156 Note that it is not possible to mix GNAT tasking and
25157 HP Ada 83 tasking in the same program, since the two run-time
25158 libraries are not compatible.
25159
25160 @node The Task Stack
25161 @subsection The Task Stack
25162
25163 @noindent
25164 In HP Ada, a task stack is allocated each time a
25165 non-passive task is activated. As soon as the task is
25166 terminated, the storage for the task stack is deallocated.
25167 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
25168 a default stack size is used. Also, regardless of the size
25169 specified, some additional space is allocated for task
25170 management purposes. On OpenVMS Alpha systems, at least
25171 one page is allocated.
25172
25173 GNAT handles task stacks in a similar manner. In accordance with
25174 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
25175 an alternative method for controlling the task stack size.
25176 The specification of the attribute @code{T'STORAGE_SIZE} is also
25177 supported in a manner compatible with HP Ada.
25178
25179 @node External Interrupts
25180 @subsection External Interrupts
25181
25182 @noindent
25183 On HP Ada, external interrupts can be associated with task entries.
25184 GNAT is compatible with HP Ada in its handling of external interrupts.
25185
25186 @node Pragmas and Pragma-Related Features
25187 @section Pragmas and Pragma-Related Features
25188
25189 @noindent
25190 Both HP Ada and GNAT supply all language-defined pragmas
25191 as specified by the Ada 83 standard. GNAT also supplies all
25192 language-defined pragmas introduced by Ada 95 and Ada 2005.
25193 In addition, GNAT implements the implementation-defined pragmas
25194 from HP Ada 83.
25195
25196 @itemize @bullet
25197 @item  @code{AST_ENTRY}
25198
25199 @item  @code{COMMON_OBJECT}
25200
25201 @item  @code{COMPONENT_ALIGNMENT}
25202
25203 @item  @code{EXPORT_EXCEPTION}
25204
25205 @item  @code{EXPORT_FUNCTION}
25206
25207 @item  @code{EXPORT_OBJECT}
25208
25209 @item  @code{EXPORT_PROCEDURE}
25210
25211 @item  @code{EXPORT_VALUED_PROCEDURE}
25212
25213 @item  @code{FLOAT_REPRESENTATION}
25214
25215 @item  @code{IDENT}
25216
25217 @item  @code{IMPORT_EXCEPTION}
25218
25219 @item  @code{IMPORT_FUNCTION}
25220
25221 @item  @code{IMPORT_OBJECT}
25222
25223 @item  @code{IMPORT_PROCEDURE}
25224
25225 @item  @code{IMPORT_VALUED_PROCEDURE}
25226
25227 @item  @code{INLINE_GENERIC}
25228
25229 @item  @code{INTERFACE_NAME}
25230
25231 @item  @code{LONG_FLOAT}
25232
25233 @item  @code{MAIN_STORAGE}
25234
25235 @item  @code{PASSIVE}
25236
25237 @item  @code{PSECT_OBJECT}
25238
25239 @item  @code{SHARE_GENERIC}
25240
25241 @item  @code{SUPPRESS_ALL}
25242
25243 @item  @code{TASK_STORAGE}
25244
25245 @item  @code{TIME_SLICE}
25246
25247 @item  @code{TITLE}
25248 @end itemize
25249
25250 @noindent
25251 These pragmas are all fully implemented, with the exception of @code{TITLE},
25252 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
25253 recognized, but which have no
25254 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
25255 use of Ada protected objects. In GNAT, all generics are inlined.
25256
25257 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
25258 a separate subprogram specification which must appear before the
25259 subprogram body.
25260
25261 GNAT also supplies a number of implementation-defined pragmas as follows:
25262 @itemize @bullet
25263 @item  @code{ABORT_DEFER}
25264
25265 @item  @code{ADA_83}
25266
25267 @item  @code{ADA_95}
25268
25269 @item  @code{ADA_05}
25270
25271 @item  @code{ANNOTATE}
25272
25273 @item  @code{ASSERT}
25274
25275 @item  @code{C_PASS_BY_COPY}
25276
25277 @item  @code{CPP_CLASS}
25278
25279 @item  @code{CPP_CONSTRUCTOR}
25280
25281 @item  @code{CPP_DESTRUCTOR}
25282
25283 @item  @code{DEBUG}
25284
25285 @item  @code{EXTEND_SYSTEM}
25286
25287 @item  @code{LINKER_ALIAS}
25288
25289 @item  @code{LINKER_SECTION}
25290
25291 @item  @code{MACHINE_ATTRIBUTE}
25292
25293 @item  @code{NO_RETURN}
25294
25295 @item  @code{PURE_FUNCTION}
25296
25297 @item  @code{SOURCE_FILE_NAME}
25298
25299 @item  @code{SOURCE_REFERENCE}
25300
25301 @item  @code{TASK_INFO}
25302
25303 @item  @code{UNCHECKED_UNION}
25304
25305 @item  @code{UNIMPLEMENTED_UNIT}
25306
25307 @item  @code{UNIVERSAL_DATA}
25308
25309 @item  @code{UNSUPPRESS}
25310
25311 @item  @code{WARNINGS}
25312
25313 @item  @code{WEAK_EXTERNAL}
25314 @end itemize
25315
25316 @noindent
25317 For full details on these GNAT implementation-defined pragmas,
25318 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
25319 Manual}.
25320
25321 @menu
25322 * Restrictions on the Pragma INLINE::
25323 * Restrictions on the Pragma INTERFACE::
25324 * Restrictions on the Pragma SYSTEM_NAME::
25325 @end menu
25326
25327 @node Restrictions on the Pragma INLINE
25328 @subsection Restrictions on Pragma @code{INLINE}
25329
25330 @noindent
25331 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
25332 @itemize @bullet
25333 @item  Parameters cannot have a task type.
25334
25335 @item  Function results cannot be task types, unconstrained
25336 array types, or unconstrained types with discriminants.
25337
25338 @item  Bodies cannot declare the following:
25339 @itemize @bullet
25340 @item  Subprogram body or stub (imported subprogram is allowed)
25341
25342 @item  Tasks
25343
25344 @item  Generic declarations
25345
25346 @item  Instantiations
25347
25348 @item  Exceptions
25349
25350 @item  Access types (types derived from access types allowed)
25351
25352 @item  Array or record types
25353
25354 @item  Dependent tasks
25355
25356 @item  Direct recursive calls of subprogram or containing
25357 subprogram, directly or via a renaming
25358
25359 @end itemize
25360 @end itemize
25361
25362 @noindent
25363 In GNAT, the only restriction on pragma @code{INLINE} is that the
25364 body must occur before the call if both are in the same
25365 unit, and the size must be appropriately small. There are
25366 no other specific restrictions which cause subprograms to
25367 be incapable of being inlined.
25368
25369 @node  Restrictions on the Pragma INTERFACE
25370 @subsection  Restrictions on Pragma @code{INTERFACE}
25371
25372 @noindent
25373 The following restrictions on pragma @code{INTERFACE}
25374 are enforced by both HP Ada and GNAT:
25375 @itemize @bullet
25376 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
25377 Default is the default on OpenVMS Alpha systems.
25378
25379 @item  Parameter passing: Language specifies default
25380 mechanisms but can be overridden with an @code{EXPORT} pragma.
25381
25382 @itemize @bullet
25383 @item  Ada: Use internal Ada rules.
25384
25385 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
25386 record or task type. Result cannot be a string, an
25387 array, or a record.
25388
25389 @item  Fortran: Parameters cannot have a task type. Result cannot
25390 be a string, an array, or a record.
25391 @end itemize
25392 @end itemize
25393
25394 @noindent
25395 GNAT is entirely upwards compatible with HP Ada, and in addition allows
25396 record parameters for all languages.
25397
25398 @node  Restrictions on the Pragma SYSTEM_NAME
25399 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
25400
25401 @noindent
25402 For HP Ada for OpenVMS Alpha, the enumeration literal
25403 for the type @code{NAME} is @code{OPENVMS_AXP}.
25404 In GNAT, the enumeration
25405 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
25406
25407 @node  Library of Predefined Units
25408 @section  Library of Predefined Units
25409
25410 @noindent
25411 A library of predefined units is provided as part of the
25412 HP Ada and GNAT implementations. HP Ada does not provide
25413 the package @code{MACHINE_CODE} but instead recommends importing
25414 assembler code.
25415
25416 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
25417 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
25418 version.
25419 The HP Ada Predefined Library units are modified to remove post-Ada 83
25420 incompatibilities and to make them interoperable with GNAT
25421 (@pxref{Changes to DECLIB}, for details).
25422 The units are located in the @file{DECLIB} directory.
25423
25424 The GNAT RTL is contained in
25425 the @file{ADALIB} directory, and
25426 the default search path is set up to find @code{DECLIB} units in preference
25427 to @code{ADALIB} units with the same name (@code{TEXT_IO},
25428 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
25429
25430 @menu
25431 * Changes to DECLIB::
25432 @end menu
25433
25434 @node Changes to DECLIB
25435 @subsection Changes to @code{DECLIB}
25436
25437 @noindent
25438 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
25439 compatibility are minor and include the following:
25440
25441 @itemize @bullet
25442 @item  Adjusting the location of pragmas and record representation
25443 clauses to obey Ada 95 (and thus Ada 2005) rules
25444
25445 @item  Adding the proper notation to generic formal parameters
25446 that take unconstrained types in instantiation
25447
25448 @item  Adding pragma @code{ELABORATE_BODY} to package specs
25449 that have package bodies not otherwise allowed
25450
25451 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
25452 ``@code{PROTECTD}''.
25453 Currently these are found only in the @code{STARLET} package spec.
25454
25455 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
25456 where the address size is constrained to 32 bits.
25457 @end itemize
25458
25459 @noindent
25460 None of the above changes is visible to users.
25461
25462 @node Bindings
25463 @section Bindings
25464
25465 @noindent
25466 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
25467 @itemize @bullet
25468
25469 @item  Command Language Interpreter (CLI interface)
25470
25471 @item  DECtalk Run-Time Library (DTK interface)
25472
25473 @item  Librarian utility routines (LBR interface)
25474
25475 @item  General Purpose Run-Time Library (LIB interface)
25476
25477 @item  Math Run-Time Library (MTH interface)
25478
25479 @item  National Character Set Run-Time Library (NCS interface)
25480
25481 @item  Compiled Code Support Run-Time Library (OTS interface)
25482
25483 @item  Parallel Processing Run-Time Library (PPL interface)
25484
25485 @item  Screen Management Run-Time Library (SMG interface)
25486
25487 @item  Sort Run-Time Library (SOR interface)
25488
25489 @item  String Run-Time Library (STR interface)
25490
25491 @item STARLET System Library
25492 @findex Starlet
25493
25494 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
25495
25496 @item  X Windows Toolkit (XT interface)
25497
25498 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
25499 @end itemize
25500
25501 @noindent
25502 GNAT provides implementations of these HP bindings in the @code{DECLIB}
25503 directory, on both the Alpha and I64 OpenVMS platforms.
25504
25505 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
25506 in the
25507 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
25508 A pragma @code{Linker_Options} has been added to packages @code{Xm},
25509 @code{Xt}, and @code{X_Lib}
25510 causing the default X/Motif sharable image libraries to be linked in. This
25511 is done via options files named @file{xm.opt}, @file{xt.opt}, and
25512 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
25513
25514 It may be necessary to edit these options files to update or correct the
25515 library names if, for example, the newer X/Motif bindings from
25516 @file{ADA$EXAMPLES}
25517 had been (previous to installing GNAT) copied and renamed to supersede the
25518 default @file{ADA$PREDEFINED} versions.
25519
25520 @menu
25521 * Shared Libraries and Options Files::
25522 * Interfaces to C::
25523 @end menu
25524
25525 @node Shared Libraries and Options Files
25526 @subsection Shared Libraries and Options Files
25527
25528 @noindent
25529 When using the HP Ada
25530 predefined X and Motif bindings, the linking with their sharable images is
25531 done automatically by @command{GNAT LINK}.
25532 When using other X and Motif bindings, you need
25533 to add the corresponding sharable images to the command line for
25534 @code{GNAT LINK}. When linking with shared libraries, or with
25535 @file{.OPT} files, you must
25536 also add them to the command line for @command{GNAT LINK}.
25537
25538 A shared library to be used with GNAT is built in the same way as other
25539 libraries under VMS. The VMS Link command can be used in standard fashion.
25540
25541 @node Interfaces to C
25542 @subsection Interfaces to C
25543
25544 @noindent
25545 HP Ada
25546 provides the following Ada types and operations:
25547
25548 @itemize @bullet
25549 @item C types package (@code{C_TYPES})
25550
25551 @item C strings (@code{C_TYPES.NULL_TERMINATED})
25552
25553 @item Other_types (@code{SHORT_INT})
25554 @end itemize
25555
25556 @noindent
25557 Interfacing to C with GNAT, you can use the above approach
25558 described for HP Ada or the facilities of Annex B of
25559 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
25560 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
25561 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
25562
25563 The @option{-gnatF} qualifier forces default and explicit
25564 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
25565 to be uppercased for compatibility with the default behavior
25566 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
25567
25568 @node Main Program Definition
25569 @section Main Program Definition
25570
25571 @noindent
25572 The following section discusses differences in the
25573 definition of main programs on HP Ada and GNAT.
25574 On HP Ada, main programs are defined to meet the
25575 following conditions:
25576 @itemize @bullet
25577 @item  Procedure with no formal parameters (returns @code{0} upon
25578 normal completion)
25579
25580 @item  Procedure with no formal parameters (returns @code{42} when
25581 an unhandled exception is raised)
25582
25583 @item  Function with no formal parameters whose returned value
25584 is of a discrete type
25585
25586 @item  Procedure with one @code{out} formal of a discrete type for
25587 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
25588
25589 @end itemize
25590
25591 @noindent
25592 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
25593 a main function or main procedure returns a discrete
25594 value whose size is less than 64 bits (32 on VAX systems),
25595 the value is zero- or sign-extended as appropriate.
25596 On GNAT, main programs are defined as follows:
25597 @itemize @bullet
25598 @item  Must be a non-generic, parameterless subprogram that
25599 is either a procedure or function returning an Ada
25600 @code{STANDARD.INTEGER} (the predefined type)
25601
25602 @item  Cannot be a generic subprogram or an instantiation of a
25603 generic subprogram
25604 @end itemize
25605
25606 @node Implementation-Defined Attributes
25607 @section Implementation-Defined Attributes
25608
25609 @noindent
25610 GNAT provides all HP Ada implementation-defined
25611 attributes.
25612
25613 @node Compiler and Run-Time Interfacing
25614 @section Compiler and Run-Time Interfacing
25615
25616 @noindent
25617 HP Ada provides the following qualifiers to pass options to the linker
25618 (ACS LINK):
25619 @itemize @bullet
25620 @item  @option{/WAIT} and @option{/SUBMIT}
25621
25622 @item  @option{/COMMAND}
25623
25624 @item  @option{/@r{[}NO@r{]}MAP}
25625
25626 @item  @option{/OUTPUT=@var{file-spec}}
25627
25628 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25629 @end itemize
25630
25631 @noindent
25632 To pass options to the linker, GNAT provides the following
25633 switches:
25634
25635 @itemize @bullet
25636 @item   @option{/EXECUTABLE=@var{exec-name}}
25637
25638 @item   @option{/VERBOSE}
25639
25640 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25641 @end itemize
25642
25643 @noindent
25644 For more information on these switches, see
25645 @ref{Switches for gnatlink}.
25646 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
25647 to control optimization. HP Ada also supplies the
25648 following pragmas:
25649 @itemize @bullet
25650 @item  @code{OPTIMIZE}
25651
25652 @item  @code{INLINE}
25653
25654 @item  @code{INLINE_GENERIC}
25655
25656 @item  @code{SUPPRESS_ALL}
25657
25658 @item  @code{PASSIVE}
25659 @end itemize
25660
25661 @noindent
25662 In GNAT, optimization is controlled strictly by command
25663 line parameters, as described in the corresponding section of this guide.
25664 The HP pragmas for control of optimization are
25665 recognized but ignored.
25666
25667 Note that in GNAT, the default is optimization off, whereas in HP Ada
25668 the default is that optimization is turned on.
25669
25670 @node Program Compilation and Library Management
25671 @section Program Compilation and Library Management
25672
25673 @noindent
25674 HP Ada and GNAT provide a comparable set of commands to
25675 build programs. HP Ada also provides a program library,
25676 which is a concept that does not exist on GNAT. Instead,
25677 GNAT provides directories of sources that are compiled as
25678 needed.
25679
25680 The following table summarizes
25681 the HP Ada commands and provides
25682 equivalent GNAT commands. In this table, some GNAT
25683 equivalents reflect the fact that GNAT does not use the
25684 concept of a program library. Instead, it uses a model
25685 in which collections of source and object files are used
25686 in a manner consistent with other languages like C and
25687 Fortran. Therefore, standard system file commands are used
25688 to manipulate these elements. Those GNAT commands are marked with
25689 an asterisk.
25690 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
25691
25692 @need 1500
25693 @multitable @columnfractions .35 .65
25694
25695 @item @emph{HP Ada Command}
25696 @tab @emph{GNAT Equivalent / Description}
25697
25698 @item @command{ADA}
25699 @tab @command{GNAT COMPILE}@*
25700 Invokes the compiler to compile one or more Ada source files.
25701
25702 @item @command{ACS ATTACH}@*
25703 @tab [No equivalent]@*
25704 Switches control of terminal from current process running the program
25705 library manager.
25706
25707 @item @command{ACS CHECK}
25708 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
25709 Forms the execution closure of one
25710 or more compiled units and checks completeness and currency.
25711
25712 @item @command{ACS COMPILE}
25713 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25714 Forms the execution closure of one or
25715 more specified units, checks completeness and currency,
25716 identifies units that have revised source files, compiles same,
25717 and recompiles units that are or will become obsolete.
25718 Also completes incomplete generic instantiations.
25719
25720 @item @command{ACS COPY FOREIGN}
25721 @tab Copy (*)@*
25722 Copies a foreign object file into the program library as a
25723 library unit body.
25724
25725 @item @command{ACS COPY UNIT}
25726 @tab Copy (*)@*
25727 Copies a compiled unit from one program library to another.
25728
25729 @item @command{ACS CREATE LIBRARY}
25730 @tab Create /directory (*)@*
25731 Creates a program library.
25732
25733 @item @command{ACS CREATE SUBLIBRARY}
25734 @tab Create /directory (*)@*
25735 Creates a program sublibrary.
25736
25737 @item @command{ACS DELETE LIBRARY}
25738 @tab @*
25739 Deletes a program library and its contents.
25740
25741 @item @command{ACS DELETE SUBLIBRARY}
25742 @tab @*
25743 Deletes a program sublibrary and its contents.
25744
25745 @item @command{ACS DELETE UNIT}
25746 @tab Delete file (*)@*
25747 On OpenVMS systems, deletes one or more compiled units from
25748 the current program library.
25749
25750 @item @command{ACS DIRECTORY}
25751 @tab Directory (*)@*
25752 On OpenVMS systems, lists units contained in the current
25753 program library.
25754
25755 @item @command{ACS ENTER FOREIGN}
25756 @tab Copy (*)@*
25757 Allows the import of a foreign body as an Ada library
25758 spec and enters a reference to a pointer.
25759
25760 @item @command{ACS ENTER UNIT}
25761 @tab Copy (*)@*
25762 Enters a reference (pointer) from the current program library to
25763 a unit compiled into another program library.
25764
25765 @item @command{ACS EXIT}
25766 @tab [No equivalent]@*
25767 Exits from the program library manager.
25768
25769 @item @command{ACS EXPORT}
25770 @tab Copy (*)@*
25771 Creates an object file that contains system-specific object code
25772 for one or more units. With GNAT, object files can simply be copied
25773 into the desired directory.
25774
25775 @item @command{ACS EXTRACT SOURCE}
25776 @tab Copy (*)@*
25777 Allows access to the copied source file for each Ada compilation unit
25778
25779 @item @command{ACS HELP}
25780 @tab @command{HELP GNAT}@*
25781 Provides online help.
25782
25783 @item @command{ACS LINK}
25784 @tab @command{GNAT LINK}@*
25785 Links an object file containing Ada units into an executable file.
25786
25787 @item @command{ACS LOAD}
25788 @tab Copy (*)@*
25789 Loads (partially compiles) Ada units into the program library.
25790 Allows loading a program from a collection of files into a library
25791 without knowing the relationship among units.
25792
25793 @item @command{ACS MERGE}
25794 @tab Copy (*)@*
25795 Merges into the current program library, one or more units from
25796 another library where they were modified.
25797
25798 @item @command{ACS RECOMPILE}
25799 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25800 Recompiles from   external or copied source files any obsolete
25801 unit in the closure. Also, completes any incomplete generic
25802 instantiations.
25803
25804 @item @command{ACS REENTER}
25805 @tab @command{GNAT MAKE}@*
25806 Reenters current references to units compiled after last entered
25807 with the @command{ACS ENTER UNIT} command.
25808
25809 @item @command{ACS SET LIBRARY}
25810 @tab Set default (*)@*
25811 Defines a program library to be the compilation context as well
25812 as the target library for compiler output and commands in general.
25813
25814 @item @command{ACS SET PRAGMA}
25815 @tab Edit @file{gnat.adc} (*)@*
25816 Redefines specified  values of the library characteristics
25817 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
25818 and @code{Float_Representation}.
25819
25820 @item @command{ACS SET SOURCE}
25821 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
25822 Defines the source file search list for the @command{ACS COMPILE} command.
25823
25824 @item @command{ACS SHOW LIBRARY}
25825 @tab Directory (*)@*
25826 Lists information about one or more program libraries.
25827
25828 @item @command{ACS SHOW PROGRAM}
25829 @tab [No equivalent]@*
25830 Lists information about the execution closure of one or
25831 more units in the program library.
25832
25833 @item @command{ACS SHOW SOURCE}
25834 @tab Show logical @code{ADA_INCLUDE_PATH}@*
25835 Shows the source file search used when compiling units.
25836
25837 @item @command{ACS SHOW VERSION}
25838 @tab Compile with @option{VERBOSE} option
25839 Displays the version number of the compiler and program library
25840 manager used.
25841
25842 @item @command{ACS SPAWN}
25843 @tab [No equivalent]@*
25844 Creates a subprocess of the current process (same as @command{DCL SPAWN}
25845 command).
25846
25847 @item @command{ACS VERIFY}
25848 @tab [No equivalent]@*
25849 Performs a series of consistency checks on a program library to
25850 determine whether the library structure and library files are in
25851 valid form.
25852 @end multitable
25853
25854 @noindent
25855
25856 @node Input-Output
25857 @section Input-Output
25858
25859 @noindent
25860 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
25861 Management Services (RMS) to perform operations on
25862 external files.
25863
25864 @noindent
25865 HP Ada and GNAT predefine an identical set of input-
25866 output packages. To make the use of the
25867 generic @code{TEXT_IO} operations more convenient, HP Ada
25868 provides predefined library packages that instantiate the
25869 integer and floating-point operations for the predefined
25870 integer and floating-point types as shown in the following table.
25871
25872 @multitable @columnfractions .45 .55
25873 @item @emph{Package Name} @tab Instantiation
25874
25875 @item @code{INTEGER_TEXT_IO}
25876 @tab @code{INTEGER_IO(INTEGER)}
25877
25878 @item @code{SHORT_INTEGER_TEXT_IO}
25879 @tab @code{INTEGER_IO(SHORT_INTEGER)}
25880
25881 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
25882 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
25883
25884 @item @code{FLOAT_TEXT_IO}
25885 @tab @code{FLOAT_IO(FLOAT)}
25886
25887 @item @code{LONG_FLOAT_TEXT_IO}
25888 @tab @code{FLOAT_IO(LONG_FLOAT)}
25889 @end multitable
25890
25891 @noindent
25892 The HP Ada predefined packages and their operations
25893 are implemented using OpenVMS Alpha files and input-output
25894 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
25895 Familiarity with the following is recommended:
25896 @itemize @bullet
25897 @item  RMS file organizations and access methods
25898
25899 @item  OpenVMS file specifications and directories
25900
25901 @item  OpenVMS File Definition Language (FDL)
25902 @end itemize
25903
25904 @noindent
25905 GNAT provides I/O facilities that are completely
25906 compatible with HP Ada. The distribution includes the
25907 standard HP Ada versions of all I/O packages, operating
25908 in a manner compatible with HP Ada. In particular, the
25909 following packages are by default the HP Ada (Ada 83)
25910 versions of these packages rather than the renamings
25911 suggested in Annex J of the Ada Reference Manual:
25912 @itemize @bullet
25913 @item  @code{TEXT_IO}
25914
25915 @item  @code{SEQUENTIAL_IO}
25916
25917 @item  @code{DIRECT_IO}
25918 @end itemize
25919
25920 @noindent
25921 The use of the standard child package syntax (for
25922 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
25923 packages.
25924 GNAT provides HP-compatible predefined instantiations
25925 of the @code{TEXT_IO} packages, and also
25926 provides the standard predefined instantiations required
25927 by the @cite{Ada Reference Manual}.
25928
25929 For further information on how GNAT interfaces to the file
25930 system or how I/O is implemented in programs written in
25931 mixed languages, see @ref{Implementation of the Standard I/O,,,
25932 gnat_rm, GNAT Reference Manual}.
25933 This chapter covers the following:
25934 @itemize @bullet
25935 @item  Standard I/O packages
25936
25937 @item  @code{FORM} strings
25938
25939 @item  @code{ADA.DIRECT_IO}
25940
25941 @item  @code{ADA.SEQUENTIAL_IO}
25942
25943 @item  @code{ADA.TEXT_IO}
25944
25945 @item  Stream pointer positioning
25946
25947 @item  Reading and writing non-regular files
25948
25949 @item  @code{GET_IMMEDIATE}
25950
25951 @item  Treating @code{TEXT_IO} files as streams
25952
25953 @item  Shared files
25954
25955 @item  Open modes
25956 @end itemize
25957
25958 @node Implementation Limits
25959 @section Implementation Limits
25960
25961 @noindent
25962 The following table lists implementation limits for HP Ada
25963 and GNAT systems.
25964 @multitable @columnfractions .60 .20 .20
25965 @sp 1
25966 @item  @emph{Compilation Parameter}
25967 @tab   @emph{HP Ada}
25968 @tab   @emph{GNAT}
25969 @sp 1
25970
25971 @item  In a subprogram or entry  declaration, maximum number of
25972 formal parameters that are of an unconstrained record type
25973 @tab   32
25974 @tab   No set limit
25975 @sp 1
25976
25977 @item  Maximum identifier length (number of characters)
25978 @tab   255
25979 @tab   32766
25980 @sp 1
25981
25982 @item  Maximum number of characters in a source line
25983 @tab   255
25984 @tab   32766
25985 @sp 1
25986
25987 @item  Maximum collection size   (number of bytes)
25988 @tab   2**31-1
25989 @tab   2**31-1
25990 @sp 1
25991
25992 @item  Maximum number of discriminants for a record type
25993 @tab   245
25994 @tab   No set limit
25995 @sp 1
25996
25997 @item  Maximum number of formal parameters in an entry or
25998 subprogram declaration
25999 @tab   246
26000 @tab    No set limit
26001 @sp 1
26002
26003 @item  Maximum number of dimensions in an array type
26004 @tab   255
26005 @tab   No set limit
26006 @sp 1
26007
26008 @item  Maximum number of library  units and subunits in a compilation.
26009 @tab   4095
26010 @tab   No set limit
26011 @sp 1
26012
26013 @item  Maximum number of library units and subunits in an execution.
26014 @tab   16383
26015 @tab   No set limit
26016 @sp 1
26017
26018 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
26019 or @code{PSECT_OBJECT}
26020 @tab   32757
26021 @tab   No set limit
26022 @sp 1
26023
26024 @item  Maximum number of enumeration literals in an enumeration type
26025 definition
26026 @tab   65535
26027 @tab   No set limit
26028 @sp 1
26029
26030 @item  Maximum number of lines in a source file
26031 @tab   65534
26032 @tab   No set limit
26033 @sp 1
26034
26035 @item  Maximum number of bits in any object
26036 @tab   2**31-1
26037 @tab   2**31-1
26038 @sp 1
26039
26040 @item  Maximum size of the static portion of a stack frame (approximate)
26041 @tab   2**31-1
26042 @tab   2**31-1
26043 @end multitable
26044
26045 @node Tools and Utilities
26046 @section Tools and Utilities
26047
26048 @noindent
26049 The following table lists some of the OpenVMS development tools
26050 available for HP Ada, and the corresponding tools for
26051 use with @value{EDITION} on Alpha and I64 platforms.
26052 Aside from the debugger, all the OpenVMS tools identified are part
26053 of the DECset package.
26054
26055 @iftex
26056 @c Specify table in TeX since Texinfo does a poor job
26057 @tex
26058 \smallskip
26059 \smallskip
26060 \settabs\+Language-Sensitive Editor\quad
26061    &Product with HP Ada\quad
26062    &\cr
26063 \+\it Tool
26064    &\it Product with HP Ada
26065    & \it Product with GNAT Pro\cr
26066 \smallskip
26067 \+Code Management System
26068    &HP CMS
26069    & HP CMS\cr
26070 \smallskip
26071 \+Language-Sensitive Editor
26072    &HP LSE
26073    & emacs or HP LSE (Alpha)\cr
26074 \+
26075    &
26076    & HP LSE (I64)\cr
26077 \smallskip
26078 \+Debugger
26079    &OpenVMS Debug
26080    & gdb (Alpha),\cr
26081 \+
26082    &
26083    & OpenVMS Debug (I64)\cr
26084 \smallskip
26085 \+Source Code Analyzer /
26086    &HP SCA
26087    & GNAT XREF\cr
26088 \+Cross Referencer
26089    &
26090    &\cr
26091 \smallskip
26092 \+Test Manager
26093    &HP Digital Test
26094    & HP DTM\cr
26095 \+
26096    &Manager (DTM)
26097    &\cr
26098 \smallskip
26099 \+Performance and
26100    & HP PCA
26101    & HP PCA\cr
26102 \+Coverage Analyzer
26103    &
26104    &\cr
26105 \smallskip
26106 \+Module Management
26107    & HP MMS
26108    & Not applicable\cr
26109 \+ System
26110    &
26111    &\cr
26112 \smallskip
26113 \smallskip
26114 @end tex
26115 @end iftex
26116
26117 @ifnottex
26118 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
26119 @c the TeX version above for the printed version
26120 @flushleft
26121 @c @multitable @columnfractions .3 .4 .4
26122 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
26123 @item @i{Tool}
26124 @tab @i{Tool with HP Ada}
26125 @tab @i{Tool with @value{EDITION}}
26126 @item Code Management@*System
26127 @tab HP CMS
26128 @tab HP CMS
26129 @item Language-Sensitive@*Editor
26130 @tab HP LSE
26131 @tab emacs or HP LSE (Alpha)
26132 @item
26133 @tab
26134 @tab HP LSE (I64)
26135 @item Debugger
26136 @tab OpenVMS Debug
26137 @tab gdb (Alpha),
26138 @item
26139 @tab
26140 @tab OpenVMS Debug (I64)
26141 @item Source Code Analyzer /@*Cross Referencer
26142 @tab HP SCA
26143 @tab GNAT XREF
26144 @item Test Manager
26145 @tab HP Digital Test@*Manager (DTM)
26146 @tab HP DTM
26147 @item Performance and@*Coverage Analyzer
26148 @tab HP PCA
26149 @tab HP PCA
26150 @item Module Management@*System
26151 @tab HP MMS
26152 @tab Not applicable
26153 @end multitable
26154 @end flushleft
26155 @end ifnottex
26156
26157 @end ifset
26158
26159 @c **************************************
26160 @node Platform-Specific Information for the Run-Time Libraries
26161 @appendix Platform-Specific Information for the Run-Time Libraries
26162 @cindex Tasking and threads libraries
26163 @cindex Threads libraries and tasking
26164 @cindex Run-time libraries (platform-specific information)
26165
26166 @noindent
26167 The GNAT run-time implementation may vary with respect to both the
26168 underlying threads library and the exception handling scheme.
26169 For threads support, one or more of the following are supplied:
26170 @itemize @bullet
26171 @item @b{native threads library}, a binding to the thread package from
26172 the underlying operating system
26173
26174 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
26175 POSIX thread package
26176 @end itemize
26177
26178 @noindent
26179 For exception handling, either or both of two models are supplied:
26180 @itemize @bullet
26181 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
26182 Most programs should experience a substantial speed improvement by
26183 being compiled with a ZCX run-time.
26184 This is especially true for
26185 tasking applications or applications with many exception handlers.}
26186 @cindex Zero-Cost Exceptions
26187 @cindex ZCX (Zero-Cost Exceptions)
26188 which uses binder-generated tables that
26189 are interrogated at run time to locate a handler
26190
26191 @item @b{setjmp / longjmp} (``SJLJ''),
26192 @cindex setjmp/longjmp Exception Model
26193 @cindex SJLJ (setjmp/longjmp Exception Model)
26194 which uses dynamically-set data to establish
26195 the set of handlers
26196 @end itemize
26197
26198 @noindent
26199 This appendix summarizes which combinations of threads and exception support
26200 are supplied on various GNAT platforms.
26201 It then shows how to select a particular library either
26202 permanently or temporarily,
26203 explains the properties of (and tradeoffs among) the various threads
26204 libraries, and provides some additional
26205 information about several specific platforms.
26206
26207 @menu
26208 * Summary of Run-Time Configurations::
26209 * Specifying a Run-Time Library::
26210 * Choosing the Scheduling Policy::
26211 * Solaris-Specific Considerations::
26212 * Linux-Specific Considerations::
26213 * AIX-Specific Considerations::
26214 * Irix-Specific Considerations::
26215 * RTX-Specific Considerations::
26216 @end menu
26217
26218 @node Summary of Run-Time Configurations
26219 @section Summary of Run-Time Configurations
26220
26221 @multitable @columnfractions .30 .70
26222 @item @b{alpha-openvms}
26223 @item @code{@ @ }@i{rts-native (default)}
26224 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26225 @item @code{@ @ @ @ }Exceptions @tab ZCX
26226 @*
26227 @item @b{alpha-tru64}
26228 @item @code{@ @ }@i{rts-native (default)}
26229 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26230 @item @code{@ @ @ @ }Exceptions @tab ZCX
26231 @*
26232 @item @code{@ @ }@i{rts-sjlj}
26233 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26234 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26235 @*
26236 @item @b{ia64-hp_linux}
26237 @item @code{@ @ }@i{rts-native (default)}
26238 @item @code{@ @ @ @ }Tasking    @tab pthread library
26239 @item @code{@ @ @ @ }Exceptions @tab ZCX
26240 @*
26241 @item @b{ia64-hpux}
26242 @item @code{@ @ }@i{rts-native (default)}
26243 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26244 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26245 @*
26246 @item @b{ia64-openvms}
26247 @item @code{@ @ }@i{rts-native (default)}
26248 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26249 @item @code{@ @ @ @ }Exceptions @tab ZCX
26250 @*
26251 @item @b{ia64-sgi_linux}
26252 @item @code{@ @ }@i{rts-native (default)}
26253 @item @code{@ @ @ @ }Tasking    @tab pthread library
26254 @item @code{@ @ @ @ }Exceptions @tab ZCX
26255 @*
26256 @item @b{mips-irix}
26257 @item @code{@ @ }@i{rts-native (default)}
26258 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
26259 @item @code{@ @ @ @ }Exceptions @tab ZCX
26260 @*
26261 @item @b{pa-hpux}
26262 @item @code{@ @ }@i{rts-native (default)}
26263 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26264 @item @code{@ @ @ @ }Exceptions @tab ZCX
26265 @*
26266 @item @code{@ @ }@i{rts-sjlj}
26267 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26268 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26269 @*
26270 @item @b{ppc-aix}
26271 @item @code{@ @ }@i{rts-native (default)}
26272 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
26273 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26274 @*
26275 @item @b{ppc-darwin}
26276 @item @code{@ @ }@i{rts-native (default)}
26277 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
26278 @item @code{@ @ @ @ }Exceptions @tab ZCX
26279 @*
26280 @item @b{sparc-solaris}  @tab
26281 @item @code{@ @ }@i{rts-native (default)}
26282 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26283 @item @code{@ @ @ @ }Exceptions @tab ZCX
26284 @*
26285 @item @code{@ @ }@i{rts-pthread}
26286 @item @code{@ @ @ @ }Tasking    @tab pthread library
26287 @item @code{@ @ @ @ }Exceptions @tab ZCX
26288 @*
26289 @item @code{@ @ }@i{rts-sjlj}
26290 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26291 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26292 @*
26293 @item @b{sparc64-solaris}  @tab
26294 @item @code{@ @ }@i{rts-native (default)}
26295 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26296 @item @code{@ @ @ @ }Exceptions @tab ZCX
26297 @*
26298 @item @b{x86-linux}
26299 @item @code{@ @ }@i{rts-native (default)}
26300 @item @code{@ @ @ @ }Tasking    @tab pthread library
26301 @item @code{@ @ @ @ }Exceptions @tab ZCX
26302 @*
26303 @item @code{@ @ }@i{rts-sjlj}
26304 @item @code{@ @ @ @ }Tasking    @tab pthread library
26305 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26306 @*
26307 @item @b{x86-lynx}
26308 @item @code{@ @ }@i{rts-native (default)}
26309 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
26310 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26311 @*
26312 @item @b{x86-solaris}
26313 @item @code{@ @ }@i{rts-native (default)}
26314 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
26315 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26316 @*
26317 @item @b{x86-windows}
26318 @item @code{@ @ }@i{rts-native (default)}
26319 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
26320 @item @code{@ @ @ @ }Exceptions @tab ZCX
26321 @*
26322 @item @code{@ @ }@i{rts-sjlj (default)}
26323 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
26324 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26325 @*
26326 @item @b{x86-windows-rtx}
26327 @item @code{@ @ }@i{rts-rtx-rtss (default)}
26328 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
26329 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26330 @*
26331 @item @code{@ @ }@i{rts-rtx-w32}
26332 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
26333 @item @code{@ @ @ @ }Exceptions @tab ZCX
26334 @*
26335 @item @b{x86_64-linux}
26336 @item @code{@ @ }@i{rts-native (default)}
26337 @item @code{@ @ @ @ }Tasking    @tab pthread library
26338 @item @code{@ @ @ @ }Exceptions @tab ZCX
26339 @*
26340 @item @code{@ @ }@i{rts-sjlj}
26341 @item @code{@ @ @ @ }Tasking    @tab pthread library
26342 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26343 @*
26344 @end multitable
26345
26346 @node Specifying a Run-Time Library
26347 @section Specifying a Run-Time Library
26348
26349 @noindent
26350 The @file{adainclude} subdirectory containing the sources of the GNAT
26351 run-time library, and the @file{adalib} subdirectory containing the
26352 @file{ALI} files and the static and/or shared GNAT library, are located
26353 in the gcc target-dependent area:
26354
26355 @smallexample
26356 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
26357 @end smallexample
26358
26359 @noindent
26360 As indicated above, on some platforms several run-time libraries are supplied.
26361 These libraries are installed in the target dependent area and
26362 contain a complete source and binary subdirectory. The detailed description
26363 below explains the differences between the different libraries in terms of
26364 their thread support.
26365
26366 The default run-time library (when GNAT is installed) is @emph{rts-native}.
26367 This default run time is selected by the means of soft links.
26368 For example on x86-linux:
26369
26370 @smallexample
26371 @group
26372  $(target-dir)
26373      |
26374      +--- adainclude----------+
26375      |                        |
26376      +--- adalib-----------+  |
26377      |                     |  |
26378      +--- rts-native       |  |
26379      |    |                |  |
26380      |    +--- adainclude <---+
26381      |    |                |
26382      |    +--- adalib <----+
26383      |
26384      +--- rts-sjlj
26385           |
26386           +--- adainclude
26387           |
26388           +--- adalib
26389 @end group
26390 @end smallexample
26391
26392 @noindent
26393 If the @i{rts-sjlj} library is to be selected on a permanent basis,
26394 these soft links can be modified with the following commands:
26395
26396 @smallexample
26397 $ cd $target
26398 $ rm -f adainclude adalib
26399 $ ln -s rts-sjlj/adainclude adainclude
26400 $ ln -s rts-sjlj/adalib adalib
26401 @end smallexample
26402
26403 @noindent
26404 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
26405 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
26406 @file{$target/ada_object_path}.
26407
26408 Selecting another run-time library temporarily can be
26409 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
26410 @cindex @option{--RTS} option
26411
26412 @node Choosing the Scheduling Policy
26413 @section Choosing the Scheduling Policy
26414
26415 @noindent
26416 When using a POSIX threads implementation, you have a choice of several
26417 scheduling policies: @code{SCHED_FIFO},
26418 @cindex @code{SCHED_FIFO} scheduling policy
26419 @code{SCHED_RR}
26420 @cindex @code{SCHED_RR} scheduling policy
26421 and @code{SCHED_OTHER}.
26422 @cindex @code{SCHED_OTHER} scheduling policy
26423 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
26424 or @code{SCHED_RR} requires special (e.g., root) privileges.
26425
26426 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
26427 @code{SCHED_FIFO},
26428 @cindex @code{SCHED_FIFO} scheduling policy
26429 you can use one of the following:
26430
26431 @itemize @bullet
26432 @item
26433 @code{pragma Time_Slice (0.0)}
26434 @cindex pragma Time_Slice
26435 @item
26436 the corresponding binder option @option{-T0}
26437 @cindex @option{-T0} option
26438 @item
26439 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
26440 @cindex pragma Task_Dispatching_Policy
26441 @end itemize
26442
26443 @noindent
26444 To specify @code{SCHED_RR},
26445 @cindex @code{SCHED_RR} scheduling policy
26446 you should use @code{pragma Time_Slice} with a
26447 value greater than @code{0.0}, or else use the corresponding @option{-T}
26448 binder option.
26449
26450 @node Solaris-Specific Considerations
26451 @section Solaris-Specific Considerations
26452 @cindex Solaris Sparc threads libraries
26453
26454 @noindent
26455 This section addresses some topics related to the various threads libraries
26456 on Sparc Solaris.
26457
26458 @menu
26459 * Solaris Threads Issues::
26460 @end menu
26461
26462 @node Solaris Threads Issues
26463 @subsection Solaris Threads Issues
26464
26465 @noindent
26466 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
26467 library based on POSIX threads --- @emph{rts-pthread}.
26468 @cindex rts-pthread threads library
26469 This run-time library has the advantage of being mostly shared across all
26470 POSIX-compliant thread implementations, and it also provides under
26471 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
26472 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
26473 and @code{PTHREAD_PRIO_PROTECT}
26474 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
26475 semantics that can be selected using the predefined pragma
26476 @code{Locking_Policy}
26477 @cindex pragma Locking_Policy (under rts-pthread)
26478 with respectively
26479 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
26480 @cindex @code{Inheritance_Locking} (under rts-pthread)
26481 @cindex @code{Ceiling_Locking} (under rts-pthread)
26482
26483 As explained above, the native run-time library is based on the Solaris thread
26484 library (@code{libthread}) and is the default library.
26485
26486 When the Solaris threads library is used (this is the default), programs
26487 compiled with GNAT can automatically take advantage of
26488 and can thus execute on multiple processors.
26489 The user can alternatively specify a processor on which the program should run
26490 to emulate a single-processor system. The multiprocessor / uniprocessor choice
26491 is made by
26492 setting the environment variable @env{GNAT_PROCESSOR}
26493 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
26494 to one of the following:
26495
26496 @table @code
26497 @item -2
26498 Use the default configuration (run the program on all
26499 available processors) - this is the same as having @code{GNAT_PROCESSOR}
26500 unset
26501
26502 @item -1
26503 Let the run-time implementation choose one processor and run the program on
26504 that processor
26505
26506 @item 0 .. Last_Proc
26507 Run the program on the specified processor.
26508 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
26509 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
26510 @end table
26511
26512 @node Linux-Specific Considerations
26513 @section Linux-Specific Considerations
26514 @cindex Linux threads libraries
26515
26516 @noindent
26517 On GNU/Linux without NPTL support (usually system with GNU C Library
26518 older than 2.3), the signal model is not POSIX compliant, which means
26519 that to send a signal to the process, you need to send the signal to all
26520 threads, e.g.@: by using @code{killpg()}.
26521
26522 @node AIX-Specific Considerations
26523 @section AIX-Specific Considerations
26524 @cindex AIX resolver library
26525
26526 @noindent
26527 On AIX, the resolver library initializes some internal structure on
26528 the first call to @code{get*by*} functions, which are used to implement
26529 @code{GNAT.Sockets.Get_Host_By_Name} and
26530 @code{GNAT.Sockets.Get_Host_By_Address}.
26531 If such initialization occurs within an Ada task, and the stack size for
26532 the task is the default size, a stack overflow may occur.
26533
26534 To avoid this overflow, the user should either ensure that the first call
26535 to @code{GNAT.Sockets.Get_Host_By_Name} or
26536 @code{GNAT.Sockets.Get_Host_By_Addrss}
26537 occurs in the environment task, or use @code{pragma Storage_Size} to
26538 specify a sufficiently large size for the stack of the task that contains
26539 this call.
26540
26541 @node Irix-Specific Considerations
26542 @section Irix-Specific Considerations
26543 @cindex Irix libraries
26544
26545 @noindent
26546 The GCC support libraries coming with the Irix compiler have moved to
26547 their canonical place with respect to the general Irix ABI related
26548 conventions. Running applications built with the default shared GNAT
26549 run-time now requires the LD_LIBRARY_PATH environment variable to
26550 include this location. A possible way to achieve this is to issue the
26551 following command line on a bash prompt:
26552
26553 @smallexample
26554 @group
26555 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
26556 @end group
26557 @end smallexample
26558
26559 @node RTX-Specific Considerations
26560 @section RTX-Specific Considerations
26561 @cindex RTX libraries
26562
26563 @noindent
26564 The Real-time Extension (RTX) to Windows is based on the Windows Win32
26565 API. Applications can be built to work in two different modes:
26566
26567 @itemize @bullet
26568 @item
26569 Windows executables that run in Ring 3 to utilize memory protection
26570 (@emph{rts-rtx-w32}).
26571
26572 @item
26573 Real-time subsystem (RTSS) executables that run in Ring 0, where
26574 performance can be optimized with RTSS applications taking precedent
26575 over all Windows applications (@emph{rts-rtx-rtss}).
26576
26577 @end itemize
26578
26579 @c *******************************
26580 @node Example of Binder Output File
26581 @appendix Example of Binder Output File
26582
26583 @noindent
26584 This Appendix displays the source code for @command{gnatbind}'s output
26585 file generated for a simple ``Hello World'' program.
26586 Comments have been added for clarification purposes.
26587
26588 @smallexample @c adanocomment
26589 @iftex
26590 @leftskip=0cm
26591 @end iftex
26592 --  The package is called Ada_Main unless this name is actually used
26593 --  as a unit name in the partition, in which case some other unique
26594 --  name is used.
26595
26596 with System;
26597 package ada_main is
26598
26599    Elab_Final_Code : Integer;
26600    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
26601
26602    --  The main program saves the parameters (argument count,
26603    --  argument values, environment pointer) in global variables
26604    --  for later access by other units including
26605    --  Ada.Command_Line.
26606
26607    gnat_argc : Integer;
26608    gnat_argv : System.Address;
26609    gnat_envp : System.Address;
26610
26611    --  The actual variables are stored in a library routine. This
26612    --  is useful for some shared library situations, where there
26613    --  are problems if variables are not in the library.
26614
26615    pragma Import (C, gnat_argc);
26616    pragma Import (C, gnat_argv);
26617    pragma Import (C, gnat_envp);
26618
26619    --  The exit status is similarly an external location
26620
26621    gnat_exit_status : Integer;
26622    pragma Import (C, gnat_exit_status);
26623
26624    GNAT_Version : constant String :=
26625                     "GNAT Version: 6.0.0w (20061115)";
26626    pragma Export (C, GNAT_Version, "__gnat_version");
26627
26628    --  This is the generated adafinal routine that performs
26629    --  finalization at the end of execution. In the case where
26630    --  Ada is the main program, this main program makes a call
26631    --  to adafinal at program termination.
26632
26633    procedure adafinal;
26634    pragma Export (C, adafinal, "adafinal");
26635
26636    --  This is the generated adainit routine that performs
26637    --  initialization at the start of execution. In the case
26638    --  where Ada is the main program, this main program makes
26639    --  a call to adainit at program startup.
26640
26641    procedure adainit;
26642    pragma Export (C, adainit, "adainit");
26643
26644    --  This routine is called at the start of execution. It is
26645    --  a dummy routine that is used by the debugger to breakpoint
26646    --  at the start of execution.
26647
26648    procedure Break_Start;
26649    pragma Import (C, Break_Start, "__gnat_break_start");
26650
26651    --  This is the actual generated main program (it would be
26652    --  suppressed if the no main program switch were used). As
26653    --  required by standard system conventions, this program has
26654    --  the external name main.
26655
26656    function main
26657      (argc : Integer;
26658       argv : System.Address;
26659       envp : System.Address)
26660       return Integer;
26661    pragma Export (C, main, "main");
26662
26663    --  The following set of constants give the version
26664    --  identification values for every unit in the bound
26665    --  partition. This identification is computed from all
26666    --  dependent semantic units, and corresponds to the
26667    --  string that would be returned by use of the
26668    --  Body_Version or Version attributes.
26669
26670    type Version_32 is mod 2 ** 32;
26671    u00001 : constant Version_32 := 16#7880BEB3#;
26672    u00002 : constant Version_32 := 16#0D24CBD0#;
26673    u00003 : constant Version_32 := 16#3283DBEB#;
26674    u00004 : constant Version_32 := 16#2359F9ED#;
26675    u00005 : constant Version_32 := 16#664FB847#;
26676    u00006 : constant Version_32 := 16#68E803DF#;
26677    u00007 : constant Version_32 := 16#5572E604#;
26678    u00008 : constant Version_32 := 16#46B173D8#;
26679    u00009 : constant Version_32 := 16#156A40CF#;
26680    u00010 : constant Version_32 := 16#033DABE0#;
26681    u00011 : constant Version_32 := 16#6AB38FEA#;
26682    u00012 : constant Version_32 := 16#22B6217D#;
26683    u00013 : constant Version_32 := 16#68A22947#;
26684    u00014 : constant Version_32 := 16#18CC4A56#;
26685    u00015 : constant Version_32 := 16#08258E1B#;
26686    u00016 : constant Version_32 := 16#367D5222#;
26687    u00017 : constant Version_32 := 16#20C9ECA4#;
26688    u00018 : constant Version_32 := 16#50D32CB6#;
26689    u00019 : constant Version_32 := 16#39A8BB77#;
26690    u00020 : constant Version_32 := 16#5CF8FA2B#;
26691    u00021 : constant Version_32 := 16#2F1EB794#;
26692    u00022 : constant Version_32 := 16#31AB6444#;
26693    u00023 : constant Version_32 := 16#1574B6E9#;
26694    u00024 : constant Version_32 := 16#5109C189#;
26695    u00025 : constant Version_32 := 16#56D770CD#;
26696    u00026 : constant Version_32 := 16#02F9DE3D#;
26697    u00027 : constant Version_32 := 16#08AB6B2C#;
26698    u00028 : constant Version_32 := 16#3FA37670#;
26699    u00029 : constant Version_32 := 16#476457A0#;
26700    u00030 : constant Version_32 := 16#731E1B6E#;
26701    u00031 : constant Version_32 := 16#23C2E789#;
26702    u00032 : constant Version_32 := 16#0F1BD6A1#;
26703    u00033 : constant Version_32 := 16#7C25DE96#;
26704    u00034 : constant Version_32 := 16#39ADFFA2#;
26705    u00035 : constant Version_32 := 16#571DE3E7#;
26706    u00036 : constant Version_32 := 16#5EB646AB#;
26707    u00037 : constant Version_32 := 16#4249379B#;
26708    u00038 : constant Version_32 := 16#0357E00A#;
26709    u00039 : constant Version_32 := 16#3784FB72#;
26710    u00040 : constant Version_32 := 16#2E723019#;
26711    u00041 : constant Version_32 := 16#623358EA#;
26712    u00042 : constant Version_32 := 16#107F9465#;
26713    u00043 : constant Version_32 := 16#6843F68A#;
26714    u00044 : constant Version_32 := 16#63305874#;
26715    u00045 : constant Version_32 := 16#31E56CE1#;
26716    u00046 : constant Version_32 := 16#02917970#;
26717    u00047 : constant Version_32 := 16#6CCBA70E#;
26718    u00048 : constant Version_32 := 16#41CD4204#;
26719    u00049 : constant Version_32 := 16#572E3F58#;
26720    u00050 : constant Version_32 := 16#20729FF5#;
26721    u00051 : constant Version_32 := 16#1D4F93E8#;
26722    u00052 : constant Version_32 := 16#30B2EC3D#;
26723    u00053 : constant Version_32 := 16#34054F96#;
26724    u00054 : constant Version_32 := 16#5A199860#;
26725    u00055 : constant Version_32 := 16#0E7F912B#;
26726    u00056 : constant Version_32 := 16#5760634A#;
26727    u00057 : constant Version_32 := 16#5D851835#;
26728
26729    --  The following Export pragmas export the version numbers
26730    --  with symbolic names ending in B (for body) or S
26731    --  (for spec) so that they can be located in a link. The
26732    --  information provided here is sufficient to track down
26733    --  the exact versions of units used in a given build.
26734
26735    pragma Export (C, u00001, "helloB");
26736    pragma Export (C, u00002, "system__standard_libraryB");
26737    pragma Export (C, u00003, "system__standard_libraryS");
26738    pragma Export (C, u00004, "adaS");
26739    pragma Export (C, u00005, "ada__text_ioB");
26740    pragma Export (C, u00006, "ada__text_ioS");
26741    pragma Export (C, u00007, "ada__exceptionsB");
26742    pragma Export (C, u00008, "ada__exceptionsS");
26743    pragma Export (C, u00009, "gnatS");
26744    pragma Export (C, u00010, "gnat__heap_sort_aB");
26745    pragma Export (C, u00011, "gnat__heap_sort_aS");
26746    pragma Export (C, u00012, "systemS");
26747    pragma Export (C, u00013, "system__exception_tableB");
26748    pragma Export (C, u00014, "system__exception_tableS");
26749    pragma Export (C, u00015, "gnat__htableB");
26750    pragma Export (C, u00016, "gnat__htableS");
26751    pragma Export (C, u00017, "system__exceptionsS");
26752    pragma Export (C, u00018, "system__machine_state_operationsB");
26753    pragma Export (C, u00019, "system__machine_state_operationsS");
26754    pragma Export (C, u00020, "system__machine_codeS");
26755    pragma Export (C, u00021, "system__storage_elementsB");
26756    pragma Export (C, u00022, "system__storage_elementsS");
26757    pragma Export (C, u00023, "system__secondary_stackB");
26758    pragma Export (C, u00024, "system__secondary_stackS");
26759    pragma Export (C, u00025, "system__parametersB");
26760    pragma Export (C, u00026, "system__parametersS");
26761    pragma Export (C, u00027, "system__soft_linksB");
26762    pragma Export (C, u00028, "system__soft_linksS");
26763    pragma Export (C, u00029, "system__stack_checkingB");
26764    pragma Export (C, u00030, "system__stack_checkingS");
26765    pragma Export (C, u00031, "system__tracebackB");
26766    pragma Export (C, u00032, "system__tracebackS");
26767    pragma Export (C, u00033, "ada__streamsS");
26768    pragma Export (C, u00034, "ada__tagsB");
26769    pragma Export (C, u00035, "ada__tagsS");
26770    pragma Export (C, u00036, "system__string_opsB");
26771    pragma Export (C, u00037, "system__string_opsS");
26772    pragma Export (C, u00038, "interfacesS");
26773    pragma Export (C, u00039, "interfaces__c_streamsB");
26774    pragma Export (C, u00040, "interfaces__c_streamsS");
26775    pragma Export (C, u00041, "system__file_ioB");
26776    pragma Export (C, u00042, "system__file_ioS");
26777    pragma Export (C, u00043, "ada__finalizationB");
26778    pragma Export (C, u00044, "ada__finalizationS");
26779    pragma Export (C, u00045, "system__finalization_rootB");
26780    pragma Export (C, u00046, "system__finalization_rootS");
26781    pragma Export (C, u00047, "system__finalization_implementationB");
26782    pragma Export (C, u00048, "system__finalization_implementationS");
26783    pragma Export (C, u00049, "system__string_ops_concat_3B");
26784    pragma Export (C, u00050, "system__string_ops_concat_3S");
26785    pragma Export (C, u00051, "system__stream_attributesB");
26786    pragma Export (C, u00052, "system__stream_attributesS");
26787    pragma Export (C, u00053, "ada__io_exceptionsS");
26788    pragma Export (C, u00054, "system__unsigned_typesS");
26789    pragma Export (C, u00055, "system__file_control_blockS");
26790    pragma Export (C, u00056, "ada__finalization__list_controllerB");
26791    pragma Export (C, u00057, "ada__finalization__list_controllerS");
26792
26793    -- BEGIN ELABORATION ORDER
26794    -- ada (spec)
26795    -- gnat (spec)
26796    -- gnat.heap_sort_a (spec)
26797    -- gnat.heap_sort_a (body)
26798    -- gnat.htable (spec)
26799    -- gnat.htable (body)
26800    -- interfaces (spec)
26801    -- system (spec)
26802    -- system.machine_code (spec)
26803    -- system.parameters (spec)
26804    -- system.parameters (body)
26805    -- interfaces.c_streams (spec)
26806    -- interfaces.c_streams (body)
26807    -- system.standard_library (spec)
26808    -- ada.exceptions (spec)
26809    -- system.exception_table (spec)
26810    -- system.exception_table (body)
26811    -- ada.io_exceptions (spec)
26812    -- system.exceptions (spec)
26813    -- system.storage_elements (spec)
26814    -- system.storage_elements (body)
26815    -- system.machine_state_operations (spec)
26816    -- system.machine_state_operations (body)
26817    -- system.secondary_stack (spec)
26818    -- system.stack_checking (spec)
26819    -- system.soft_links (spec)
26820    -- system.soft_links (body)
26821    -- system.stack_checking (body)
26822    -- system.secondary_stack (body)
26823    -- system.standard_library (body)
26824    -- system.string_ops (spec)
26825    -- system.string_ops (body)
26826    -- ada.tags (spec)
26827    -- ada.tags (body)
26828    -- ada.streams (spec)
26829    -- system.finalization_root (spec)
26830    -- system.finalization_root (body)
26831    -- system.string_ops_concat_3 (spec)
26832    -- system.string_ops_concat_3 (body)
26833    -- system.traceback (spec)
26834    -- system.traceback (body)
26835    -- ada.exceptions (body)
26836    -- system.unsigned_types (spec)
26837    -- system.stream_attributes (spec)
26838    -- system.stream_attributes (body)
26839    -- system.finalization_implementation (spec)
26840    -- system.finalization_implementation (body)
26841    -- ada.finalization (spec)
26842    -- ada.finalization (body)
26843    -- ada.finalization.list_controller (spec)
26844    -- ada.finalization.list_controller (body)
26845    -- system.file_control_block (spec)
26846    -- system.file_io (spec)
26847    -- system.file_io (body)
26848    -- ada.text_io (spec)
26849    -- ada.text_io (body)
26850    -- hello (body)
26851    -- END ELABORATION ORDER
26852
26853 end ada_main;
26854
26855 --  The following source file name pragmas allow the generated file
26856 --  names to be unique for different main programs. They are needed
26857 --  since the package name will always be Ada_Main.
26858
26859 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26860 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26861
26862 --  Generated package body for Ada_Main starts here
26863
26864 package body ada_main is
26865
26866    --  The actual finalization is performed by calling the
26867    --  library routine in System.Standard_Library.Adafinal
26868
26869    procedure Do_Finalize;
26870    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
26871
26872    -------------
26873    -- adainit --
26874    -------------
26875
26876 @findex adainit
26877    procedure adainit is
26878
26879       --  These booleans are set to True once the associated unit has
26880       --  been elaborated. It is also used to avoid elaborating the
26881       --  same unit twice.
26882
26883       E040 : Boolean;
26884       pragma Import (Ada, E040, "interfaces__c_streams_E");
26885
26886       E008 : Boolean;
26887       pragma Import (Ada, E008, "ada__exceptions_E");
26888
26889       E014 : Boolean;
26890       pragma Import (Ada, E014, "system__exception_table_E");
26891
26892       E053 : Boolean;
26893       pragma Import (Ada, E053, "ada__io_exceptions_E");
26894
26895       E017 : Boolean;
26896       pragma Import (Ada, E017, "system__exceptions_E");
26897
26898       E024 : Boolean;
26899       pragma Import (Ada, E024, "system__secondary_stack_E");
26900
26901       E030 : Boolean;
26902       pragma Import (Ada, E030, "system__stack_checking_E");
26903
26904       E028 : Boolean;
26905       pragma Import (Ada, E028, "system__soft_links_E");
26906
26907       E035 : Boolean;
26908       pragma Import (Ada, E035, "ada__tags_E");
26909
26910       E033 : Boolean;
26911       pragma Import (Ada, E033, "ada__streams_E");
26912
26913       E046 : Boolean;
26914       pragma Import (Ada, E046, "system__finalization_root_E");
26915
26916       E048 : Boolean;
26917       pragma Import (Ada, E048, "system__finalization_implementation_E");
26918
26919       E044 : Boolean;
26920       pragma Import (Ada, E044, "ada__finalization_E");
26921
26922       E057 : Boolean;
26923       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
26924
26925       E055 : Boolean;
26926       pragma Import (Ada, E055, "system__file_control_block_E");
26927
26928       E042 : Boolean;
26929       pragma Import (Ada, E042, "system__file_io_E");
26930
26931       E006 : Boolean;
26932       pragma Import (Ada, E006, "ada__text_io_E");
26933
26934       --  Set_Globals is a library routine that stores away the
26935       --  value of the indicated set of global values in global
26936       --  variables within the library.
26937
26938       procedure Set_Globals
26939         (Main_Priority            : Integer;
26940          Time_Slice_Value         : Integer;
26941          WC_Encoding              : Character;
26942          Locking_Policy           : Character;
26943          Queuing_Policy           : Character;
26944          Task_Dispatching_Policy  : Character;
26945          Adafinal                 : System.Address;
26946          Unreserve_All_Interrupts : Integer;
26947          Exception_Tracebacks     : Integer);
26948 @findex __gnat_set_globals
26949       pragma Import (C, Set_Globals, "__gnat_set_globals");
26950
26951       --  SDP_Table_Build is a library routine used to build the
26952       --  exception tables. See unit Ada.Exceptions in files
26953       --  a-except.ads/adb for full details of how zero cost
26954       --  exception handling works. This procedure, the call to
26955       --  it, and the two following tables are all omitted if the
26956       --  build is in longjmp/setjmp exception mode.
26957
26958 @findex SDP_Table_Build
26959 @findex Zero Cost Exceptions
26960       procedure SDP_Table_Build
26961         (SDP_Addresses   : System.Address;
26962          SDP_Count       : Natural;
26963          Elab_Addresses  : System.Address;
26964          Elab_Addr_Count : Natural);
26965       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
26966
26967       --  Table of Unit_Exception_Table addresses. Used for zero
26968       --  cost exception handling to build the top level table.
26969
26970       ST : aliased constant array (1 .. 23) of System.Address := (
26971         Hello'UET_Address,
26972         Ada.Text_Io'UET_Address,
26973         Ada.Exceptions'UET_Address,
26974         Gnat.Heap_Sort_A'UET_Address,
26975         System.Exception_Table'UET_Address,
26976         System.Machine_State_Operations'UET_Address,
26977         System.Secondary_Stack'UET_Address,
26978         System.Parameters'UET_Address,
26979         System.Soft_Links'UET_Address,
26980         System.Stack_Checking'UET_Address,
26981         System.Traceback'UET_Address,
26982         Ada.Streams'UET_Address,
26983         Ada.Tags'UET_Address,
26984         System.String_Ops'UET_Address,
26985         Interfaces.C_Streams'UET_Address,
26986         System.File_Io'UET_Address,
26987         Ada.Finalization'UET_Address,
26988         System.Finalization_Root'UET_Address,
26989         System.Finalization_Implementation'UET_Address,
26990         System.String_Ops_Concat_3'UET_Address,
26991         System.Stream_Attributes'UET_Address,
26992         System.File_Control_Block'UET_Address,
26993         Ada.Finalization.List_Controller'UET_Address);
26994
26995       --  Table of addresses of elaboration routines. Used for
26996       --  zero cost exception handling to make sure these
26997       --  addresses are included in the top level procedure
26998       --  address table.
26999
27000       EA : aliased constant array (1 .. 23) of System.Address := (
27001         adainit'Code_Address,
27002         Do_Finalize'Code_Address,
27003         Ada.Exceptions'Elab_Spec'Address,
27004         System.Exceptions'Elab_Spec'Address,
27005         Interfaces.C_Streams'Elab_Spec'Address,
27006         System.Exception_Table'Elab_Body'Address,
27007         Ada.Io_Exceptions'Elab_Spec'Address,
27008         System.Stack_Checking'Elab_Spec'Address,
27009         System.Soft_Links'Elab_Body'Address,
27010         System.Secondary_Stack'Elab_Body'Address,
27011         Ada.Tags'Elab_Spec'Address,
27012         Ada.Tags'Elab_Body'Address,
27013         Ada.Streams'Elab_Spec'Address,
27014         System.Finalization_Root'Elab_Spec'Address,
27015         Ada.Exceptions'Elab_Body'Address,
27016         System.Finalization_Implementation'Elab_Spec'Address,
27017         System.Finalization_Implementation'Elab_Body'Address,
27018         Ada.Finalization'Elab_Spec'Address,
27019         Ada.Finalization.List_Controller'Elab_Spec'Address,
27020         System.File_Control_Block'Elab_Spec'Address,
27021         System.File_Io'Elab_Body'Address,
27022         Ada.Text_Io'Elab_Spec'Address,
27023         Ada.Text_Io'Elab_Body'Address);
27024
27025    --  Start of processing for adainit
27026
27027    begin
27028
27029       --  Call SDP_Table_Build to build the top level procedure
27030       --  table for zero cost exception handling (omitted in
27031       --  longjmp/setjmp mode).
27032
27033       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
27034
27035       --  Call Set_Globals to record various information for
27036       --  this partition.  The values are derived by the binder
27037       --  from information stored in the ali files by the compiler.
27038
27039 @findex __gnat_set_globals
27040       Set_Globals
27041         (Main_Priority            => -1,
27042          --  Priority of main program, -1 if no pragma Priority used
27043
27044          Time_Slice_Value         => -1,
27045          --  Time slice from Time_Slice pragma, -1 if none used
27046
27047          WC_Encoding              => 'b',
27048          --  Wide_Character encoding used, default is brackets
27049
27050          Locking_Policy           => ' ',
27051          --  Locking_Policy used, default of space means not
27052          --  specified, otherwise it is the first character of
27053          --  the policy name.
27054
27055          Queuing_Policy           => ' ',
27056          --  Queuing_Policy used, default of space means not
27057          --  specified, otherwise it is the first character of
27058          --  the policy name.
27059
27060          Task_Dispatching_Policy  => ' ',
27061          --  Task_Dispatching_Policy used, default of space means
27062          --  not specified, otherwise first character of the
27063          --  policy name.
27064
27065          Adafinal                 => System.Null_Address,
27066          --  Address of Adafinal routine, not used anymore
27067
27068          Unreserve_All_Interrupts => 0,
27069          --  Set true if pragma Unreserve_All_Interrupts was used
27070
27071          Exception_Tracebacks     => 0);
27072          --  Indicates if exception tracebacks are enabled
27073
27074       Elab_Final_Code := 1;
27075
27076       --  Now we have the elaboration calls for all units in the partition.
27077       --  The Elab_Spec and Elab_Body attributes generate references to the
27078       --  implicit elaboration procedures generated by the compiler for
27079       --  each unit that requires elaboration.
27080
27081       if not E040 then
27082          Interfaces.C_Streams'Elab_Spec;
27083       end if;
27084       E040 := True;
27085       if not E008 then
27086          Ada.Exceptions'Elab_Spec;
27087       end if;
27088       if not E014 then
27089          System.Exception_Table'Elab_Body;
27090          E014 := True;
27091       end if;
27092       if not E053 then
27093          Ada.Io_Exceptions'Elab_Spec;
27094          E053 := True;
27095       end if;
27096       if not E017 then
27097          System.Exceptions'Elab_Spec;
27098          E017 := True;
27099       end if;
27100       if not E030 then
27101          System.Stack_Checking'Elab_Spec;
27102       end if;
27103       if not E028 then
27104          System.Soft_Links'Elab_Body;
27105          E028 := True;
27106       end if;
27107       E030 := True;
27108       if not E024 then
27109          System.Secondary_Stack'Elab_Body;
27110          E024 := True;
27111       end if;
27112       if not E035 then
27113          Ada.Tags'Elab_Spec;
27114       end if;
27115       if not E035 then
27116          Ada.Tags'Elab_Body;
27117          E035 := True;
27118       end if;
27119       if not E033 then
27120          Ada.Streams'Elab_Spec;
27121          E033 := True;
27122       end if;
27123       if not E046 then
27124          System.Finalization_Root'Elab_Spec;
27125       end if;
27126       E046 := True;
27127       if not E008 then
27128          Ada.Exceptions'Elab_Body;
27129          E008 := True;
27130       end if;
27131       if not E048 then
27132          System.Finalization_Implementation'Elab_Spec;
27133       end if;
27134       if not E048 then
27135          System.Finalization_Implementation'Elab_Body;
27136          E048 := True;
27137       end if;
27138       if not E044 then
27139          Ada.Finalization'Elab_Spec;
27140       end if;
27141       E044 := True;
27142       if not E057 then
27143          Ada.Finalization.List_Controller'Elab_Spec;
27144       end if;
27145       E057 := True;
27146       if not E055 then
27147          System.File_Control_Block'Elab_Spec;
27148          E055 := True;
27149       end if;
27150       if not E042 then
27151          System.File_Io'Elab_Body;
27152          E042 := True;
27153       end if;
27154       if not E006 then
27155          Ada.Text_Io'Elab_Spec;
27156       end if;
27157       if not E006 then
27158          Ada.Text_Io'Elab_Body;
27159          E006 := True;
27160       end if;
27161
27162       Elab_Final_Code := 0;
27163    end adainit;
27164
27165    --------------
27166    -- adafinal --
27167    --------------
27168
27169 @findex adafinal
27170    procedure adafinal is
27171    begin
27172       Do_Finalize;
27173    end adafinal;
27174
27175    ----------
27176    -- main --
27177    ----------
27178
27179    --  main is actually a function, as in the ANSI C standard,
27180    --  defined to return the exit status. The three parameters
27181    --  are the argument count, argument values and environment
27182    --  pointer.
27183
27184 @findex Main Program
27185    function main
27186      (argc : Integer;
27187       argv : System.Address;
27188       envp : System.Address)
27189       return Integer
27190    is
27191       --  The initialize routine performs low level system
27192       --  initialization using a standard library routine which
27193       --  sets up signal handling and performs any other
27194       --  required setup. The routine can be found in file
27195       --  a-init.c.
27196
27197 @findex __gnat_initialize
27198       procedure initialize;
27199       pragma Import (C, initialize, "__gnat_initialize");
27200
27201       --  The finalize routine performs low level system
27202       --  finalization using a standard library routine. The
27203       --  routine is found in file a-final.c and in the standard
27204       --  distribution is a dummy routine that does nothing, so
27205       --  really this is a hook for special user finalization.
27206
27207 @findex __gnat_finalize
27208       procedure finalize;
27209       pragma Import (C, finalize, "__gnat_finalize");
27210
27211       --  We get to the main program of the partition by using
27212       --  pragma Import because if we try to with the unit and
27213       --  call it Ada style, then not only do we waste time
27214       --  recompiling it, but also, we don't really know the right
27215       --  switches (e.g.@: identifier character set) to be used
27216       --  to compile it.
27217
27218       procedure Ada_Main_Program;
27219       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
27220
27221    --  Start of processing for main
27222
27223    begin
27224       --  Save global variables
27225
27226       gnat_argc := argc;
27227       gnat_argv := argv;
27228       gnat_envp := envp;
27229
27230       --  Call low level system initialization
27231
27232       Initialize;
27233
27234       --  Call our generated Ada initialization routine
27235
27236       adainit;
27237
27238       --  This is the point at which we want the debugger to get
27239       --  control
27240
27241       Break_Start;
27242
27243       --  Now we call the main program of the partition
27244
27245       Ada_Main_Program;
27246
27247       --  Perform Ada finalization
27248
27249       adafinal;
27250
27251       --  Perform low level system finalization
27252
27253       Finalize;
27254
27255       --  Return the proper exit status
27256       return (gnat_exit_status);
27257    end;
27258
27259 --  This section is entirely comments, so it has no effect on the
27260 --  compilation of the Ada_Main package. It provides the list of
27261 --  object files and linker options, as well as some standard
27262 --  libraries needed for the link. The gnatlink utility parses
27263 --  this b~hello.adb file to read these comment lines to generate
27264 --  the appropriate command line arguments for the call to the
27265 --  system linker. The BEGIN/END lines are used for sentinels for
27266 --  this parsing operation.
27267
27268 --  The exact file names will of course depend on the environment,
27269 --  host/target and location of files on the host system.
27270
27271 @findex Object file list
27272 -- BEGIN Object file/option list
27273    --   ./hello.o
27274    --   -L./
27275    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
27276    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
27277 -- END Object file/option list
27278
27279 end ada_main;
27280 @end smallexample
27281
27282 @noindent
27283 The Ada code in the above example is exactly what is generated by the
27284 binder. We have added comments to more clearly indicate the function
27285 of each part of the generated @code{Ada_Main} package.
27286
27287 The code is standard Ada in all respects, and can be processed by any
27288 tools that handle Ada. In particular, it is possible to use the debugger
27289 in Ada mode to debug the generated @code{Ada_Main} package. For example,
27290 suppose that for reasons that you do not understand, your program is crashing
27291 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
27292 you can place a breakpoint on the call:
27293
27294 @smallexample @c ada
27295 Ada.Text_Io'Elab_Body;
27296 @end smallexample
27297
27298 @noindent
27299 and trace the elaboration routine for this package to find out where
27300 the problem might be (more usually of course you would be debugging
27301 elaboration code in your own application).
27302
27303 @node Elaboration Order Handling in GNAT
27304 @appendix Elaboration Order Handling in GNAT
27305 @cindex Order of elaboration
27306 @cindex Elaboration control
27307
27308 @menu
27309 * Elaboration Code::
27310 * Checking the Elaboration Order::
27311 * Controlling the Elaboration Order::
27312 * Controlling Elaboration in GNAT - Internal Calls::
27313 * Controlling Elaboration in GNAT - External Calls::
27314 * Default Behavior in GNAT - Ensuring Safety::
27315 * Treatment of Pragma Elaborate::
27316 * Elaboration Issues for Library Tasks::
27317 * Mixing Elaboration Models::
27318 * What to Do If the Default Elaboration Behavior Fails::
27319 * Elaboration for Access-to-Subprogram Values::
27320 * Summary of Procedures for Elaboration Control::
27321 * Other Elaboration Order Considerations::
27322 @end menu
27323
27324 @noindent
27325 This chapter describes the handling of elaboration code in Ada and
27326 in GNAT, and discusses how the order of elaboration of program units can
27327 be controlled in GNAT, either automatically or with explicit programming
27328 features.
27329
27330 @node Elaboration Code
27331 @section Elaboration Code
27332
27333 @noindent
27334 Ada provides rather general mechanisms for executing code at elaboration
27335 time, that is to say before the main program starts executing. Such code arises
27336 in three contexts:
27337
27338 @table @asis
27339 @item Initializers for variables.
27340 Variables declared at the library level, in package specs or bodies, can
27341 require initialization that is performed at elaboration time, as in:
27342 @smallexample @c ada
27343 @cartouche
27344 Sqrt_Half : Float := Sqrt (0.5);
27345 @end cartouche
27346 @end smallexample
27347
27348 @item Package initialization code
27349 Code in a @code{BEGIN-END} section at the outer level of a package body is
27350 executed as part of the package body elaboration code.
27351
27352 @item Library level task allocators
27353 Tasks that are declared using task allocators at the library level
27354 start executing immediately and hence can execute at elaboration time.
27355 @end table
27356
27357 @noindent
27358 Subprogram calls are possible in any of these contexts, which means that
27359 any arbitrary part of the program may be executed as part of the elaboration
27360 code. It is even possible to write a program which does all its work at
27361 elaboration time, with a null main program, although stylistically this
27362 would usually be considered an inappropriate way to structure
27363 a program.
27364
27365 An important concern arises in the context of elaboration code:
27366 we have to be sure that it is executed in an appropriate order. What we
27367 have is a series of elaboration code sections, potentially one section
27368 for each unit in the program. It is important that these execute
27369 in the correct order. Correctness here means that, taking the above
27370 example of the declaration of @code{Sqrt_Half},
27371 if some other piece of
27372 elaboration code references @code{Sqrt_Half},
27373 then it must run after the
27374 section of elaboration code that contains the declaration of
27375 @code{Sqrt_Half}.
27376
27377 There would never be any order of elaboration problem if we made a rule
27378 that whenever you @code{with} a unit, you must elaborate both the spec and body
27379 of that unit before elaborating the unit doing the @code{with}'ing:
27380
27381 @smallexample @c ada
27382 @group
27383 @cartouche
27384 with Unit_1;
27385 package Unit_2 is @dots{}
27386 @end cartouche
27387 @end group
27388 @end smallexample
27389
27390 @noindent
27391 would require that both the body and spec of @code{Unit_1} be elaborated
27392 before the spec of @code{Unit_2}. However, a rule like that would be far too
27393 restrictive. In particular, it would make it impossible to have routines
27394 in separate packages that were mutually recursive.
27395
27396 You might think that a clever enough compiler could look at the actual
27397 elaboration code and determine an appropriate correct order of elaboration,
27398 but in the general case, this is not possible. Consider the following
27399 example.
27400
27401 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
27402 that references
27403 the variable @code{Sqrt_1}, which is declared in the elaboration code
27404 of the body of @code{Unit_1}:
27405
27406 @smallexample @c ada
27407 @cartouche
27408 Sqrt_1 : Float := Sqrt (0.1);
27409 @end cartouche
27410 @end smallexample
27411
27412 @noindent
27413 The elaboration code of the body of @code{Unit_1} also contains:
27414
27415 @smallexample @c ada
27416 @group
27417 @cartouche
27418 if expression_1 = 1 then
27419    Q := Unit_2.Func_2;
27420 end if;
27421 @end cartouche
27422 @end group
27423 @end smallexample
27424
27425 @noindent
27426 @code{Unit_2} is exactly parallel,
27427 it has a procedure @code{Func_2} that references
27428 the variable @code{Sqrt_2}, which is declared in the elaboration code of
27429 the body @code{Unit_2}:
27430
27431 @smallexample @c ada
27432 @cartouche
27433 Sqrt_2 : Float := Sqrt (0.1);
27434 @end cartouche
27435 @end smallexample
27436
27437 @noindent
27438 The elaboration code of the body of @code{Unit_2} also contains:
27439
27440 @smallexample @c ada
27441 @group
27442 @cartouche
27443 if expression_2 = 2 then
27444    Q := Unit_1.Func_1;
27445 end if;
27446 @end cartouche
27447 @end group
27448 @end smallexample
27449
27450 @noindent
27451 Now the question is, which of the following orders of elaboration is
27452 acceptable:
27453
27454 @smallexample
27455 @group
27456 Spec of Unit_1
27457 Spec of Unit_2
27458 Body of Unit_1
27459 Body of Unit_2
27460 @end group
27461 @end smallexample
27462
27463 @noindent
27464 or
27465
27466 @smallexample
27467 @group
27468 Spec of Unit_2
27469 Spec of Unit_1
27470 Body of Unit_2
27471 Body of Unit_1
27472 @end group
27473 @end smallexample
27474
27475 @noindent
27476 If you carefully analyze the flow here, you will see that you cannot tell
27477 at compile time the answer to this question.
27478 If @code{expression_1} is not equal to 1,
27479 and @code{expression_2} is not equal to 2,
27480 then either order is acceptable, because neither of the function calls is
27481 executed. If both tests evaluate to true, then neither order is acceptable
27482 and in fact there is no correct order.
27483
27484 If one of the two expressions is true, and the other is false, then one
27485 of the above orders is correct, and the other is incorrect. For example,
27486 if @code{expression_1} /= 1 and @code{expression_2} = 2,
27487 then the call to @code{Func_1}
27488 will occur, but not the call to @code{Func_2.}
27489 This means that it is essential
27490 to elaborate the body of @code{Unit_1} before
27491 the body of @code{Unit_2}, so the first
27492 order of elaboration is correct and the second is wrong.
27493
27494 By making @code{expression_1} and @code{expression_2}
27495 depend on input data, or perhaps
27496 the time of day, we can make it impossible for the compiler or binder
27497 to figure out which of these expressions will be true, and hence it
27498 is impossible to guarantee a safe order of elaboration at run time.
27499
27500 @node Checking the Elaboration Order
27501 @section Checking the Elaboration Order
27502
27503 @noindent
27504 In some languages that involve the same kind of elaboration problems,
27505 e.g.@: Java and C++, the programmer is expected to worry about these
27506 ordering problems himself, and it is common to
27507 write a program in which an incorrect elaboration order  gives
27508 surprising results, because it references variables before they
27509 are initialized.
27510 Ada is designed to be a safe language, and a programmer-beware approach is
27511 clearly not sufficient. Consequently, the language provides three lines
27512 of defense:
27513
27514 @table @asis
27515 @item Standard rules
27516 Some standard rules restrict the possible choice of elaboration
27517 order. In particular, if you @code{with} a unit, then its spec is always
27518 elaborated before the unit doing the @code{with}. Similarly, a parent
27519 spec is always elaborated before the child spec, and finally
27520 a spec is always elaborated before its corresponding body.
27521
27522 @item Dynamic elaboration checks
27523 @cindex Elaboration checks
27524 @cindex Checks, elaboration
27525 Dynamic checks are made at run time, so that if some entity is accessed
27526 before it is elaborated (typically  by means of a subprogram call)
27527 then the exception (@code{Program_Error}) is raised.
27528
27529 @item Elaboration control
27530 Facilities are provided for the programmer to specify the desired order
27531 of elaboration.
27532 @end table
27533
27534 Let's look at these facilities in more detail. First, the rules for
27535 dynamic checking. One possible rule would be simply to say that the
27536 exception is raised if you access a variable which has not yet been
27537 elaborated. The trouble with this approach is that it could require
27538 expensive checks on every variable reference. Instead Ada has two
27539 rules which are a little more restrictive, but easier to check, and
27540 easier to state:
27541
27542 @table @asis
27543 @item Restrictions on calls
27544 A subprogram can only be called at elaboration time if its body
27545 has been elaborated. The rules for elaboration given above guarantee
27546 that the spec of the subprogram has been elaborated before the
27547 call, but not the body. If this rule is violated, then the
27548 exception @code{Program_Error} is raised.
27549
27550 @item Restrictions on instantiations
27551 A generic unit can only be instantiated if the body of the generic
27552 unit has been elaborated. Again, the rules for elaboration given above
27553 guarantee that the spec of the generic unit has been elaborated
27554 before the instantiation, but not the body. If this rule is
27555 violated, then the exception @code{Program_Error} is raised.
27556 @end table
27557
27558 @noindent
27559 The idea is that if the body has been elaborated, then any variables
27560 it references must have been elaborated; by checking for the body being
27561 elaborated we guarantee that none of its references causes any
27562 trouble. As we noted above, this is a little too restrictive, because a
27563 subprogram that has no non-local references in its body may in fact be safe
27564 to call. However, it really would be unsafe to rely on this, because
27565 it would mean that the caller was aware of details of the implementation
27566 in the body. This goes against the basic tenets of Ada.
27567
27568 A plausible implementation can be described as follows.
27569 A Boolean variable is associated with each subprogram
27570 and each generic unit. This variable is initialized to False, and is set to
27571 True at the point body is elaborated. Every call or instantiation checks the
27572 variable, and raises @code{Program_Error} if the variable is False.
27573
27574 Note that one might think that it would be good enough to have one Boolean
27575 variable for each package, but that would not deal with cases of trying
27576 to call a body in the same package as the call
27577 that has not been elaborated yet.
27578 Of course a compiler may be able to do enough analysis to optimize away
27579 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
27580 does such optimizations, but still the easiest conceptual model is to
27581 think of there being one variable per subprogram.
27582
27583 @node Controlling the Elaboration Order
27584 @section Controlling the Elaboration Order
27585
27586 @noindent
27587 In the previous section we discussed the rules in Ada which ensure
27588 that @code{Program_Error} is raised if an incorrect elaboration order is
27589 chosen. This prevents erroneous executions, but we need mechanisms to
27590 specify a correct execution and avoid the exception altogether.
27591 To achieve this, Ada provides a number of features for controlling
27592 the order of elaboration. We discuss these features in this section.
27593
27594 First, there are several ways of indicating to the compiler that a given
27595 unit has no elaboration problems:
27596
27597 @table @asis
27598 @item packages that do not require a body
27599 A library package that does not require a body does not permit
27600 a body (this rule was introduced in Ada 95).
27601 Thus if we have a such a package, as in:
27602
27603 @smallexample @c ada
27604 @group
27605 @cartouche
27606 package Definitions is
27607    generic
27608       type m is new integer;
27609    package Subp is
27610       type a is array (1 .. 10) of m;
27611       type b is array (1 .. 20) of m;
27612    end Subp;
27613 end Definitions;
27614 @end cartouche
27615 @end group
27616 @end smallexample
27617
27618 @noindent
27619 A package that @code{with}'s @code{Definitions} may safely instantiate
27620 @code{Definitions.Subp} because the compiler can determine that there
27621 definitely is no package body to worry about in this case
27622
27623 @item pragma Pure
27624 @cindex pragma Pure
27625 @findex Pure
27626 Places sufficient restrictions on a unit to guarantee that
27627 no call to any subprogram in the unit can result in an
27628 elaboration problem. This means that the compiler does not need
27629 to worry about the point of elaboration of such units, and in
27630 particular, does not need to check any calls to any subprograms
27631 in this unit.
27632
27633 @item pragma Preelaborate
27634 @findex Preelaborate
27635 @cindex pragma Preelaborate
27636 This pragma places slightly less stringent restrictions on a unit than
27637 does pragma Pure,
27638 but these restrictions are still sufficient to ensure that there
27639 are no elaboration problems with any calls to the unit.
27640
27641 @item pragma Elaborate_Body
27642 @findex Elaborate_Body
27643 @cindex pragma Elaborate_Body
27644 This pragma requires that the body of a unit be elaborated immediately
27645 after its spec. Suppose a unit @code{A} has such a pragma,
27646 and unit @code{B} does
27647 a @code{with} of unit @code{A}. Recall that the standard rules require
27648 the spec of unit @code{A}
27649 to be elaborated before the @code{with}'ing unit; given the pragma in
27650 @code{A}, we also know that the body of @code{A}
27651 will be elaborated before @code{B}, so
27652 that calls to @code{A} are safe and do not need a check.
27653 @end table
27654
27655 @noindent
27656 Note that,
27657 unlike pragma @code{Pure} and pragma @code{Preelaborate},
27658 the use of
27659 @code{Elaborate_Body} does not guarantee that the program is
27660 free of elaboration problems, because it may not be possible
27661 to satisfy the requested elaboration order.
27662 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
27663 If a programmer
27664 marks @code{Unit_1} as @code{Elaborate_Body},
27665 and not @code{Unit_2,} then the order of
27666 elaboration will be:
27667
27668 @smallexample
27669 @group
27670 Spec of Unit_2
27671 Spec of Unit_1
27672 Body of Unit_1
27673 Body of Unit_2
27674 @end group
27675 @end smallexample
27676
27677 @noindent
27678 Now that means that the call to @code{Func_1} in @code{Unit_2}
27679 need not be checked,
27680 it must be safe. But the call to @code{Func_2} in
27681 @code{Unit_1} may still fail if
27682 @code{Expression_1} is equal to 1,
27683 and the programmer must still take
27684 responsibility for this not being the case.
27685
27686 If all units carry a pragma @code{Elaborate_Body}, then all problems are
27687 eliminated, except for calls entirely within a body, which are
27688 in any case fully under programmer control. However, using the pragma
27689 everywhere is not always possible.
27690 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
27691 we marked both of them as having pragma @code{Elaborate_Body}, then
27692 clearly there would be no possible elaboration order.
27693
27694 The above pragmas allow a server to guarantee safe use by clients, and
27695 clearly this is the preferable approach. Consequently a good rule
27696 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
27697 and if this is not possible,
27698 mark them as @code{Elaborate_Body} if possible.
27699 As we have seen, there are situations where neither of these
27700 three pragmas can be used.
27701 So we also provide methods for clients to control the
27702 order of elaboration of the servers on which they depend:
27703
27704 @table @asis
27705 @item pragma Elaborate (unit)
27706 @findex Elaborate
27707 @cindex pragma Elaborate
27708 This pragma is placed in the context clause, after a @code{with} clause,
27709 and it requires that the body of the named unit be elaborated before
27710 the unit in which the pragma occurs. The idea is to use this pragma
27711 if the current unit calls at elaboration time, directly or indirectly,
27712 some subprogram in the named unit.
27713
27714 @item pragma Elaborate_All (unit)
27715 @findex Elaborate_All
27716 @cindex pragma Elaborate_All
27717 This is a stronger version of the Elaborate pragma. Consider the
27718 following example:
27719
27720 @smallexample
27721 Unit A @code{with}'s unit B and calls B.Func in elab code
27722 Unit B @code{with}'s unit C, and B.Func calls C.Func
27723 @end smallexample
27724
27725 @noindent
27726 Now if we put a pragma @code{Elaborate (B)}
27727 in unit @code{A}, this ensures that the
27728 body of @code{B} is elaborated before the call, but not the
27729 body of @code{C}, so
27730 the call to @code{C.Func} could still cause @code{Program_Error} to
27731 be raised.
27732
27733 The effect of a pragma @code{Elaborate_All} is stronger, it requires
27734 not only that the body of the named unit be elaborated before the
27735 unit doing the @code{with}, but also the bodies of all units that the
27736 named unit uses, following @code{with} links transitively. For example,
27737 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
27738 then it requires
27739 not only that the body of @code{B} be elaborated before @code{A},
27740 but also the
27741 body of @code{C}, because @code{B} @code{with}'s @code{C}.
27742 @end table
27743
27744 @noindent
27745 We are now in a position to give a usage rule in Ada for avoiding
27746 elaboration problems, at least if dynamic dispatching and access to
27747 subprogram values are not used. We will handle these cases separately
27748 later.
27749
27750 The rule is simple. If a unit has elaboration code that can directly or
27751 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
27752 a generic package in a @code{with}'ed unit,
27753 then if the @code{with}'ed unit does not have
27754 pragma @code{Pure} or @code{Preelaborate}, then the client should have
27755 a pragma @code{Elaborate_All}
27756 for the @code{with}'ed unit. By following this rule a client is
27757 assured that calls can be made without risk of an exception.
27758
27759 For generic subprogram instantiations, the rule can be relaxed to
27760 require only a pragma @code{Elaborate} since elaborating the body
27761 of a subprogram cannot cause any transitive elaboration (we are
27762 not calling the subprogram in this case, just elaborating its
27763 declaration).
27764
27765 If this rule is not followed, then a program may be in one of four
27766 states:
27767
27768 @table @asis
27769 @item No order exists
27770 No order of elaboration exists which follows the rules, taking into
27771 account any @code{Elaborate}, @code{Elaborate_All},
27772 or @code{Elaborate_Body} pragmas. In
27773 this case, an Ada compiler must diagnose the situation at bind
27774 time, and refuse to build an executable program.
27775
27776 @item One or more orders exist, all incorrect
27777 One or more acceptable elaboration orders exist, and all of them
27778 generate an elaboration order problem. In this case, the binder
27779 can build an executable program, but @code{Program_Error} will be raised
27780 when the program is run.
27781
27782 @item Several orders exist, some right, some incorrect
27783 One or more acceptable elaboration orders exists, and some of them
27784 work, and some do not. The programmer has not controlled
27785 the order of elaboration, so the binder may or may not pick one of
27786 the correct orders, and the program may or may not raise an
27787 exception when it is run. This is the worst case, because it means
27788 that the program may fail when moved to another compiler, or even
27789 another version of the same compiler.
27790
27791 @item One or more orders exists, all correct
27792 One ore more acceptable elaboration orders exist, and all of them
27793 work. In this case the program runs successfully. This state of
27794 affairs can be guaranteed by following the rule we gave above, but
27795 may be true even if the rule is not followed.
27796 @end table
27797
27798 @noindent
27799 Note that one additional advantage of following our rules on the use
27800 of @code{Elaborate} and @code{Elaborate_All}
27801 is that the program continues to stay in the ideal (all orders OK) state
27802 even if maintenance
27803 changes some bodies of some units. Conversely, if a program that does
27804 not follow this rule happens to be safe at some point, this state of affairs
27805 may deteriorate silently as a result of maintenance changes.
27806
27807 You may have noticed that the above discussion did not mention
27808 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
27809 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
27810 code in the body makes calls to some other unit, so it is still necessary
27811 to use @code{Elaborate_All} on such units.
27812
27813 @node Controlling Elaboration in GNAT - Internal Calls
27814 @section Controlling Elaboration in GNAT - Internal Calls
27815
27816 @noindent
27817 In the case of internal calls, i.e., calls within a single package, the
27818 programmer has full control over the order of elaboration, and it is up
27819 to the programmer to elaborate declarations in an appropriate order. For
27820 example writing:
27821
27822 @smallexample @c ada
27823 @group
27824 @cartouche
27825 function One return Float;
27826
27827 Q : Float := One;
27828
27829 function One return Float is
27830 begin
27831      return 1.0;
27832 end One;
27833 @end cartouche
27834 @end group
27835 @end smallexample
27836
27837 @noindent
27838 will obviously raise @code{Program_Error} at run time, because function
27839 One will be called before its body is elaborated. In this case GNAT will
27840 generate a warning that the call will raise @code{Program_Error}:
27841
27842 @smallexample
27843 @group
27844 @cartouche
27845  1. procedure y is
27846  2.    function One return Float;
27847  3.
27848  4.    Q : Float := One;
27849                     |
27850     >>> warning: cannot call "One" before body is elaborated
27851     >>> warning: Program_Error will be raised at run time
27852
27853  5.
27854  6.    function One return Float is
27855  7.    begin
27856  8.         return 1.0;
27857  9.    end One;
27858 10.
27859 11. begin
27860 12.    null;
27861 13. end;
27862 @end cartouche
27863 @end group
27864 @end smallexample
27865
27866 @noindent
27867 Note that in this particular case, it is likely that the call is safe, because
27868 the function @code{One} does not access any global variables.
27869 Nevertheless in Ada, we do not want the validity of the check to depend on
27870 the contents of the body (think about the separate compilation case), so this
27871 is still wrong, as we discussed in the previous sections.
27872
27873 The error is easily corrected by rearranging the declarations so that the
27874 body of @code{One} appears before the declaration containing the call
27875 (note that in Ada 95 and Ada 2005,
27876 declarations can appear in any order, so there is no restriction that
27877 would prevent this reordering, and if we write:
27878
27879 @smallexample @c ada
27880 @group
27881 @cartouche
27882 function One return Float;
27883
27884 function One return Float is
27885 begin
27886      return 1.0;
27887 end One;
27888
27889 Q : Float := One;
27890 @end cartouche
27891 @end group
27892 @end smallexample
27893
27894 @noindent
27895 then all is well, no warning is generated, and no
27896 @code{Program_Error} exception
27897 will be raised.
27898 Things are more complicated when a chain of subprograms is executed:
27899
27900 @smallexample @c ada
27901 @group
27902 @cartouche
27903 function A return Integer;
27904 function B return Integer;
27905 function C return Integer;
27906
27907 function B return Integer is begin return A; end;
27908 function C return Integer is begin return B; end;
27909
27910 X : Integer := C;
27911
27912 function A return Integer is begin return 1; end;
27913 @end cartouche
27914 @end group
27915 @end smallexample
27916
27917 @noindent
27918 Now the call to @code{C}
27919 at elaboration time in the declaration of @code{X} is correct, because
27920 the body of @code{C} is already elaborated,
27921 and the call to @code{B} within the body of
27922 @code{C} is correct, but the call
27923 to @code{A} within the body of @code{B} is incorrect, because the body
27924 of @code{A} has not been elaborated, so @code{Program_Error}
27925 will be raised on the call to @code{A}.
27926 In this case GNAT will generate a
27927 warning that @code{Program_Error} may be
27928 raised at the point of the call. Let's look at the warning:
27929
27930 @smallexample
27931 @group
27932 @cartouche
27933  1. procedure x is
27934  2.    function A return Integer;
27935  3.    function B return Integer;
27936  4.    function C return Integer;
27937  5.
27938  6.    function B return Integer is begin return A; end;
27939                                                     |
27940     >>> warning: call to "A" before body is elaborated may
27941                  raise Program_Error
27942     >>> warning: "B" called at line 7
27943     >>> warning: "C" called at line 9
27944
27945  7.    function C return Integer is begin return B; end;
27946  8.
27947  9.    X : Integer := C;
27948 10.
27949 11.    function A return Integer is begin return 1; end;
27950 12.
27951 13. begin
27952 14.    null;
27953 15. end;
27954 @end cartouche
27955 @end group
27956 @end smallexample
27957
27958 @noindent
27959 Note that the message here says ``may raise'', instead of the direct case,
27960 where the message says ``will be raised''. That's because whether
27961 @code{A} is
27962 actually called depends in general on run-time flow of control.
27963 For example, if the body of @code{B} said
27964
27965 @smallexample @c ada
27966 @group
27967 @cartouche
27968 function B return Integer is
27969 begin
27970    if some-condition-depending-on-input-data then
27971       return A;
27972    else
27973       return 1;
27974    end if;
27975 end B;
27976 @end cartouche
27977 @end group
27978 @end smallexample
27979
27980 @noindent
27981 then we could not know until run time whether the incorrect call to A would
27982 actually occur, so @code{Program_Error} might
27983 or might not be raised. It is possible for a compiler to
27984 do a better job of analyzing bodies, to
27985 determine whether or not @code{Program_Error}
27986 might be raised, but it certainly
27987 couldn't do a perfect job (that would require solving the halting problem
27988 and is provably impossible), and because this is a warning anyway, it does
27989 not seem worth the effort to do the analysis. Cases in which it
27990 would be relevant are rare.
27991
27992 In practice, warnings of either of the forms given
27993 above will usually correspond to
27994 real errors, and should be examined carefully and eliminated.
27995 In the rare case where a warning is bogus, it can be suppressed by any of
27996 the following methods:
27997
27998 @itemize @bullet
27999 @item
28000 Compile with the @option{-gnatws} switch set
28001
28002 @item
28003 Suppress @code{Elaboration_Check} for the called subprogram
28004
28005 @item
28006 Use pragma @code{Warnings_Off} to turn warnings off for the call
28007 @end itemize
28008
28009 @noindent
28010 For the internal elaboration check case,
28011 GNAT by default generates the
28012 necessary run-time checks to ensure
28013 that @code{Program_Error} is raised if any
28014 call fails an elaboration check. Of course this can only happen if a
28015 warning has been issued as described above. The use of pragma
28016 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
28017 some of these checks, meaning that it may be possible (but is not
28018 guaranteed) for a program to be able to call a subprogram whose body
28019 is not yet elaborated, without raising a @code{Program_Error} exception.
28020
28021 @node Controlling Elaboration in GNAT - External Calls
28022 @section Controlling Elaboration in GNAT - External Calls
28023
28024 @noindent
28025 The previous section discussed the case in which the execution of a
28026 particular thread of elaboration code occurred entirely within a
28027 single unit. This is the easy case to handle, because a programmer
28028 has direct and total control over the order of elaboration, and
28029 furthermore, checks need only be generated in cases which are rare
28030 and which the compiler can easily detect.
28031 The situation is more complex when separate compilation is taken into account.
28032 Consider the following:
28033
28034 @smallexample @c ada
28035 @cartouche
28036 @group
28037 package Math is
28038    function Sqrt (Arg : Float) return Float;
28039 end Math;
28040
28041 package body Math is
28042    function Sqrt (Arg : Float) return Float is
28043    begin
28044          @dots{}
28045    end Sqrt;
28046 end Math;
28047 @end group
28048 @group
28049 with Math;
28050 package Stuff is
28051    X : Float := Math.Sqrt (0.5);
28052 end Stuff;
28053
28054 with Stuff;
28055 procedure Main is
28056 begin
28057    @dots{}
28058 end Main;
28059 @end group
28060 @end cartouche
28061 @end smallexample
28062
28063 @noindent
28064 where @code{Main} is the main program. When this program is executed, the
28065 elaboration code must first be executed, and one of the jobs of the
28066 binder is to determine the order in which the units of a program are
28067 to be elaborated. In this case we have four units: the spec and body
28068 of @code{Math},
28069 the spec of @code{Stuff} and the body of @code{Main}).
28070 In what order should the four separate sections of elaboration code
28071 be executed?
28072
28073 There are some restrictions in the order of elaboration that the binder
28074 can choose. In particular, if unit U has a @code{with}
28075 for a package @code{X}, then you
28076 are assured that the spec of @code{X}
28077 is elaborated before U , but you are
28078 not assured that the body of @code{X}
28079 is elaborated before U.
28080 This means that in the above case, the binder is allowed to choose the
28081 order:
28082
28083 @smallexample
28084 spec of Math
28085 spec of Stuff
28086 body of Math
28087 body of Main
28088 @end smallexample
28089
28090 @noindent
28091 but that's not good, because now the call to @code{Math.Sqrt}
28092 that happens during
28093 the elaboration of the @code{Stuff}
28094 spec happens before the body of @code{Math.Sqrt} is
28095 elaborated, and hence causes @code{Program_Error} exception to be raised.
28096 At first glance, one might say that the binder is misbehaving, because
28097 obviously you want to elaborate the body of something you @code{with}
28098 first, but
28099 that is not a general rule that can be followed in all cases. Consider
28100
28101 @smallexample @c ada
28102 @group
28103 @cartouche
28104 package X is @dots{}
28105
28106 package Y is @dots{}
28107
28108 with X;
28109 package body Y is @dots{}
28110
28111 with Y;
28112 package body X is @dots{}
28113 @end cartouche
28114 @end group
28115 @end smallexample
28116
28117 @noindent
28118 This is a common arrangement, and, apart from the order of elaboration
28119 problems that might arise in connection with elaboration code, this works fine.
28120 A rule that says that you must first elaborate the body of anything you
28121 @code{with} cannot work in this case:
28122 the body of @code{X} @code{with}'s @code{Y},
28123 which means you would have to
28124 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
28125 which means
28126 you have to elaborate the body of @code{X} first, but @dots{} and we have a
28127 loop that cannot be broken.
28128
28129 It is true that the binder can in many cases guess an order of elaboration
28130 that is unlikely to cause a @code{Program_Error}
28131 exception to be raised, and it tries to do so (in the
28132 above example of @code{Math/Stuff/Spec}, the GNAT binder will
28133 by default
28134 elaborate the body of @code{Math} right after its spec, so all will be well).
28135
28136 However, a program that blindly relies on the binder to be helpful can
28137 get into trouble, as we discussed in the previous sections, so
28138 GNAT
28139 provides a number of facilities for assisting the programmer in
28140 developing programs that are robust with respect to elaboration order.
28141
28142 @node Default Behavior in GNAT - Ensuring Safety
28143 @section Default Behavior in GNAT - Ensuring Safety
28144
28145 @noindent
28146 The default behavior in GNAT ensures elaboration safety. In its
28147 default mode GNAT implements the
28148 rule we previously described as the right approach. Let's restate it:
28149
28150 @itemize
28151 @item
28152 @emph{If a unit has elaboration code that can directly or indirectly make a
28153 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
28154 package in a @code{with}'ed unit, then if the @code{with}'ed unit
28155 does not have pragma @code{Pure} or
28156 @code{Preelaborate}, then the client should have an
28157 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
28158
28159 @emph{In the case of instantiating a generic subprogram, it is always
28160 sufficient to have only an @code{Elaborate} pragma for the
28161 @code{with}'ed unit.}
28162 @end itemize
28163
28164 @noindent
28165 By following this rule a client is assured that calls and instantiations
28166 can be made without risk of an exception.
28167
28168 In this mode GNAT traces all calls that are potentially made from
28169 elaboration code, and puts in any missing implicit @code{Elaborate}
28170 and @code{Elaborate_All} pragmas.
28171 The advantage of this approach is that no elaboration problems
28172 are possible if the binder can find an elaboration order that is
28173 consistent with these implicit @code{Elaborate} and
28174 @code{Elaborate_All} pragmas. The
28175 disadvantage of this approach is that no such order may exist.
28176
28177 If the binder does not generate any diagnostics, then it means that it has
28178 found an elaboration order that is guaranteed to be safe. However, the binder
28179 may still be relying on implicitly generated @code{Elaborate} and
28180 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
28181 guaranteed.
28182
28183 If it is important to guarantee portability, then the compilations should
28184 use the
28185 @option{-gnatwl}
28186 (warn on elaboration problems) switch. This will cause warning messages
28187 to be generated indicating the missing @code{Elaborate} and
28188 @code{Elaborate_All} pragmas.
28189 Consider the following source program:
28190
28191 @smallexample @c ada
28192 @group
28193 @cartouche
28194 with k;
28195 package j is
28196   m : integer := k.r;
28197 end;
28198 @end cartouche
28199 @end group
28200 @end smallexample
28201
28202 @noindent
28203 where it is clear that there
28204 should be a pragma @code{Elaborate_All}
28205 for unit @code{k}. An implicit pragma will be generated, and it is
28206 likely that the binder will be able to honor it. However, if you want
28207 to port this program to some other Ada compiler than GNAT.
28208 it is safer to include the pragma explicitly in the source. If this
28209 unit is compiled with the
28210 @option{-gnatwl}
28211 switch, then the compiler outputs a warning:
28212
28213 @smallexample
28214 @group
28215 @cartouche
28216 1. with k;
28217 2. package j is
28218 3.   m : integer := k.r;
28219                      |
28220    >>> warning: call to "r" may raise Program_Error
28221    >>> warning: missing pragma Elaborate_All for "k"
28222
28223 4. end;
28224 @end cartouche
28225 @end group
28226 @end smallexample
28227
28228 @noindent
28229 and these warnings can be used as a guide for supplying manually
28230 the missing pragmas. It is usually a bad idea to use this warning
28231 option during development. That's because it will warn you when
28232 you need to put in a pragma, but cannot warn you when it is time
28233 to take it out. So the use of pragma @code{Elaborate_All} may lead to
28234 unnecessary dependencies and even false circularities.
28235
28236 This default mode is more restrictive than the Ada Reference
28237 Manual, and it is possible to construct programs which will compile
28238 using the dynamic model described there, but will run into a
28239 circularity using the safer static model we have described.
28240
28241 Of course any Ada compiler must be able to operate in a mode
28242 consistent with the requirements of the Ada Reference Manual,
28243 and in particular must have the capability of implementing the
28244 standard dynamic model of elaboration with run-time checks.
28245
28246 In GNAT, this standard mode can be achieved either by the use of
28247 the @option{-gnatE} switch on the compiler (@command{gcc} or
28248 @command{gnatmake}) command, or by the use of the configuration pragma:
28249
28250 @smallexample @c ada
28251 pragma Elaboration_Checks (RM);
28252 @end smallexample
28253
28254 @noindent
28255 Either approach will cause the unit affected to be compiled using the
28256 standard dynamic run-time elaboration checks described in the Ada
28257 Reference Manual. The static model is generally preferable, since it
28258 is clearly safer to rely on compile and link time checks rather than
28259 run-time checks. However, in the case of legacy code, it may be
28260 difficult to meet the requirements of the static model. This
28261 issue is further discussed in
28262 @ref{What to Do If the Default Elaboration Behavior Fails}.
28263
28264 Note that the static model provides a strict subset of the allowed
28265 behavior and programs of the Ada Reference Manual, so if you do
28266 adhere to the static model and no circularities exist,
28267 then you are assured that your program will
28268 work using the dynamic model, providing that you remove any
28269 pragma Elaborate statements from the source.
28270
28271 @node Treatment of Pragma Elaborate
28272 @section Treatment of Pragma Elaborate
28273 @cindex Pragma Elaborate
28274
28275 @noindent
28276 The use of @code{pragma Elaborate}
28277 should generally be avoided in Ada 95 and Ada 2005 programs,
28278 since there is no guarantee that transitive calls
28279 will be properly handled. Indeed at one point, this pragma was placed
28280 in Annex J (Obsolescent Features), on the grounds that it is never useful.
28281
28282 Now that's a bit restrictive. In practice, the case in which
28283 @code{pragma Elaborate} is useful is when the caller knows that there
28284 are no transitive calls, or that the called unit contains all necessary
28285 transitive @code{pragma Elaborate} statements, and legacy code often
28286 contains such uses.
28287
28288 Strictly speaking the static mode in GNAT should ignore such pragmas,
28289 since there is no assurance at compile time that the necessary safety
28290 conditions are met. In practice, this would cause GNAT to be incompatible
28291 with correctly written Ada 83 code that had all necessary
28292 @code{pragma Elaborate} statements in place. Consequently, we made the
28293 decision that GNAT in its default mode will believe that if it encounters
28294 a @code{pragma Elaborate} then the programmer knows what they are doing,
28295 and it will trust that no elaboration errors can occur.
28296
28297 The result of this decision is two-fold. First to be safe using the
28298 static mode, you should remove all @code{pragma Elaborate} statements.
28299 Second, when fixing circularities in existing code, you can selectively
28300 use @code{pragma Elaborate} statements to convince the static mode of
28301 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
28302 statement.
28303
28304 When using the static mode with @option{-gnatwl}, any use of
28305 @code{pragma Elaborate} will generate a warning about possible
28306 problems.
28307
28308 @node Elaboration Issues for Library Tasks
28309 @section Elaboration Issues for Library Tasks
28310 @cindex Library tasks, elaboration issues
28311 @cindex Elaboration of library tasks
28312
28313 @noindent
28314 In this section we examine special elaboration issues that arise for
28315 programs that declare library level tasks.
28316
28317 Generally the model of execution of an Ada program is that all units are
28318 elaborated, and then execution of the program starts. However, the
28319 declaration of library tasks definitely does not fit this model. The
28320 reason for this is that library tasks start as soon as they are declared
28321 (more precisely, as soon as the statement part of the enclosing package
28322 body is reached), that is to say before elaboration
28323 of the program is complete. This means that if such a task calls a
28324 subprogram, or an entry in another task, the callee may or may not be
28325 elaborated yet, and in the standard
28326 Reference Manual model of dynamic elaboration checks, you can even
28327 get timing dependent Program_Error exceptions, since there can be
28328 a race between the elaboration code and the task code.
28329
28330 The static model of elaboration in GNAT seeks to avoid all such
28331 dynamic behavior, by being conservative, and the conservative
28332 approach in this particular case is to assume that all the code
28333 in a task body is potentially executed at elaboration time if
28334 a task is declared at the library level.
28335
28336 This can definitely result in unexpected circularities. Consider
28337 the following example
28338
28339 @smallexample @c ada
28340 package Decls is
28341   task Lib_Task is
28342      entry Start;
28343   end Lib_Task;
28344
28345   type My_Int is new Integer;
28346
28347   function Ident (M : My_Int) return My_Int;
28348 end Decls;
28349
28350 with Utils;
28351 package body Decls is
28352   task body Lib_Task is
28353   begin
28354      accept Start;
28355      Utils.Put_Val (2);
28356   end Lib_Task;
28357
28358   function Ident (M : My_Int) return My_Int is
28359   begin
28360      return M;
28361   end Ident;
28362 end Decls;
28363
28364 with Decls;
28365 package Utils is
28366   procedure Put_Val (Arg : Decls.My_Int);
28367 end Utils;
28368
28369 with Text_IO;
28370 package body Utils is
28371   procedure Put_Val (Arg : Decls.My_Int) is
28372   begin
28373      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28374   end Put_Val;
28375 end Utils;
28376
28377 with Decls;
28378 procedure Main is
28379 begin
28380    Decls.Lib_Task.Start;
28381 end;
28382 @end smallexample
28383
28384 @noindent
28385 If the above example is compiled in the default static elaboration
28386 mode, then a circularity occurs. The circularity comes from the call
28387 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
28388 this call occurs in elaboration code, we need an implicit pragma
28389 @code{Elaborate_All} for @code{Utils}. This means that not only must
28390 the spec and body of @code{Utils} be elaborated before the body
28391 of @code{Decls}, but also the spec and body of any unit that is
28392 @code{with'ed} by the body of @code{Utils} must also be elaborated before
28393 the body of @code{Decls}. This is the transitive implication of
28394 pragma @code{Elaborate_All} and it makes sense, because in general
28395 the body of @code{Put_Val} might have a call to something in a
28396 @code{with'ed} unit.
28397
28398 In this case, the body of Utils (actually its spec) @code{with's}
28399 @code{Decls}. Unfortunately this means that the body of @code{Decls}
28400 must be elaborated before itself, in case there is a call from the
28401 body of @code{Utils}.
28402
28403 Here is the exact chain of events we are worrying about:
28404
28405 @enumerate
28406 @item
28407 In the body of @code{Decls} a call is made from within the body of a library
28408 task to a subprogram in the package @code{Utils}. Since this call may
28409 occur at elaboration time (given that the task is activated at elaboration
28410 time), we have to assume the worst, i.e., that the
28411 call does happen at elaboration time.
28412
28413 @item
28414 This means that the body and spec of @code{Util} must be elaborated before
28415 the body of @code{Decls} so that this call does not cause an access before
28416 elaboration.
28417
28418 @item
28419 Within the body of @code{Util}, specifically within the body of
28420 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
28421 by this package.
28422
28423 @item
28424 One such @code{with}'ed package is package @code{Decls}, so there
28425 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
28426 In fact there is such a call in this example, but we would have to
28427 assume that there was such a call even if it were not there, since
28428 we are not supposed to write the body of @code{Decls} knowing what
28429 is in the body of @code{Utils}; certainly in the case of the
28430 static elaboration model, the compiler does not know what is in
28431 other bodies and must assume the worst.
28432
28433 @item
28434 This means that the spec and body of @code{Decls} must also be
28435 elaborated before we elaborate the unit containing the call, but
28436 that unit is @code{Decls}! This means that the body of @code{Decls}
28437 must be elaborated before itself, and that's a circularity.
28438 @end enumerate
28439
28440 @noindent
28441 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
28442 the body of @code{Decls} you will get a true Ada Reference Manual
28443 circularity that makes the program illegal.
28444
28445 In practice, we have found that problems with the static model of
28446 elaboration in existing code often arise from library tasks, so
28447 we must address this particular situation.
28448
28449 Note that if we compile and run the program above, using the dynamic model of
28450 elaboration (that is to say use the @option{-gnatE} switch),
28451 then it compiles, binds,
28452 links, and runs, printing the expected result of 2. Therefore in some sense
28453 the circularity here is only apparent, and we need to capture
28454 the properties of this program that  distinguish it from other library-level
28455 tasks that have real elaboration problems.
28456
28457 We have four possible answers to this question:
28458
28459 @itemize @bullet
28460
28461 @item
28462 Use the dynamic model of elaboration.
28463
28464 If we use the @option{-gnatE} switch, then as noted above, the program works.
28465 Why is this? If we examine the task body, it is apparent that the task cannot
28466 proceed past the
28467 @code{accept} statement until after elaboration has been completed, because
28468 the corresponding entry call comes from the main program, not earlier.
28469 This is why the dynamic model works here. But that's really giving
28470 up on a precise analysis, and we prefer to take this approach only if we cannot
28471 solve the
28472 problem in any other manner. So let us examine two ways to reorganize
28473 the program to avoid the potential elaboration problem.
28474
28475 @item
28476 Split library tasks into separate packages.
28477
28478 Write separate packages, so that library tasks are isolated from
28479 other declarations as much as possible. Let us look at a variation on
28480 the above program.
28481
28482 @smallexample @c ada
28483 package Decls1 is
28484   task Lib_Task is
28485      entry Start;
28486   end Lib_Task;
28487 end Decls1;
28488
28489 with Utils;
28490 package body Decls1 is
28491   task body Lib_Task is
28492   begin
28493      accept Start;
28494      Utils.Put_Val (2);
28495   end Lib_Task;
28496 end Decls1;
28497
28498 package Decls2 is
28499   type My_Int is new Integer;
28500   function Ident (M : My_Int) return My_Int;
28501 end Decls2;
28502
28503 with Utils;
28504 package body Decls2 is
28505   function Ident (M : My_Int) return My_Int is
28506   begin
28507      return M;
28508   end Ident;
28509 end Decls2;
28510
28511 with Decls2;
28512 package Utils is
28513   procedure Put_Val (Arg : Decls2.My_Int);
28514 end Utils;
28515
28516 with Text_IO;
28517 package body Utils is
28518   procedure Put_Val (Arg : Decls2.My_Int) is
28519   begin
28520      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
28521   end Put_Val;
28522 end Utils;
28523
28524 with Decls1;
28525 procedure Main is
28526 begin
28527    Decls1.Lib_Task.Start;
28528 end;
28529 @end smallexample
28530
28531 @noindent
28532 All we have done is to split @code{Decls} into two packages, one
28533 containing the library task, and one containing everything else. Now
28534 there is no cycle, and the program compiles, binds, links and executes
28535 using the default static model of elaboration.
28536
28537 @item
28538 Declare separate task types.
28539
28540 A significant part of the problem arises because of the use of the
28541 single task declaration form. This means that the elaboration of
28542 the task type, and the elaboration of the task itself (i.e.@: the
28543 creation of the task) happen at the same time. A good rule
28544 of style in Ada is to always create explicit task types. By
28545 following the additional step of placing task objects in separate
28546 packages from the task type declaration, many elaboration problems
28547 are avoided. Here is another modified example of the example program:
28548
28549 @smallexample @c ada
28550 package Decls is
28551   task type Lib_Task_Type is
28552      entry Start;
28553   end Lib_Task_Type;
28554
28555   type My_Int is new Integer;
28556
28557   function Ident (M : My_Int) return My_Int;
28558 end Decls;
28559
28560 with Utils;
28561 package body Decls is
28562   task body Lib_Task_Type is
28563   begin
28564      accept Start;
28565      Utils.Put_Val (2);
28566   end Lib_Task_Type;
28567
28568   function Ident (M : My_Int) return My_Int is
28569   begin
28570      return M;
28571   end Ident;
28572 end Decls;
28573
28574 with Decls;
28575 package Utils is
28576   procedure Put_Val (Arg : Decls.My_Int);
28577 end Utils;
28578
28579 with Text_IO;
28580 package body Utils is
28581   procedure Put_Val (Arg : Decls.My_Int) is
28582   begin
28583      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28584   end Put_Val;
28585 end Utils;
28586
28587 with Decls;
28588 package Declst is
28589    Lib_Task : Decls.Lib_Task_Type;
28590 end Declst;
28591
28592 with Declst;
28593 procedure Main is
28594 begin
28595    Declst.Lib_Task.Start;
28596 end;
28597 @end smallexample
28598
28599 @noindent
28600 What we have done here is to replace the @code{task} declaration in
28601 package @code{Decls} with a @code{task type} declaration. Then we
28602 introduce a separate package @code{Declst} to contain the actual
28603 task object. This separates the elaboration issues for
28604 the @code{task type}
28605 declaration, which causes no trouble, from the elaboration issues
28606 of the task object, which is also unproblematic, since it is now independent
28607 of the elaboration of  @code{Utils}.
28608 This separation of concerns also corresponds to
28609 a generally sound engineering principle of separating declarations
28610 from instances. This version of the program also compiles, binds, links,
28611 and executes, generating the expected output.
28612
28613 @item
28614 Use No_Entry_Calls_In_Elaboration_Code restriction.
28615 @cindex No_Entry_Calls_In_Elaboration_Code
28616
28617 The previous two approaches described how a program can be restructured
28618 to avoid the special problems caused by library task bodies. in practice,
28619 however, such restructuring may be difficult to apply to existing legacy code,
28620 so we must consider solutions that do not require massive rewriting.
28621
28622 Let us consider more carefully why our original sample program works
28623 under the dynamic model of elaboration. The reason is that the code
28624 in the task body blocks immediately on the @code{accept}
28625 statement. Now of course there is nothing to prohibit elaboration
28626 code from making entry calls (for example from another library level task),
28627 so we cannot tell in isolation that
28628 the task will not execute the accept statement  during elaboration.
28629
28630 However, in practice it is very unusual to see elaboration code
28631 make any entry calls, and the pattern of tasks starting
28632 at elaboration time and then immediately blocking on @code{accept} or
28633 @code{select} statements is very common. What this means is that
28634 the compiler is being too pessimistic when it analyzes the
28635 whole package body as though it might be executed at elaboration
28636 time.
28637
28638 If we know that the elaboration code contains no entry calls, (a very safe
28639 assumption most of the time, that could almost be made the default
28640 behavior), then we can compile all units of the program under control
28641 of the following configuration pragma:
28642
28643 @smallexample
28644 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28645 @end smallexample
28646
28647 @noindent
28648 This pragma can be placed in the @file{gnat.adc} file in the usual
28649 manner. If we take our original unmodified program and compile it
28650 in the presence of a @file{gnat.adc} containing the above pragma,
28651 then once again, we can compile, bind, link, and execute, obtaining
28652 the expected result. In the presence of this pragma, the compiler does
28653 not trace calls in a task body, that appear after the first @code{accept}
28654 or @code{select} statement, and therefore does not report a potential
28655 circularity in the original program.
28656
28657 The compiler will check to the extent it can that the above
28658 restriction is not violated, but it is not always possible to do a
28659 complete check at compile time, so it is important to use this
28660 pragma only if the stated restriction is in fact met, that is to say
28661 no task receives an entry call before elaboration of all units is completed.
28662
28663 @end itemize
28664
28665 @node Mixing Elaboration Models
28666 @section Mixing Elaboration Models
28667 @noindent
28668 So far, we have assumed that the entire program is either compiled
28669 using the dynamic model or static model, ensuring consistency. It
28670 is possible to mix the two models, but rules have to be followed
28671 if this mixing is done to ensure that elaboration checks are not
28672 omitted.
28673
28674 The basic rule is that @emph{a unit compiled with the static model cannot
28675 be @code{with'ed} by a unit compiled with the dynamic model}. The
28676 reason for this is that in the static model, a unit assumes that
28677 its clients guarantee to use (the equivalent of) pragma
28678 @code{Elaborate_All} so that no elaboration checks are required
28679 in inner subprograms, and this assumption is violated if the
28680 client is compiled with dynamic checks.
28681
28682 The precise rule is as follows. A unit that is compiled with dynamic
28683 checks can only @code{with} a unit that meets at least one of the
28684 following criteria:
28685
28686 @itemize @bullet
28687
28688 @item
28689 The @code{with'ed} unit is itself compiled with dynamic elaboration
28690 checks (that is with the @option{-gnatE} switch.
28691
28692 @item
28693 The @code{with'ed} unit is an internal GNAT implementation unit from
28694 the System, Interfaces, Ada, or GNAT hierarchies.
28695
28696 @item
28697 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
28698
28699 @item
28700 The @code{with'ing} unit (that is the client) has an explicit pragma
28701 @code{Elaborate_All} for the @code{with'ed} unit.
28702
28703 @end itemize
28704
28705 @noindent
28706 If this rule is violated, that is if a unit with dynamic elaboration
28707 checks @code{with's} a unit that does not meet one of the above four
28708 criteria, then the binder (@code{gnatbind}) will issue a warning
28709 similar to that in the following example:
28710
28711 @smallexample
28712 warning: "x.ads" has dynamic elaboration checks and with's
28713 warning:   "y.ads" which has static elaboration checks
28714 @end smallexample
28715
28716 @noindent
28717 These warnings indicate that the rule has been violated, and that as a result
28718 elaboration checks may be missed in the resulting executable file.
28719 This warning may be suppressed using the @option{-ws} binder switch
28720 in the usual manner.
28721
28722 One useful application of this mixing rule is in the case of a subsystem
28723 which does not itself @code{with} units from the remainder of the
28724 application. In this case, the entire subsystem can be compiled with
28725 dynamic checks to resolve a circularity in the subsystem, while
28726 allowing the main application that uses this subsystem to be compiled
28727 using the more reliable default static model.
28728
28729 @node What to Do If the Default Elaboration Behavior Fails
28730 @section What to Do If the Default Elaboration Behavior Fails
28731
28732 @noindent
28733 If the binder cannot find an acceptable order, it outputs detailed
28734 diagnostics. For example:
28735 @smallexample
28736 @group
28737 @iftex
28738 @leftskip=0cm
28739 @end iftex
28740 error: elaboration circularity detected
28741 info:   "proc (body)" must be elaborated before "pack (body)"
28742 info:     reason: Elaborate_All probably needed in unit "pack (body)"
28743 info:     recompile "pack (body)" with -gnatwl
28744 info:                             for full details
28745 info:       "proc (body)"
28746 info:         is needed by its spec:
28747 info:       "proc (spec)"
28748 info:         which is withed by:
28749 info:       "pack (body)"
28750 info:  "pack (body)" must be elaborated before "proc (body)"
28751 info:     reason: pragma Elaborate in unit "proc (body)"
28752 @end group
28753
28754 @end smallexample
28755
28756 @noindent
28757 In this case we have a cycle that the binder cannot break. On the one
28758 hand, there is an explicit pragma Elaborate in @code{proc} for
28759 @code{pack}. This means that the body of @code{pack} must be elaborated
28760 before the body of @code{proc}. On the other hand, there is elaboration
28761 code in @code{pack} that calls a subprogram in @code{proc}. This means
28762 that for maximum safety, there should really be a pragma
28763 Elaborate_All in @code{pack} for @code{proc} which would require that
28764 the body of @code{proc} be elaborated before the body of
28765 @code{pack}. Clearly both requirements cannot be satisfied.
28766 Faced with a circularity of this kind, you have three different options.
28767
28768 @table @asis
28769 @item Fix the program
28770 The most desirable option from the point of view of long-term maintenance
28771 is to rearrange the program so that the elaboration problems are avoided.
28772 One useful technique is to place the elaboration code into separate
28773 child packages. Another is to move some of the initialization code to
28774 explicitly called subprograms, where the program controls the order
28775 of initialization explicitly. Although this is the most desirable option,
28776 it may be impractical and involve too much modification, especially in
28777 the case of complex legacy code.
28778
28779 @item Perform dynamic checks
28780 If the compilations are done using the
28781 @option{-gnatE}
28782 (dynamic elaboration check) switch, then GNAT behaves in a quite different
28783 manner. Dynamic checks are generated for all calls that could possibly result
28784 in raising an exception. With this switch, the compiler does not generate
28785 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
28786 exactly as specified in the @cite{Ada Reference Manual}.
28787 The binder will generate
28788 an executable program that may or may not raise @code{Program_Error}, and then
28789 it is the programmer's job to ensure that it does not raise an exception. Note
28790 that it is important to compile all units with the switch, it cannot be used
28791 selectively.
28792
28793 @item Suppress checks
28794 The drawback of dynamic checks is that they generate a
28795 significant overhead at run time, both in space and time. If you
28796 are absolutely sure that your program cannot raise any elaboration
28797 exceptions, and you still want to use the dynamic elaboration model,
28798 then you can use the configuration pragma
28799 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
28800 example this pragma could be placed in the @file{gnat.adc} file.
28801
28802 @item Suppress checks selectively
28803 When you know that certain calls or instantiations in elaboration code cannot
28804 possibly lead to an elaboration error, and the binder nevertheless complains
28805 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
28806 elaboration circularities, it is possible to remove those warnings locally and
28807 obtain a program that will bind. Clearly this can be unsafe, and it is the
28808 responsibility of the programmer to make sure that the resulting program has no
28809 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
28810 used with different granularity to suppress warnings and break elaboration
28811 circularities:
28812
28813 @itemize @bullet
28814 @item
28815 Place the pragma that names the called subprogram in the declarative part
28816 that contains the call.
28817
28818 @item
28819 Place the pragma in the declarative part, without naming an entity. This
28820 disables warnings on all calls in the corresponding  declarative region.
28821
28822 @item
28823 Place the pragma in the package spec that declares the called subprogram,
28824 and name the subprogram. This disables warnings on all elaboration calls to
28825 that subprogram.
28826
28827 @item
28828 Place the pragma in the package spec that declares the called subprogram,
28829 without naming any entity. This disables warnings on all elaboration calls to
28830 all subprograms declared in this spec.
28831
28832 @item Use Pragma Elaborate
28833 As previously described in section @xref{Treatment of Pragma Elaborate},
28834 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
28835 that no elaboration checks are required on calls to the designated unit.
28836 There may be cases in which the caller knows that no transitive calls
28837 can occur, so that a @code{pragma Elaborate} will be sufficient in a
28838 case where @code{pragma Elaborate_All} would cause a circularity.
28839 @end itemize
28840
28841 @noindent
28842 These five cases are listed in order of decreasing safety, and therefore
28843 require increasing programmer care in their application. Consider the
28844 following program:
28845
28846 @smallexample @c adanocomment
28847 package Pack1 is
28848   function F1 return Integer;
28849   X1 : Integer;
28850 end Pack1;
28851
28852 package Pack2 is
28853   function F2 return Integer;
28854   function Pure (x : integer) return integer;
28855   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
28856   --  pragma Suppress (Elaboration_Check);              -- (4)
28857 end Pack2;
28858
28859 with Pack2;
28860 package body Pack1 is
28861   function F1 return Integer is
28862   begin
28863     return 100;
28864   end F1;
28865   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
28866 begin
28867   declare
28868     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
28869     --  pragma Suppress(Elaboration_Check);             -- (2)
28870   begin
28871     X1 := Pack2.F2 + 1;                --  Elab. call (2)
28872   end;
28873 end Pack1;
28874
28875 with Pack1;
28876 package body Pack2 is
28877   function F2 return Integer is
28878   begin
28879      return Pack1.F1;
28880   end F2;
28881   function Pure (x : integer) return integer is
28882   begin
28883      return x ** 3 - 3 * x;
28884   end;
28885 end Pack2;
28886
28887 with Pack1, Ada.Text_IO;
28888 procedure Proc3 is
28889 begin
28890   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
28891 end Proc3;
28892 @end smallexample
28893 In the absence of any pragmas, an attempt to bind this program produces
28894 the following diagnostics:
28895 @smallexample
28896 @group
28897 @iftex
28898 @leftskip=.5cm
28899 @end iftex
28900 error: elaboration circularity detected
28901 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
28902 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
28903 info:       recompile "pack1 (body)" with -gnatwl for full details
28904 info:          "pack1 (body)"
28905 info:             must be elaborated along with its spec:
28906 info:          "pack1 (spec)"
28907 info:             which is withed by:
28908 info:          "pack2 (body)"
28909 info:             which must be elaborated along with its spec:
28910 info:          "pack2 (spec)"
28911 info:             which is withed by:
28912 info:          "pack1 (body)"
28913 @end group
28914 @end smallexample
28915 The sources of the circularity are the two calls to @code{Pack2.Pure} and
28916 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
28917 F2 is safe, even though F2 calls F1, because the call appears after the
28918 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
28919 remove the warning on the call. It is also possible to use pragma (2)
28920 because there are no other potentially unsafe calls in the block.
28921
28922 @noindent
28923 The call to @code{Pure} is safe because this function does not depend on the
28924 state of @code{Pack2}. Therefore any call to this function is safe, and it
28925 is correct to place pragma (3) in the corresponding package spec.
28926
28927 @noindent
28928 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
28929 warnings on all calls to functions declared therein. Note that this is not
28930 necessarily safe, and requires more detailed examination of the subprogram
28931 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
28932 be already elaborated.
28933 @end table
28934
28935 @noindent
28936 It is hard to generalize on which of these four approaches should be
28937 taken. Obviously if it is possible to fix the program so that the default
28938 treatment works, this is preferable, but this may not always be practical.
28939 It is certainly simple enough to use
28940 @option{-gnatE}
28941 but the danger in this case is that, even if the GNAT binder
28942 finds a correct elaboration order, it may not always do so,
28943 and certainly a binder from another Ada compiler might not. A
28944 combination of testing and analysis (for which the warnings generated
28945 with the
28946 @option{-gnatwl}
28947 switch can be useful) must be used to ensure that the program is free
28948 of errors. One switch that is useful in this testing is the
28949 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
28950 switch for
28951 @code{gnatbind}.
28952 Normally the binder tries to find an order that has the best chance
28953 of avoiding elaboration problems. However, if this switch is used, the binder
28954 plays a devil's advocate role, and tries to choose the order that
28955 has the best chance of failing. If your program works even with this
28956 switch, then it has a better chance of being error free, but this is still
28957 not a guarantee.
28958
28959 For an example of this approach in action, consider the C-tests (executable
28960 tests) from the ACVC suite. If these are compiled and run with the default
28961 treatment, then all but one of them succeed without generating any error
28962 diagnostics from the binder. However, there is one test that fails, and
28963 this is not surprising, because the whole point of this test is to ensure
28964 that the compiler can handle cases where it is impossible to determine
28965 a correct order statically, and it checks that an exception is indeed
28966 raised at run time.
28967
28968 This one test must be compiled and run using the
28969 @option{-gnatE}
28970 switch, and then it passes. Alternatively, the entire suite can
28971 be run using this switch. It is never wrong to run with the dynamic
28972 elaboration switch if your code is correct, and we assume that the
28973 C-tests are indeed correct (it is less efficient, but efficiency is
28974 not a factor in running the ACVC tests.)
28975
28976 @node Elaboration for Access-to-Subprogram Values
28977 @section Elaboration for Access-to-Subprogram Values
28978 @cindex Access-to-subprogram
28979
28980 @noindent
28981 Access-to-subprogram types (introduced in Ada 95) complicate
28982 the handling of elaboration. The trouble is that it becomes
28983 impossible to tell at compile time which procedure
28984 is being called. This means that it is not possible for the binder
28985 to analyze the elaboration requirements in this case.
28986
28987 If at the point at which the access value is created
28988 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
28989 the body of the subprogram is
28990 known to have been elaborated, then the access value is safe, and its use
28991 does not require a check. This may be achieved by appropriate arrangement
28992 of the order of declarations if the subprogram is in the current unit,
28993 or, if the subprogram is in another unit, by using pragma
28994 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
28995 on the referenced unit.
28996
28997 If the referenced body is not known to have been elaborated at the point
28998 the access value is created, then any use of the access value must do a
28999 dynamic check, and this dynamic check will fail and raise a
29000 @code{Program_Error} exception if the body has not been elaborated yet.
29001 GNAT will generate the necessary checks, and in addition, if the
29002 @option{-gnatwl}
29003 switch is set, will generate warnings that such checks are required.
29004
29005 The use of dynamic dispatching for tagged types similarly generates
29006 a requirement for dynamic checks, and premature calls to any primitive
29007 operation of a tagged type before the body of the operation has been
29008 elaborated, will result in the raising of @code{Program_Error}.
29009
29010 @node Summary of Procedures for Elaboration Control
29011 @section Summary of Procedures for Elaboration Control
29012 @cindex Elaboration control
29013
29014 @noindent
29015 First, compile your program with the default options, using none of
29016 the special elaboration control switches. If the binder successfully
29017 binds your program, then you can be confident that, apart from issues
29018 raised by the use of access-to-subprogram types and dynamic dispatching,
29019 the program is free of elaboration errors. If it is important that the
29020 program be portable, then use the
29021 @option{-gnatwl}
29022 switch to generate warnings about missing @code{Elaborate} or
29023 @code{Elaborate_All} pragmas, and supply the missing pragmas.
29024
29025 If the program fails to bind using the default static elaboration
29026 handling, then you can fix the program to eliminate the binder
29027 message, or recompile the entire program with the
29028 @option{-gnatE} switch to generate dynamic elaboration checks,
29029 and, if you are sure there really are no elaboration problems,
29030 use a global pragma @code{Suppress (Elaboration_Check)}.
29031
29032 @node Other Elaboration Order Considerations
29033 @section Other Elaboration Order Considerations
29034 @noindent
29035 This section has been entirely concerned with the issue of finding a valid
29036 elaboration order, as defined by the Ada Reference Manual. In a case
29037 where several elaboration orders are valid, the task is to find one
29038 of the possible valid elaboration orders (and the static model in GNAT
29039 will ensure that this is achieved).
29040
29041 The purpose of the elaboration rules in the Ada Reference Manual is to
29042 make sure that no entity is accessed before it has been elaborated. For
29043 a subprogram, this means that the spec and body must have been elaborated
29044 before the subprogram is called. For an object, this means that the object
29045 must have been elaborated before its value is read or written. A violation
29046 of either of these two requirements is an access before elaboration order,
29047 and this section has been all about avoiding such errors.
29048
29049 In the case where more than one order of elaboration is possible, in the
29050 sense that access before elaboration errors are avoided, then any one of
29051 the orders is ``correct'' in the sense that it meets the requirements of
29052 the Ada Reference Manual, and no such error occurs.
29053
29054 However, it may be the case for a given program, that there are
29055 constraints on the order of elaboration that come not from consideration
29056 of avoiding elaboration errors, but rather from extra-lingual logic
29057 requirements. Consider this example:
29058
29059 @smallexample @c ada
29060 with Init_Constants;
29061 package Constants is
29062    X : Integer := 0;
29063    Y : Integer := 0;
29064 end Constants;
29065
29066 package Init_Constants is
29067    procedure P; -- require a body
29068 end Init_Constants;
29069
29070 with Constants;
29071 package body Init_Constants is
29072    procedure P is begin null; end;
29073 begin
29074    Constants.X := 3;
29075    Constants.Y := 4;
29076 end Init_Constants;
29077
29078 with Constants;
29079 package Calc is
29080    Z : Integer := Constants.X + Constants.Y;
29081 end Calc;
29082
29083 with Calc;
29084 with Text_IO; use Text_IO;
29085 procedure Main is
29086 begin
29087    Put_Line (Calc.Z'Img);
29088 end Main;
29089 @end smallexample
29090
29091 @noindent
29092 In this example, there is more than one valid order of elaboration. For
29093 example both the following are correct orders:
29094
29095 @smallexample
29096 Init_Constants spec
29097 Constants spec
29098 Calc spec
29099 Init_Constants body
29100 Main body
29101
29102   and
29103
29104 Init_Constants spec
29105 Init_Constants body
29106 Constants spec
29107 Calc spec
29108 Main body
29109 @end smallexample
29110
29111 @noindent
29112 There is no language rule to prefer one or the other, both are correct
29113 from an order of elaboration point of view. But the programmatic effects
29114 of the two orders are very different. In the first, the elaboration routine
29115 of @code{Calc} initializes @code{Z} to zero, and then the main program
29116 runs with this value of zero. But in the second order, the elaboration
29117 routine of @code{Calc} runs after the body of Init_Constants has set
29118 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
29119 runs.
29120
29121 One could perhaps by applying pretty clever non-artificial intelligence
29122 to the situation guess that it is more likely that the second order of
29123 elaboration is the one desired, but there is no formal linguistic reason
29124 to prefer one over the other. In fact in this particular case, GNAT will
29125 prefer the second order, because of the rule that bodies are elaborated
29126 as soon as possible, but it's just luck that this is what was wanted
29127 (if indeed the second order was preferred).
29128
29129 If the program cares about the order of elaboration routines in a case like
29130 this, it is important to specify the order required. In this particular
29131 case, that could have been achieved by adding to the spec of Calc:
29132
29133 @smallexample @c ada
29134 pragma Elaborate_All (Constants);
29135 @end smallexample
29136
29137 @noindent
29138 which requires that the body (if any) and spec of @code{Constants},
29139 as well as the body and spec of any unit @code{with}'ed by
29140 @code{Constants} be elaborated before @code{Calc} is elaborated.
29141
29142 Clearly no automatic method can always guess which alternative you require,
29143 and if you are working with legacy code that had constraints of this kind
29144 which were not properly specified by adding @code{Elaborate} or
29145 @code{Elaborate_All} pragmas, then indeed it is possible that two different
29146 compilers can choose different orders.
29147
29148 However, GNAT does attempt to diagnose the common situation where there
29149 are uninitialized variables in the visible part of a package spec, and the
29150 corresponding package body has an elaboration block that directly or
29151 indirectly initialized one or more of these variables. This is the situation
29152 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
29153 a warning that suggests this addition if it detects this situation.
29154
29155 The @code{gnatbind}
29156 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
29157 out problems. This switch causes bodies to be elaborated as late as possible
29158 instead of as early as possible. In the example above, it would have forced
29159 the choice of the first elaboration order. If you get different results
29160 when using this switch, and particularly if one set of results is right,
29161 and one is wrong as far as you are concerned, it shows that you have some
29162 missing @code{Elaborate} pragmas. For the example above, we have the
29163 following output:
29164
29165 @smallexample
29166 gnatmake -f -q main
29167 main
29168  7
29169 gnatmake -f -q main -bargs -p
29170 main
29171  0
29172 @end smallexample
29173
29174 @noindent
29175 It is of course quite unlikely that both these results are correct, so
29176 it is up to you in a case like this to investigate the source of the
29177 difference, by looking at the two elaboration orders that are chosen,
29178 and figuring out which is correct, and then adding the necessary
29179 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
29180
29181
29182
29183 @c *******************************
29184 @node Conditional Compilation
29185 @appendix Conditional Compilation
29186 @c *******************************
29187 @cindex Conditional compilation
29188
29189 @noindent
29190 It is often necessary to arrange for a single source program
29191 to serve multiple purposes, where it is compiled in different
29192 ways to achieve these different goals. Some examples of the
29193 need for this feature are
29194
29195 @itemize @bullet
29196 @item  Adapting a program to a different hardware environment
29197 @item  Adapting a program to a different target architecture
29198 @item  Turning debugging features on and off
29199 @item  Arranging for a program to compile with different compilers
29200 @end itemize
29201
29202 @noindent
29203 In C, or C++, the typical approach would be to use the preprocessor
29204 that is defined as part of the language. The Ada language does not
29205 contain such a feature. This is not an oversight, but rather a very
29206 deliberate design decision, based on the experience that overuse of
29207 the preprocessing features in C and C++ can result in programs that
29208 are extremely difficult to maintain. For example, if we have ten
29209 switches that can be on or off, this means that there are a thousand
29210 separate programs, any one of which might not even be syntactically
29211 correct, and even if syntactically correct, the resulting program
29212 might not work correctly. Testing all combinations can quickly become
29213 impossible.
29214
29215 Nevertheless, the need to tailor programs certainly exists, and in
29216 this Appendix we will discuss how this can
29217 be achieved using Ada in general, and GNAT in particular.
29218
29219 @menu
29220 * Use of Boolean Constants::
29221 * Debugging - A Special Case::
29222 * Conditionalizing Declarations::
29223 * Use of Alternative Implementations::
29224 * Preprocessing::
29225 @end menu
29226
29227 @node Use of Boolean Constants
29228 @section Use of Boolean Constants
29229
29230 @noindent
29231 In the case where the difference is simply which code
29232 sequence is executed, the cleanest solution is to use Boolean
29233 constants to control which code is executed.
29234
29235 @smallexample @c ada
29236 @group
29237 FP_Initialize_Required : constant Boolean := True;
29238 @dots{}
29239 if FP_Initialize_Required then
29240 @dots{}
29241 end if;
29242 @end group
29243 @end smallexample
29244
29245 @noindent
29246 Not only will the code inside the @code{if} statement not be executed if
29247 the constant Boolean is @code{False}, but it will also be completely
29248 deleted from the program.
29249 However, the code is only deleted after the @code{if} statement
29250 has been checked for syntactic and semantic correctness.
29251 (In contrast, with preprocessors the code is deleted before the
29252 compiler ever gets to see it, so it is not checked until the switch
29253 is turned on.)
29254 @cindex Preprocessors (contrasted with conditional compilation)
29255
29256 Typically the Boolean constants will be in a separate package,
29257 something like:
29258
29259 @smallexample @c ada
29260 @group
29261 package Config is
29262    FP_Initialize_Required : constant Boolean := True;
29263    Reset_Available        : constant Boolean := False;
29264    @dots{}
29265 end Config;
29266 @end group
29267 @end smallexample
29268
29269 @noindent
29270 The @code{Config} package exists in multiple forms for the various targets,
29271 with an appropriate script selecting the version of @code{Config} needed.
29272 Then any other unit requiring conditional compilation can do a @code{with}
29273 of @code{Config} to make the constants visible.
29274
29275
29276 @node Debugging - A Special Case
29277 @section Debugging - A Special Case
29278
29279 @noindent
29280 A common use of conditional code is to execute statements (for example
29281 dynamic checks, or output of intermediate results) under control of a
29282 debug switch, so that the debugging behavior can be turned on and off.
29283 This can be done using a Boolean constant to control whether the code
29284 is active:
29285
29286 @smallexample @c ada
29287 @group
29288 if Debugging then
29289    Put_Line ("got to the first stage!");
29290 end if;
29291 @end group
29292 @end smallexample
29293
29294 @noindent
29295 or
29296
29297 @smallexample @c ada
29298 @group
29299 if Debugging and then Temperature > 999.0 then
29300    raise Temperature_Crazy;
29301 end if;
29302 @end group
29303 @end smallexample
29304
29305 @noindent
29306 Since this is a common case, there are special features to deal with
29307 this in a convenient manner. For the case of tests, Ada 2005 has added
29308 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
29309 @cindex pragma @code{Assert}
29310 on the @code{Assert} pragma that has always been available in GNAT, so this
29311 feature may be used with GNAT even if you are not using Ada 2005 features.
29312 The use of pragma @code{Assert} is described in
29313 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
29314 example, the last test could be written:
29315
29316 @smallexample @c ada
29317 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
29318 @end smallexample
29319
29320 @noindent
29321 or simply
29322
29323 @smallexample @c ada
29324 pragma Assert (Temperature <= 999.0);
29325 @end smallexample
29326
29327 @noindent
29328 In both cases, if assertions are active and the temperature is excessive,
29329 the exception @code{Assert_Failure} will be raised, with the given string in
29330 the first case or a string indicating the location of the pragma in the second
29331 case used as the exception message.
29332
29333 You can turn assertions on and off by using the @code{Assertion_Policy}
29334 pragma.
29335 @cindex pragma @code{Assertion_Policy}
29336 This is an Ada 2005 pragma which is implemented in all modes by
29337 GNAT, but only in the latest versions of GNAT which include Ada 2005
29338 capability. Alternatively, you can use the @option{-gnata} switch
29339 @cindex @option{-gnata} switch
29340 to enable assertions from the command line (this is recognized by all versions
29341 of GNAT).
29342
29343 For the example above with the @code{Put_Line}, the GNAT-specific pragma
29344 @code{Debug} can be used:
29345 @cindex pragma @code{Debug}
29346
29347 @smallexample @c ada
29348 pragma Debug (Put_Line ("got to the first stage!"));
29349 @end smallexample
29350
29351 @noindent
29352 If debug pragmas are enabled, the argument, which must be of the form of
29353 a procedure call, is executed (in this case, @code{Put_Line} will be called).
29354 Only one call can be present, but of course a special debugging procedure
29355 containing any code you like can be included in the program and then
29356 called in a pragma @code{Debug} argument as needed.
29357
29358 One advantage of pragma @code{Debug} over the @code{if Debugging then}
29359 construct is that pragma @code{Debug} can appear in declarative contexts,
29360 such as at the very beginning of a procedure, before local declarations have
29361 been elaborated.
29362
29363 Debug pragmas are enabled using either the @option{-gnata} switch that also
29364 controls assertions, or with a separate Debug_Policy pragma.
29365 @cindex pragma @code{Debug_Policy}
29366 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
29367 in Ada 95 and Ada 83 programs as well), and is analogous to
29368 pragma @code{Assertion_Policy} to control assertions.
29369
29370 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
29371 and thus they can appear in @file{gnat.adc} if you are not using a
29372 project file, or in the file designated to contain configuration pragmas
29373 in a project file.
29374 They then apply to all subsequent compilations. In practice the use of
29375 the @option{-gnata} switch is often the most convenient method of controlling
29376 the status of these pragmas.
29377
29378 Note that a pragma is not a statement, so in contexts where a statement
29379 sequence is required, you can't just write a pragma on its own. You have
29380 to add a @code{null} statement.
29381
29382 @smallexample @c ada
29383 @group
29384 if @dots{} then
29385    @dots{} -- some statements
29386 else
29387    pragma Assert (Num_Cases < 10);
29388    null;
29389 end if;
29390 @end group
29391 @end smallexample
29392
29393
29394 @node Conditionalizing Declarations
29395 @section Conditionalizing Declarations
29396
29397 @noindent
29398 In some cases, it may be necessary to conditionalize declarations to meet
29399 different requirements. For example we might want a bit string whose length
29400 is set to meet some hardware message requirement.
29401
29402 In some cases, it may be possible to do this using declare blocks controlled
29403 by conditional constants:
29404
29405 @smallexample @c ada
29406 @group
29407 if Small_Machine then
29408    declare
29409       X : Bit_String (1 .. 10);
29410    begin
29411       @dots{}
29412    end;
29413 else
29414    declare
29415       X : Large_Bit_String (1 .. 1000);
29416    begin
29417       @dots{}
29418    end;
29419 end if;
29420 @end group
29421 @end smallexample
29422
29423 @noindent
29424 Note that in this approach, both declarations are analyzed by the
29425 compiler so this can only be used where both declarations are legal,
29426 even though one of them will not be used.
29427
29428 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
29429 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
29430 that are parameterized by these constants. For example
29431
29432 @smallexample @c ada
29433 @group
29434 for Rec use
29435   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
29436 end record;
29437 @end group
29438 @end smallexample
29439
29440 @noindent
29441 If @code{Bits_Per_Word} is set to 32, this generates either
29442
29443 @smallexample @c ada
29444 @group
29445 for Rec use
29446   Field1 at 0 range 0 .. 32;
29447 end record;
29448 @end group
29449 @end smallexample
29450
29451 @noindent
29452 for the big endian case, or
29453
29454 @smallexample @c ada
29455 @group
29456 for Rec use record
29457   Field1 at 0 range 10 .. 32;
29458 end record;
29459 @end group
29460 @end smallexample
29461
29462 @noindent
29463 for the little endian case. Since a powerful subset of Ada expression
29464 notation is usable for creating static constants, clever use of this
29465 feature can often solve quite difficult problems in conditionalizing
29466 compilation (note incidentally that in Ada 95, the little endian
29467 constant was introduced as @code{System.Default_Bit_Order}, so you do not
29468 need to define this one yourself).
29469
29470
29471 @node Use of Alternative Implementations
29472 @section Use of Alternative Implementations
29473
29474 @noindent
29475 In some cases, none of the approaches described above are adequate. This
29476 can occur for example if the set of declarations required is radically
29477 different for two different configurations.
29478
29479 In this situation, the official Ada way of dealing with conditionalizing
29480 such code is to write separate units for the different cases. As long as
29481 this does not result in excessive duplication of code, this can be done
29482 without creating maintenance problems. The approach is to share common
29483 code as far as possible, and then isolate the code and declarations
29484 that are different. Subunits are often a convenient method for breaking
29485 out a piece of a unit that is to be conditionalized, with separate files
29486 for different versions of the subunit for different targets, where the
29487 build script selects the right one to give to the compiler.
29488 @cindex Subunits (and conditional compilation)
29489
29490 As an example, consider a situation where a new feature in Ada 2005
29491 allows something to be done in a really nice way. But your code must be able
29492 to compile with an Ada 95 compiler. Conceptually you want to say:
29493
29494 @smallexample @c ada
29495 @group
29496 if Ada_2005 then
29497    @dots{} neat Ada 2005 code
29498 else
29499    @dots{} not quite as neat Ada 95 code
29500 end if;
29501 @end group
29502 @end smallexample
29503
29504 @noindent
29505 where @code{Ada_2005} is a Boolean constant.
29506
29507 But this won't work when @code{Ada_2005} is set to @code{False},
29508 since the @code{then} clause will be illegal for an Ada 95 compiler.
29509 (Recall that although such unreachable code would eventually be deleted
29510 by the compiler, it still needs to be legal.  If it uses features
29511 introduced in Ada 2005, it will be illegal in Ada 95.)
29512
29513 So instead we write
29514
29515 @smallexample @c ada
29516 procedure Insert is separate;
29517 @end smallexample
29518
29519 @noindent
29520 Then we have two files for the subunit @code{Insert}, with the two sets of
29521 code.
29522 If the package containing this is called @code{File_Queries}, then we might
29523 have two files
29524
29525 @itemize @bullet
29526 @item    @file{file_queries-insert-2005.adb}
29527 @item    @file{file_queries-insert-95.adb}
29528 @end itemize
29529
29530 @noindent
29531 and the build script renames the appropriate file to
29532
29533 @smallexample
29534 file_queries-insert.adb
29535 @end smallexample
29536
29537 @noindent
29538 and then carries out the compilation.
29539
29540 This can also be done with project files' naming schemes. For example:
29541
29542 @smallexample @c project
29543 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
29544 @end smallexample
29545
29546 @noindent
29547 Note also that with project files it is desirable to use a different extension
29548 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
29549 conflict may arise through another commonly used feature: to declare as part
29550 of the project a set of directories containing all the sources obeying the
29551 default naming scheme.
29552
29553 The use of alternative units is certainly feasible in all situations,
29554 and for example the Ada part of the GNAT run-time is conditionalized
29555 based on the target architecture using this approach. As a specific example,
29556 consider the implementation of the AST feature in VMS. There is one
29557 spec:
29558
29559 @smallexample
29560 s-asthan.ads
29561 @end smallexample
29562
29563 @noindent
29564 which is the same for all architectures, and three bodies:
29565
29566 @table @file
29567 @item    s-asthan.adb
29568 used for all non-VMS operating systems
29569 @item    s-asthan-vms-alpha.adb
29570 used for VMS on the Alpha
29571 @item    s-asthan-vms-ia64.adb
29572 used for VMS on the ia64
29573 @end table
29574
29575 @noindent
29576 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
29577 this operating system feature is not available, and the two remaining
29578 versions interface with the corresponding versions of VMS to provide
29579 VMS-compatible AST handling. The GNAT build script knows the architecture
29580 and operating system, and automatically selects the right version,
29581 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
29582
29583 Another style for arranging alternative implementations is through Ada's
29584 access-to-subprogram facility.
29585 In case some functionality is to be conditionally included,
29586 you can declare an access-to-procedure variable @code{Ref} that is initialized
29587 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
29588 when appropriate.
29589 In some library package, set @code{Ref} to @code{Proc'Access} for some
29590 procedure @code{Proc} that performs the relevant processing.
29591 The initialization only occurs if the library package is included in the
29592 program.
29593 The same idea can also be implemented using tagged types and dispatching
29594 calls.
29595
29596
29597 @node Preprocessing
29598 @section Preprocessing
29599 @cindex Preprocessing
29600
29601 @noindent
29602 Although it is quite possible to conditionalize code without the use of
29603 C-style preprocessing, as described earlier in this section, it is
29604 nevertheless convenient in some cases to use the C approach. Moreover,
29605 older Ada compilers have often provided some preprocessing capability,
29606 so legacy code may depend on this approach, even though it is not
29607 standard.
29608
29609 To accommodate such use, GNAT provides a preprocessor (modeled to a large
29610 extent on the various preprocessors that have been used
29611 with legacy code on other compilers, to enable easier transition).
29612
29613 The preprocessor may be used in two separate modes. It can be used quite
29614 separately from the compiler, to generate a separate output source file
29615 that is then fed to the compiler as a separate step. This is the
29616 @code{gnatprep} utility, whose use is fully described in
29617 @ref{Preprocessing Using gnatprep}.
29618 @cindex @code{gnatprep}
29619
29620 The preprocessing language allows such constructs as
29621
29622 @smallexample
29623 @group
29624 #if DEBUG or PRIORITY > 4 then
29625    bunch of declarations
29626 #else
29627    completely different bunch of declarations
29628 #end if;
29629 @end group
29630 @end smallexample
29631
29632 @noindent
29633 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
29634 defined either on the command line or in a separate file.
29635
29636 The other way of running the preprocessor is even closer to the C style and
29637 often more convenient. In this approach the preprocessing is integrated into
29638 the compilation process. The compiler is fed the preprocessor input which
29639 includes @code{#if} lines etc, and then the compiler carries out the
29640 preprocessing internally and processes the resulting output.
29641 For more details on this approach, see @ref{Integrated Preprocessing}.
29642
29643
29644 @c *******************************
29645 @node Inline Assembler
29646 @appendix Inline Assembler
29647 @c *******************************
29648
29649 @noindent
29650 If you need to write low-level software that interacts directly
29651 with the hardware, Ada provides two ways to incorporate assembly
29652 language code into your program.  First, you can import and invoke
29653 external routines written in assembly language, an Ada feature fully
29654 supported by GNAT@.  However, for small sections of code it may be simpler
29655 or more efficient to include assembly language statements directly
29656 in your Ada source program, using the facilities of the implementation-defined
29657 package @code{System.Machine_Code}, which incorporates the gcc
29658 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
29659 including the following:
29660
29661 @itemize @bullet
29662 @item No need to use non-Ada tools
29663 @item Consistent interface over different targets
29664 @item Automatic usage of the proper calling conventions
29665 @item Access to Ada constants and variables
29666 @item Definition of intrinsic routines
29667 @item Possibility of inlining a subprogram comprising assembler code
29668 @item Code optimizer can take Inline Assembler code into account
29669 @end itemize
29670
29671 This chapter presents a series of examples to show you how to use
29672 the Inline Assembler.  Although it focuses on the Intel x86,
29673 the general approach applies also to other processors.
29674 It is assumed that you are familiar with Ada
29675 and with assembly language programming.
29676
29677 @menu
29678 * Basic Assembler Syntax::
29679 * A Simple Example of Inline Assembler::
29680 * Output Variables in Inline Assembler::
29681 * Input Variables in Inline Assembler::
29682 * Inlining Inline Assembler Code::
29683 * Other Asm Functionality::
29684 @end menu
29685
29686 @c ---------------------------------------------------------------------------
29687 @node Basic Assembler Syntax
29688 @section Basic Assembler Syntax
29689
29690 @noindent
29691 The assembler used by GNAT and gcc is based not on the Intel assembly
29692 language, but rather on a language that descends from the AT&T Unix
29693 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
29694 The following table summarizes the main features of @emph{as} syntax
29695 and points out the differences from the Intel conventions.
29696 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
29697 pre-processor) documentation for further information.
29698
29699 @table @asis
29700 @item Register names
29701 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
29702 @*
29703 Intel: No extra punctuation; for example @code{eax}
29704
29705 @item Immediate operand
29706 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
29707 @*
29708 Intel: No extra punctuation; for example @code{4}
29709
29710 @item Address
29711 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
29712 @*
29713 Intel: No extra punctuation; for example @code{loc}
29714
29715 @item Memory contents
29716 gcc / @emph{as}: No extra punctuation; for example @code{loc}
29717 @*
29718 Intel: Square brackets; for example @code{[loc]}
29719
29720 @item Register contents
29721 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
29722 @*
29723 Intel: Square brackets; for example @code{[eax]}
29724
29725 @item Hexadecimal numbers
29726 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
29727 @*
29728 Intel: Trailing ``h''; for example @code{A0h}
29729
29730 @item Operand size
29731 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
29732 a 16-bit word
29733 @*
29734 Intel: Implicit, deduced by assembler; for example @code{mov}
29735
29736 @item Instruction repetition
29737 gcc / @emph{as}: Split into two lines; for example
29738 @*
29739 @code{rep}
29740 @*
29741 @code{stosl}
29742 @*
29743 Intel: Keep on one line; for example @code{rep stosl}
29744
29745 @item Order of operands
29746 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
29747 @*
29748 Intel: Destination first; for example @code{mov eax, 4}
29749 @end table
29750
29751 @c ---------------------------------------------------------------------------
29752 @node A Simple Example of Inline Assembler
29753 @section A Simple Example of Inline Assembler
29754
29755 @noindent
29756 The following example will generate a single assembly language statement,
29757 @code{nop}, which does nothing.  Despite its lack of run-time effect,
29758 the example will be useful in illustrating the basics of
29759 the Inline Assembler facility.
29760
29761 @smallexample @c ada
29762 @group
29763 with System.Machine_Code; use System.Machine_Code;
29764 procedure Nothing is
29765 begin
29766    Asm ("nop");
29767 end Nothing;
29768 @end group
29769 @end smallexample
29770
29771 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
29772 here it takes one parameter, a @emph{template string} that must be a static
29773 expression and that will form the generated instruction.
29774 @code{Asm} may be regarded as a compile-time procedure that parses
29775 the template string and additional parameters (none here),
29776 from which it generates a sequence of assembly language instructions.
29777
29778 The examples in this chapter will illustrate several of the forms
29779 for invoking @code{Asm}; a complete specification of the syntax
29780 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
29781 Manual}.
29782
29783 Under the standard GNAT conventions, the @code{Nothing} procedure
29784 should be in a file named @file{nothing.adb}.
29785 You can build the executable in the usual way:
29786 @smallexample
29787 gnatmake nothing
29788 @end smallexample
29789 However, the interesting aspect of this example is not its run-time behavior
29790 but rather the generated assembly code.
29791 To see this output, invoke the compiler as follows:
29792 @smallexample
29793    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
29794 @end smallexample
29795 where the options are:
29796
29797 @table @code
29798 @item -c
29799 compile only (no bind or link)
29800 @item -S
29801 generate assembler listing
29802 @item -fomit-frame-pointer
29803 do not set up separate stack frames
29804 @item -gnatp
29805 do not add runtime checks
29806 @end table
29807
29808 This gives a human-readable assembler version of the code. The resulting
29809 file will have the same name as the Ada source file, but with a @code{.s}
29810 extension. In our example, the file @file{nothing.s} has the following
29811 contents:
29812
29813 @smallexample
29814 @group
29815 .file "nothing.adb"
29816 gcc2_compiled.:
29817 ___gnu_compiled_ada:
29818 .text
29819    .align 4
29820 .globl __ada_nothing
29821 __ada_nothing:
29822 #APP
29823    nop
29824 #NO_APP
29825    jmp L1
29826    .align 2,0x90
29827 L1:
29828    ret
29829 @end group
29830 @end smallexample
29831
29832 The assembly code you included is clearly indicated by
29833 the compiler, between the @code{#APP} and @code{#NO_APP}
29834 delimiters. The character before the 'APP' and 'NOAPP'
29835 can differ on different targets. For example, GNU/Linux uses '#APP' while
29836 on NT you will see '/APP'.
29837
29838 If you make a mistake in your assembler code (such as using the
29839 wrong size modifier, or using a wrong operand for the instruction) GNAT
29840 will report this error in a temporary file, which will be deleted when
29841 the compilation is finished.  Generating an assembler file will help
29842 in such cases, since you can assemble this file separately using the
29843 @emph{as} assembler that comes with gcc.
29844
29845 Assembling the file using the command
29846
29847 @smallexample
29848 as @file{nothing.s}
29849 @end smallexample
29850 @noindent
29851 will give you error messages whose lines correspond to the assembler
29852 input file, so you can easily find and correct any mistakes you made.
29853 If there are no errors, @emph{as} will generate an object file
29854 @file{nothing.out}.
29855
29856 @c ---------------------------------------------------------------------------
29857 @node Output Variables in Inline Assembler
29858 @section Output Variables in Inline Assembler
29859
29860 @noindent
29861 The examples in this section, showing how to access the processor flags,
29862 illustrate how to specify the destination operands for assembly language
29863 statements.
29864
29865 @smallexample @c ada
29866 @group
29867 with Interfaces; use Interfaces;
29868 with Ada.Text_IO; use Ada.Text_IO;
29869 with System.Machine_Code; use System.Machine_Code;
29870 procedure Get_Flags is
29871    Flags : Unsigned_32;
29872    use ASCII;
29873 begin
29874    Asm ("pushfl"          & LF & HT & -- push flags on stack
29875         "popl %%eax"      & LF & HT & -- load eax with flags
29876         "movl %%eax, %0",             -- store flags in variable
29877         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29878    Put_Line ("Flags register:" & Flags'Img);
29879 end Get_Flags;
29880 @end group
29881 @end smallexample
29882
29883 In order to have a nicely aligned assembly listing, we have separated
29884 multiple assembler statements in the Asm template string with linefeed
29885 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
29886 The resulting section of the assembly output file is:
29887
29888 @smallexample
29889 @group
29890 #APP
29891    pushfl
29892    popl %eax
29893    movl %eax, -40(%ebp)
29894 #NO_APP
29895 @end group
29896 @end smallexample
29897
29898 It would have been legal to write the Asm invocation as:
29899
29900 @smallexample
29901 Asm ("pushfl popl %%eax movl %%eax, %0")
29902 @end smallexample
29903
29904 but in the generated assembler file, this would come out as:
29905
29906 @smallexample
29907 #APP
29908    pushfl popl %eax movl %eax, -40(%ebp)
29909 #NO_APP
29910 @end smallexample
29911
29912 which is not so convenient for the human reader.
29913
29914 We use Ada comments
29915 at the end of each line to explain what the assembler instructions
29916 actually do.  This is a useful convention.
29917
29918 When writing Inline Assembler instructions, you need to precede each register
29919 and variable name with a percent sign.  Since the assembler already requires
29920 a percent sign at the beginning of a register name, you need two consecutive
29921 percent signs for such names in the Asm template string, thus @code{%%eax}.
29922 In the generated assembly code, one of the percent signs will be stripped off.
29923
29924 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
29925 variables: operands you later define using @code{Input} or @code{Output}
29926 parameters to @code{Asm}.
29927 An output variable is illustrated in
29928 the third statement in the Asm template string:
29929 @smallexample
29930 movl %%eax, %0
29931 @end smallexample
29932 The intent is to store the contents of the eax register in a variable that can
29933 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
29934 necessarily work, since the compiler might optimize by using a register
29935 to hold Flags, and the expansion of the @code{movl} instruction would not be
29936 aware of this optimization.  The solution is not to store the result directly
29937 but rather to advise the compiler to choose the correct operand form;
29938 that is the purpose of the @code{%0} output variable.
29939
29940 Information about the output variable is supplied in the @code{Outputs}
29941 parameter to @code{Asm}:
29942 @smallexample
29943 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29944 @end smallexample
29945
29946 The output is defined by the @code{Asm_Output} attribute of the target type;
29947 the general format is
29948 @smallexample
29949 Type'Asm_Output (constraint_string, variable_name)
29950 @end smallexample
29951
29952 The constraint string directs the compiler how
29953 to store/access the associated variable.  In the example
29954 @smallexample
29955 Unsigned_32'Asm_Output ("=m", Flags);
29956 @end smallexample
29957 the @code{"m"} (memory) constraint tells the compiler that the variable
29958 @code{Flags} should be stored in a memory variable, thus preventing
29959 the optimizer from keeping it in a register.  In contrast,
29960 @smallexample
29961 Unsigned_32'Asm_Output ("=r", Flags);
29962 @end smallexample
29963 uses the @code{"r"} (register) constraint, telling the compiler to
29964 store the variable in a register.
29965
29966 If the constraint is preceded by the equal character (@strong{=}), it tells
29967 the compiler that the variable will be used to store data into it.
29968
29969 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
29970 allowing the optimizer to choose whatever it deems best.
29971
29972 There are a fairly large number of constraints, but the ones that are
29973 most useful (for the Intel x86 processor) are the following:
29974
29975 @table @code
29976 @item =
29977 output constraint
29978 @item g
29979 global (i.e.@: can be stored anywhere)
29980 @item m
29981 in memory
29982 @item I
29983 a constant
29984 @item a
29985 use eax
29986 @item b
29987 use ebx
29988 @item c
29989 use ecx
29990 @item d
29991 use edx
29992 @item S
29993 use esi
29994 @item D
29995 use edi
29996 @item r
29997 use one of eax, ebx, ecx or edx
29998 @item q
29999 use one of eax, ebx, ecx, edx, esi or edi
30000 @end table
30001
30002 The full set of constraints is described in the gcc and @emph{as}
30003 documentation; note that it is possible to combine certain constraints
30004 in one constraint string.
30005
30006 You specify the association of an output variable with an assembler operand
30007 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
30008 integer.  Thus in
30009 @smallexample @c ada
30010 @group
30011 Asm ("pushfl"          & LF & HT & -- push flags on stack
30012      "popl %%eax"      & LF & HT & -- load eax with flags
30013      "movl %%eax, %0",             -- store flags in variable
30014      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30015 @end group
30016 @end smallexample
30017 @noindent
30018 @code{%0} will be replaced in the expanded code by the appropriate operand,
30019 whatever
30020 the compiler decided for the @code{Flags} variable.
30021
30022 In general, you may have any number of output variables:
30023 @itemize @bullet
30024 @item
30025 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
30026 @item
30027 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
30028 of @code{Asm_Output} attributes
30029 @end itemize
30030
30031 For example:
30032 @smallexample @c ada
30033 @group
30034 Asm ("movl %%eax, %0" & LF & HT &
30035      "movl %%ebx, %1" & LF & HT &
30036      "movl %%ecx, %2",
30037      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
30038                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
30039                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
30040 @end group
30041 @end smallexample
30042 @noindent
30043 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
30044 in the Ada program.
30045
30046 As a variation on the @code{Get_Flags} example, we can use the constraints
30047 string to direct the compiler to store the eax register into the @code{Flags}
30048 variable, instead of including the store instruction explicitly in the
30049 @code{Asm} template string:
30050
30051 @smallexample @c ada
30052 @group
30053 with Interfaces; use Interfaces;
30054 with Ada.Text_IO; use Ada.Text_IO;
30055 with System.Machine_Code; use System.Machine_Code;
30056 procedure Get_Flags_2 is
30057    Flags : Unsigned_32;
30058    use ASCII;
30059 begin
30060    Asm ("pushfl"      & LF & HT & -- push flags on stack
30061         "popl %%eax",             -- save flags in eax
30062         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
30063    Put_Line ("Flags register:" & Flags'Img);
30064 end Get_Flags_2;
30065 @end group
30066 @end smallexample
30067
30068 @noindent
30069 The @code{"a"} constraint tells the compiler that the @code{Flags}
30070 variable will come from the eax register. Here is the resulting code:
30071
30072 @smallexample
30073 @group
30074 #APP
30075    pushfl
30076    popl %eax
30077 #NO_APP
30078    movl %eax,-40(%ebp)
30079 @end group
30080 @end smallexample
30081
30082 @noindent
30083 The compiler generated the store of eax into Flags after
30084 expanding the assembler code.
30085
30086 Actually, there was no need to pop the flags into the eax register;
30087 more simply, we could just pop the flags directly into the program variable:
30088
30089 @smallexample @c ada
30090 @group
30091 with Interfaces; use Interfaces;
30092 with Ada.Text_IO; use Ada.Text_IO;
30093 with System.Machine_Code; use System.Machine_Code;
30094 procedure Get_Flags_3 is
30095    Flags : Unsigned_32;
30096    use ASCII;
30097 begin
30098    Asm ("pushfl"  & LF & HT & -- push flags on stack
30099         "pop %0",             -- save flags in Flags
30100         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30101    Put_Line ("Flags register:" & Flags'Img);
30102 end Get_Flags_3;
30103 @end group
30104 @end smallexample
30105
30106 @c ---------------------------------------------------------------------------
30107 @node Input Variables in Inline Assembler
30108 @section Input Variables in Inline Assembler
30109
30110 @noindent
30111 The example in this section illustrates how to specify the source operands
30112 for assembly language statements.
30113 The program simply increments its input value by 1:
30114
30115 @smallexample @c ada
30116 @group
30117 with Interfaces; use Interfaces;
30118 with Ada.Text_IO; use Ada.Text_IO;
30119 with System.Machine_Code; use System.Machine_Code;
30120 procedure Increment is
30121
30122    function Incr (Value : Unsigned_32) return Unsigned_32 is
30123       Result : Unsigned_32;
30124    begin
30125       Asm ("incl %0",
30126            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30127            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30128       return Result;
30129    end Incr;
30130
30131    Value : Unsigned_32;
30132
30133 begin
30134    Value := 5;
30135    Put_Line ("Value before is" & Value'Img);
30136    Value := Incr (Value);
30137    Put_Line ("Value after is" & Value'Img);
30138 end Increment;
30139 @end group
30140 @end smallexample
30141
30142 The @code{Outputs} parameter to @code{Asm} specifies
30143 that the result will be in the eax register and that it is to be stored
30144 in the @code{Result} variable.
30145
30146 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
30147 but with an @code{Asm_Input} attribute.
30148 The @code{"="} constraint, indicating an output value, is not present.
30149
30150 You can have multiple input variables, in the same way that you can have more
30151 than one output variable.
30152
30153 The parameter count (%0, %1) etc, now starts at the first input
30154 statement, and continues with the output statements.
30155 When both parameters use the same variable, the
30156 compiler will treat them as the same %n operand, which is the case here.
30157
30158 Just as the @code{Outputs} parameter causes the register to be stored into the
30159 target variable after execution of the assembler statements, so does the
30160 @code{Inputs} parameter cause its variable to be loaded into the register
30161 before execution of the assembler statements.
30162
30163 Thus the effect of the @code{Asm} invocation is:
30164 @enumerate
30165 @item load the 32-bit value of @code{Value} into eax
30166 @item execute the @code{incl %eax} instruction
30167 @item store the contents of eax into the @code{Result} variable
30168 @end enumerate
30169
30170 The resulting assembler file (with @option{-O2} optimization) contains:
30171 @smallexample
30172 @group
30173 _increment__incr.1:
30174    subl $4,%esp
30175    movl 8(%esp),%eax
30176 #APP
30177    incl %eax
30178 #NO_APP
30179    movl %eax,%edx
30180    movl %ecx,(%esp)
30181    addl $4,%esp
30182    ret
30183 @end group
30184 @end smallexample
30185
30186 @c ---------------------------------------------------------------------------
30187 @node Inlining Inline Assembler Code
30188 @section Inlining Inline Assembler Code
30189
30190 @noindent
30191 For a short subprogram such as the @code{Incr} function in the previous
30192 section, the overhead of the call and return (creating / deleting the stack
30193 frame) can be significant, compared to the amount of code in the subprogram
30194 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
30195 which directs the compiler to expand invocations of the subprogram at the
30196 point(s) of call, instead of setting up a stack frame for out-of-line calls.
30197 Here is the resulting program:
30198
30199 @smallexample @c ada
30200 @group
30201 with Interfaces; use Interfaces;
30202 with Ada.Text_IO; use Ada.Text_IO;
30203 with System.Machine_Code; use System.Machine_Code;
30204 procedure Increment_2 is
30205
30206    function Incr (Value : Unsigned_32) return Unsigned_32 is
30207       Result : Unsigned_32;
30208    begin
30209       Asm ("incl %0",
30210            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30211            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30212       return Result;
30213    end Incr;
30214    pragma Inline (Increment);
30215
30216    Value : Unsigned_32;
30217
30218 begin
30219    Value := 5;
30220    Put_Line ("Value before is" & Value'Img);
30221    Value := Increment (Value);
30222    Put_Line ("Value after is" & Value'Img);
30223 end Increment_2;
30224 @end group
30225 @end smallexample
30226
30227 Compile the program with both optimization (@option{-O2}) and inlining
30228 (@option{-gnatn}) enabled.
30229
30230 The @code{Incr} function is still compiled as usual, but at the
30231 point in @code{Increment} where our function used to be called:
30232
30233 @smallexample
30234 @group
30235 pushl %edi
30236 call _increment__incr.1
30237 @end group
30238 @end smallexample
30239
30240 @noindent
30241 the code for the function body directly appears:
30242
30243 @smallexample
30244 @group
30245 movl %esi,%eax
30246 #APP
30247    incl %eax
30248 #NO_APP
30249    movl %eax,%edx
30250 @end group
30251 @end smallexample
30252
30253 @noindent
30254 thus saving the overhead of stack frame setup and an out-of-line call.
30255
30256 @c ---------------------------------------------------------------------------
30257 @node Other Asm Functionality
30258 @section Other @code{Asm} Functionality
30259
30260 @noindent
30261 This section describes two important parameters to the @code{Asm}
30262 procedure: @code{Clobber}, which identifies register usage;
30263 and @code{Volatile}, which inhibits unwanted optimizations.
30264
30265 @menu
30266 * The Clobber Parameter::
30267 * The Volatile Parameter::
30268 @end menu
30269
30270 @c ---------------------------------------------------------------------------
30271 @node The Clobber Parameter
30272 @subsection The @code{Clobber} Parameter
30273
30274 @noindent
30275 One of the dangers of intermixing assembly language and a compiled language
30276 such as Ada is that the compiler needs to be aware of which registers are
30277 being used by the assembly code.  In some cases, such as the earlier examples,
30278 the constraint string is sufficient to indicate register usage (e.g.,
30279 @code{"a"} for
30280 the eax register).  But more generally, the compiler needs an explicit
30281 identification of the registers that are used by the Inline Assembly
30282 statements.
30283
30284 Using a register that the compiler doesn't know about
30285 could be a side effect of an instruction (like @code{mull}
30286 storing its result in both eax and edx).
30287 It can also arise from explicit register usage in your
30288 assembly code; for example:
30289 @smallexample
30290 @group
30291 Asm ("movl %0, %%ebx" & LF & HT &
30292      "movl %%ebx, %1",
30293      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30294      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
30295 @end group
30296 @end smallexample
30297 @noindent
30298 where the compiler (since it does not analyze the @code{Asm} template string)
30299 does not know you are using the ebx register.
30300
30301 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
30302 to identify the registers that will be used by your assembly code:
30303
30304 @smallexample
30305 @group
30306 Asm ("movl %0, %%ebx" & LF & HT &
30307      "movl %%ebx, %1",
30308      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30309      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30310      Clobber => "ebx");
30311 @end group
30312 @end smallexample
30313
30314 The Clobber parameter is a static string expression specifying the
30315 register(s) you are using.  Note that register names are @emph{not} prefixed
30316 by a percent sign. Also, if more than one register is used then their names
30317 are separated by commas; e.g., @code{"eax, ebx"}
30318
30319 The @code{Clobber} parameter has several additional uses:
30320 @enumerate
30321 @item Use ``register'' name @code{cc} to indicate that flags might have changed
30322 @item Use ``register'' name @code{memory} if you changed a memory location
30323 @end enumerate
30324
30325 @c ---------------------------------------------------------------------------
30326 @node The Volatile Parameter
30327 @subsection The @code{Volatile} Parameter
30328 @cindex Volatile parameter
30329
30330 @noindent
30331 Compiler optimizations in the presence of Inline Assembler may sometimes have
30332 unwanted effects.  For example, when an @code{Asm} invocation with an input
30333 variable is inside a loop, the compiler might move the loading of the input
30334 variable outside the loop, regarding it as a one-time initialization.
30335
30336 If this effect is not desired, you can disable such optimizations by setting
30337 the @code{Volatile} parameter to @code{True}; for example:
30338
30339 @smallexample @c ada
30340 @group
30341 Asm ("movl %0, %%ebx" & LF & HT &
30342      "movl %%ebx, %1",
30343      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
30344      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
30345      Clobber  => "ebx",
30346      Volatile => True);
30347 @end group
30348 @end smallexample
30349
30350 By default, @code{Volatile} is set to @code{False} unless there is no
30351 @code{Outputs} parameter.
30352
30353 Although setting @code{Volatile} to @code{True} prevents unwanted
30354 optimizations, it will also disable other optimizations that might be
30355 important for efficiency. In general, you should set @code{Volatile}
30356 to @code{True} only if the compiler's optimizations have created
30357 problems.
30358 @c END OF INLINE ASSEMBLER CHAPTER
30359 @c ===============================
30360
30361 @c ***********************************
30362 @c * Compatibility and Porting Guide *
30363 @c ***********************************
30364 @node Compatibility and Porting Guide
30365 @appendix Compatibility and Porting Guide
30366
30367 @noindent
30368 This chapter describes the compatibility issues that may arise between
30369 GNAT and other Ada compilation systems (including those for Ada 83),
30370 and shows how GNAT can expedite porting
30371 applications developed in other Ada environments.
30372
30373 @menu
30374 * Compatibility with Ada 83::
30375 * Compatibility between Ada 95 and Ada 2005::
30376 * Implementation-dependent characteristics::
30377 * Compatibility with Other Ada Systems::
30378 * Representation Clauses::
30379 @ifclear vms
30380 @c Brief section is only in non-VMS version
30381 @c Full chapter is in VMS version
30382 * Compatibility with HP Ada 83::
30383 @end ifclear
30384 @ifset vms
30385 * Transitioning to 64-Bit GNAT for OpenVMS::
30386 @end ifset
30387 @end menu
30388
30389 @node Compatibility with Ada 83
30390 @section Compatibility with Ada 83
30391 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
30392
30393 @noindent
30394 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
30395 particular, the design intention was that the difficulties associated
30396 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
30397 that occur when moving from one Ada 83 system to another.
30398
30399 However, there are a number of points at which there are minor
30400 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
30401 full details of these issues,
30402 and should be consulted for a complete treatment.
30403 In practice the
30404 following subsections treat the most likely issues to be encountered.
30405
30406 @menu
30407 * Legal Ada 83 programs that are illegal in Ada 95::
30408 * More deterministic semantics::
30409 * Changed semantics::
30410 * Other language compatibility issues::
30411 @end menu
30412
30413 @node Legal Ada 83 programs that are illegal in Ada 95
30414 @subsection Legal Ada 83 programs that are illegal in Ada 95
30415
30416 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
30417 Ada 95 and thus also in Ada 2005:
30418
30419 @table @emph
30420 @item Character literals
30421 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
30422 @code{Wide_Character} as a new predefined character type, some uses of
30423 character literals that were legal in Ada 83 are illegal in Ada 95.
30424 For example:
30425 @smallexample @c ada
30426    for Char in 'A' .. 'Z' loop @dots{} end loop;
30427 @end smallexample
30428
30429 @noindent
30430 The problem is that @code{'A'} and @code{'Z'} could be from either
30431 @code{Character} or @code{Wide_Character}.  The simplest correction
30432 is to make the type explicit; e.g.:
30433 @smallexample @c ada
30434    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
30435 @end smallexample
30436
30437 @item New reserved words
30438 The identifiers @code{abstract}, @code{aliased}, @code{protected},
30439 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
30440 Existing Ada 83 code using any of these identifiers must be edited to
30441 use some alternative name.
30442
30443 @item Freezing rules
30444 The rules in Ada 95 are slightly different with regard to the point at
30445 which entities are frozen, and representation pragmas and clauses are
30446 not permitted past the freeze point.  This shows up most typically in
30447 the form of an error message complaining that a representation item
30448 appears too late, and the appropriate corrective action is to move
30449 the item nearer to the declaration of the entity to which it refers.
30450
30451 A particular case is that representation pragmas
30452 @ifset vms
30453 (including the
30454 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
30455 @end ifset
30456 cannot be applied to a subprogram body.  If necessary, a separate subprogram
30457 declaration must be introduced to which the pragma can be applied.
30458
30459 @item Optional bodies for library packages
30460 In Ada 83, a package that did not require a package body was nevertheless
30461 allowed to have one.  This lead to certain surprises in compiling large
30462 systems (situations in which the body could be unexpectedly ignored by the
30463 binder).  In Ada 95, if a package does not require a body then it is not
30464 permitted to have a body.  To fix this problem, simply remove a redundant
30465 body if it is empty, or, if it is non-empty, introduce a dummy declaration
30466 into the spec that makes the body required.  One approach is to add a private
30467 part to the package declaration (if necessary), and define a parameterless
30468 procedure called @code{Requires_Body}, which must then be given a dummy
30469 procedure body in the package body, which then becomes required.
30470 Another approach (assuming that this does not introduce elaboration
30471 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
30472 since one effect of this pragma is to require the presence of a package body.
30473
30474 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
30475 In Ada 95, the exception @code{Numeric_Error} is a renaming of
30476 @code{Constraint_Error}.
30477 This means that it is illegal to have separate exception handlers for
30478 the two exceptions.  The fix is simply to remove the handler for the
30479 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
30480 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
30481
30482 @item Indefinite subtypes in generics
30483 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
30484 as the actual for a generic formal private type, but then the instantiation
30485 would be illegal if there were any instances of declarations of variables
30486 of this type in the generic body.  In Ada 95, to avoid this clear violation
30487 of the methodological principle known as the ``contract model'',
30488 the generic declaration explicitly indicates whether
30489 or not such instantiations are permitted.  If a generic formal parameter
30490 has explicit unknown discriminants, indicated by using @code{(<>)} after the
30491 type name, then it can be instantiated with indefinite types, but no
30492 stand-alone variables can be declared of this type.  Any attempt to declare
30493 such a variable will result in an illegality at the time the generic is
30494 declared.  If the @code{(<>)} notation is not used, then it is illegal
30495 to instantiate the generic with an indefinite type.
30496 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
30497 It will show up as a compile time error, and
30498 the fix is usually simply to add the @code{(<>)} to the generic declaration.
30499 @end table
30500
30501 @node More deterministic semantics
30502 @subsection More deterministic semantics
30503
30504 @table @emph
30505 @item Conversions
30506 Conversions from real types to integer types round away from 0.  In Ada 83
30507 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
30508 implementation freedom was intended to support unbiased rounding in
30509 statistical applications, but in practice it interfered with portability.
30510 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
30511 is required.  Numeric code may be affected by this change in semantics.
30512 Note, though, that this issue is no worse than already existed in Ada 83
30513 when porting code from one vendor to another.
30514
30515 @item Tasking
30516 The Real-Time Annex introduces a set of policies that define the behavior of
30517 features that were implementation dependent in Ada 83, such as the order in
30518 which open select branches are executed.
30519 @end table
30520
30521 @node Changed semantics
30522 @subsection Changed semantics
30523
30524 @noindent
30525 The worst kind of incompatibility is one where a program that is legal in
30526 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
30527 possible in Ada 83.  Fortunately this is extremely rare, but the one
30528 situation that you should be alert to is the change in the predefined type
30529 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
30530
30531 @table @emph
30532 @item Range of type @code{Character}
30533 The range of @code{Standard.Character} is now the full 256 characters
30534 of Latin-1, whereas in most Ada 83 implementations it was restricted
30535 to 128 characters. Although some of the effects of
30536 this change will be manifest in compile-time rejection of legal
30537 Ada 83 programs it is possible for a working Ada 83 program to have
30538 a different effect in Ada 95, one that was not permitted in Ada 83.
30539 As an example, the expression
30540 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
30541 delivers @code{255} as its value.
30542 In general, you should look at the logic of any
30543 character-processing Ada 83 program and see whether it needs to be adapted
30544 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
30545 character handling package that may be relevant if code needs to be adapted
30546 to account for the additional Latin-1 elements.
30547 The desirable fix is to
30548 modify the program to accommodate the full character set, but in some cases
30549 it may be convenient to define a subtype or derived type of Character that
30550 covers only the restricted range.
30551 @cindex Latin-1
30552 @end table
30553
30554 @node Other language compatibility issues
30555 @subsection Other language compatibility issues
30556
30557 @table @emph
30558 @item @option{-gnat83} switch
30559 All implementations of GNAT provide a switch that causes GNAT to operate
30560 in Ada 83 mode.  In this mode, some but not all compatibility problems
30561 of the type described above are handled automatically.  For example, the
30562 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
30563 as identifiers as in Ada 83.
30564 However,
30565 in practice, it is usually advisable to make the necessary modifications
30566 to the program to remove the need for using this switch.
30567 See @ref{Compiling Different Versions of Ada}.
30568
30569 @item Support for removed Ada 83 pragmas and attributes
30570 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
30571 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
30572 compilers are allowed, but not required, to implement these missing
30573 elements.  In contrast with some other compilers, GNAT implements all
30574 such pragmas and attributes, eliminating this compatibility concern.  These
30575 include @code{pragma Interface} and the floating point type attributes
30576 (@code{Emax}, @code{Mantissa}, etc.), among other items.
30577 @end table
30578
30579
30580 @node Compatibility between Ada 95 and Ada 2005
30581 @section Compatibility between Ada 95 and Ada 2005
30582 @cindex Compatibility between Ada 95 and Ada 2005
30583
30584 @noindent
30585 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
30586 a number of incompatibilities. Several are enumerated below;
30587 for a complete description please see the
30588 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
30589 @cite{Rationale for Ada 2005}.
30590
30591 @table @emph
30592 @item New reserved words.
30593 The words @code{interface}, @code{overriding} and @code{synchronized} are
30594 reserved in Ada 2005.
30595 A pre-Ada 2005 program that uses any of these as an identifier will be
30596 illegal.
30597
30598 @item New declarations in predefined packages.
30599 A number of packages in the predefined environment contain new declarations:
30600 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
30601 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
30602 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
30603 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
30604 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
30605 If an Ada 95 program does a @code{with} and @code{use} of any of these
30606 packages, the new declarations may cause name clashes.
30607
30608 @item Access parameters.
30609 A nondispatching subprogram with an access parameter cannot be renamed
30610 as a dispatching operation.  This was permitted in Ada 95.
30611
30612 @item Access types, discriminants, and constraints.
30613 Rule changes in this area have led to some incompatibilities; for example,
30614 constrained subtypes of some access types are not permitted in Ada 2005.
30615
30616 @item Aggregates for limited types.
30617 The allowance of aggregates for limited types in Ada 2005 raises the
30618 possibility of ambiguities in legal Ada 95 programs, since additional types
30619 now need to be considered in expression resolution.
30620
30621 @item Fixed-point multiplication and division.
30622 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
30623 were legal in Ada 95 and invoked the predefined versions of these operations,
30624 are now ambiguous.
30625 The ambiguity may be resolved either by applying a type conversion to the
30626 expression, or by explicitly invoking the operation from package
30627 @code{Standard}.
30628
30629 @item Return-by-reference types.
30630 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
30631 can declare a function returning a value from an anonymous access type.
30632 @end table
30633
30634
30635 @node Implementation-dependent characteristics
30636 @section Implementation-dependent characteristics
30637 @noindent
30638 Although the Ada language defines the semantics of each construct as
30639 precisely as practical, in some situations (for example for reasons of
30640 efficiency, or where the effect is heavily dependent on the host or target
30641 platform) the implementation is allowed some freedom.  In porting Ada 83
30642 code to GNAT, you need to be aware of whether / how the existing code
30643 exercised such implementation dependencies.  Such characteristics fall into
30644 several categories, and GNAT offers specific support in assisting the
30645 transition from certain Ada 83 compilers.
30646
30647 @menu
30648 * Implementation-defined pragmas::
30649 * Implementation-defined attributes::
30650 * Libraries::
30651 * Elaboration order::
30652 * Target-specific aspects::
30653 @end menu
30654
30655 @node Implementation-defined pragmas
30656 @subsection Implementation-defined pragmas
30657
30658 @noindent
30659 Ada compilers are allowed to supplement the language-defined pragmas, and
30660 these are a potential source of non-portability.  All GNAT-defined pragmas
30661 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
30662 Reference Manual}, and these include several that are specifically
30663 intended to correspond to other vendors' Ada 83 pragmas.
30664 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
30665 For compatibility with HP Ada 83, GNAT supplies the pragmas
30666 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
30667 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
30668 and @code{Volatile}.
30669 Other relevant pragmas include @code{External} and @code{Link_With}.
30670 Some vendor-specific
30671 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
30672 recognized, thus
30673 avoiding compiler rejection of units that contain such pragmas; they are not
30674 relevant in a GNAT context and hence are not otherwise implemented.
30675
30676 @node Implementation-defined attributes
30677 @subsection Implementation-defined attributes
30678
30679 Analogous to pragmas, the set of attributes may be extended by an
30680 implementation.  All GNAT-defined attributes are described in
30681 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
30682 Manual}, and these include several that are specifically intended
30683 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
30684 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
30685 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
30686 @code{Type_Class}.
30687
30688 @node Libraries
30689 @subsection Libraries
30690 @noindent
30691 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
30692 code uses vendor-specific libraries then there are several ways to manage
30693 this in Ada 95 or Ada 2005:
30694 @enumerate
30695 @item
30696 If the source code for the libraries (specs and bodies) are
30697 available, then the libraries can be migrated in the same way as the
30698 application.
30699 @item
30700 If the source code for the specs but not the bodies are
30701 available, then you can reimplement the bodies.
30702 @item
30703 Some features introduced by Ada 95 obviate the need for library support.  For
30704 example most Ada 83 vendors supplied a package for unsigned integers.  The
30705 Ada 95 modular type feature is the preferred way to handle this need, so
30706 instead of migrating or reimplementing the unsigned integer package it may
30707 be preferable to retrofit the application using modular types.
30708 @end enumerate
30709
30710 @node Elaboration order
30711 @subsection Elaboration order
30712 @noindent
30713 The implementation can choose any elaboration order consistent with the unit
30714 dependency relationship.  This freedom means that some orders can result in
30715 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
30716 to invoke a subprogram its body has been elaborated, or to instantiate a
30717 generic before the generic body has been elaborated.  By default GNAT
30718 attempts to choose a safe order (one that will not encounter access before
30719 elaboration problems) by implicitly inserting @code{Elaborate} or
30720 @code{Elaborate_All} pragmas where
30721 needed.  However, this can lead to the creation of elaboration circularities
30722 and a resulting rejection of the program by gnatbind.  This issue is
30723 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
30724 In brief, there are several
30725 ways to deal with this situation:
30726
30727 @itemize @bullet
30728 @item
30729 Modify the program to eliminate the circularities, e.g.@: by moving
30730 elaboration-time code into explicitly-invoked procedures
30731 @item
30732 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
30733 @code{Elaborate} pragmas, and then inhibit the generation of implicit
30734 @code{Elaborate_All}
30735 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
30736 (by selectively suppressing elaboration checks via pragma
30737 @code{Suppress(Elaboration_Check)} when it is safe to do so).
30738 @end itemize
30739
30740 @node Target-specific aspects
30741 @subsection Target-specific aspects
30742 @noindent
30743 Low-level applications need to deal with machine addresses, data
30744 representations, interfacing with assembler code, and similar issues.  If
30745 such an Ada 83 application is being ported to different target hardware (for
30746 example where the byte endianness has changed) then you will need to
30747 carefully examine the program logic; the porting effort will heavily depend
30748 on the robustness of the original design.  Moreover, Ada 95 (and thus
30749 Ada 2005) are sometimes
30750 incompatible with typical Ada 83 compiler practices regarding implicit
30751 packing, the meaning of the Size attribute, and the size of access values.
30752 GNAT's approach to these issues is described in @ref{Representation Clauses}.
30753
30754 @node Compatibility with Other Ada Systems
30755 @section Compatibility with Other Ada Systems
30756
30757 @noindent
30758 If programs avoid the use of implementation dependent and
30759 implementation defined features, as documented in the @cite{Ada
30760 Reference Manual}, there should be a high degree of portability between
30761 GNAT and other Ada systems.  The following are specific items which
30762 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
30763 compilers, but do not affect porting code to GNAT@.
30764 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
30765 the following issues may or may not arise for Ada 2005 programs
30766 when other compilers appear.)
30767
30768 @table @emph
30769 @item Ada 83 Pragmas and Attributes
30770 Ada 95 compilers are allowed, but not required, to implement the missing
30771 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
30772 GNAT implements all such pragmas and attributes, eliminating this as
30773 a compatibility concern, but some other Ada 95 compilers reject these
30774 pragmas and attributes.
30775
30776 @item Specialized Needs Annexes
30777 GNAT implements the full set of special needs annexes.  At the
30778 current time, it is the only Ada 95 compiler to do so.  This means that
30779 programs making use of these features may not be portable to other Ada
30780 95 compilation systems.
30781
30782 @item Representation Clauses
30783 Some other Ada 95 compilers implement only the minimal set of
30784 representation clauses required by the Ada 95 reference manual.  GNAT goes
30785 far beyond this minimal set, as described in the next section.
30786 @end table
30787
30788 @node Representation Clauses
30789 @section Representation Clauses
30790
30791 @noindent
30792 The Ada 83 reference manual was quite vague in describing both the minimal
30793 required implementation of representation clauses, and also their precise
30794 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
30795 minimal set of capabilities required is still quite limited.
30796
30797 GNAT implements the full required set of capabilities in
30798 Ada 95 and Ada 2005, but also goes much further, and in particular
30799 an effort has been made to be compatible with existing Ada 83 usage to the
30800 greatest extent possible.
30801
30802 A few cases exist in which Ada 83 compiler behavior is incompatible with
30803 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
30804 intentional or accidental dependence on specific implementation dependent
30805 characteristics of these Ada 83 compilers.  The following is a list of
30806 the cases most likely to arise in existing Ada 83 code.
30807
30808 @table @emph
30809 @item Implicit Packing
30810 Some Ada 83 compilers allowed a Size specification to cause implicit
30811 packing of an array or record.  This could cause expensive implicit
30812 conversions for change of representation in the presence of derived
30813 types, and the Ada design intends to avoid this possibility.
30814 Subsequent AI's were issued to make it clear that such implicit
30815 change of representation in response to a Size clause is inadvisable,
30816 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
30817 Reference Manuals as implementation advice that is followed by GNAT@.
30818 The problem will show up as an error
30819 message rejecting the size clause.  The fix is simply to provide
30820 the explicit pragma @code{Pack}, or for more fine tuned control, provide
30821 a Component_Size clause.
30822
30823 @item Meaning of Size Attribute
30824 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
30825 the minimal number of bits required to hold values of the type.  For example,
30826 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
30827 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
30828 some 32 in this situation.  This problem will usually show up as a compile
30829 time error, but not always.  It is a good idea to check all uses of the
30830 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
30831 Object_Size can provide a useful way of duplicating the behavior of
30832 some Ada 83 compiler systems.
30833
30834 @item Size of Access Types
30835 A common assumption in Ada 83 code is that an access type is in fact a pointer,
30836 and that therefore it will be the same size as a System.Address value.  This
30837 assumption is true for GNAT in most cases with one exception.  For the case of
30838 a pointer to an unconstrained array type (where the bounds may vary from one
30839 value of the access type to another), the default is to use a ``fat pointer'',
30840 which is represented as two separate pointers, one to the bounds, and one to
30841 the array.  This representation has a number of advantages, including improved
30842 efficiency.  However, it may cause some difficulties in porting existing Ada 83
30843 code which makes the assumption that, for example, pointers fit in 32 bits on
30844 a machine with 32-bit addressing.
30845
30846 To get around this problem, GNAT also permits the use of ``thin pointers'' for
30847 access types in this case (where the designated type is an unconstrained array
30848 type).  These thin pointers are indeed the same size as a System.Address value.
30849 To specify a thin pointer, use a size clause for the type, for example:
30850
30851 @smallexample @c ada
30852 type X is access all String;
30853 for X'Size use Standard'Address_Size;
30854 @end smallexample
30855
30856 @noindent
30857 which will cause the type X to be represented using a single pointer.
30858 When using this representation, the bounds are right behind the array.
30859 This representation is slightly less efficient, and does not allow quite
30860 such flexibility in the use of foreign pointers or in using the
30861 Unrestricted_Access attribute to create pointers to non-aliased objects.
30862 But for any standard portable use of the access type it will work in
30863 a functionally correct manner and allow porting of existing code.
30864 Note that another way of forcing a thin pointer representation
30865 is to use a component size clause for the element size in an array,
30866 or a record representation clause for an access field in a record.
30867 @end table
30868
30869 @ifclear vms
30870 @c This brief section is only in the non-VMS version
30871 @c The complete chapter on HP Ada is in the VMS version
30872 @node Compatibility with HP Ada 83
30873 @section Compatibility with HP Ada 83
30874
30875 @noindent
30876 The VMS version of GNAT fully implements all the pragmas and attributes
30877 provided by HP Ada 83, as well as providing the standard HP Ada 83
30878 libraries, including Starlet.  In addition, data layouts and parameter
30879 passing conventions are highly compatible.  This means that porting
30880 existing HP Ada 83 code to GNAT in VMS systems should be easier than
30881 most other porting efforts.  The following are some of the most
30882 significant differences between GNAT and HP Ada 83.
30883
30884 @table @emph
30885 @item Default floating-point representation
30886 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
30887 it is VMS format.  GNAT does implement the necessary pragmas
30888 (Long_Float, Float_Representation) for changing this default.
30889
30890 @item System
30891 The package System in GNAT exactly corresponds to the definition in the
30892 Ada 95 reference manual, which means that it excludes many of the
30893 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
30894 that contains the additional definitions, and a special pragma,
30895 Extend_System allows this package to be treated transparently as an
30896 extension of package System.
30897
30898 @item To_Address
30899 The definitions provided by Aux_DEC are exactly compatible with those
30900 in the HP Ada 83 version of System, with one exception.
30901 HP Ada provides the following declarations:
30902
30903 @smallexample @c ada
30904 TO_ADDRESS (INTEGER)
30905 TO_ADDRESS (UNSIGNED_LONGWORD)
30906 TO_ADDRESS (@i{universal_integer})
30907 @end smallexample
30908
30909 @noindent
30910 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
30911 an extension to Ada 83 not strictly compatible with the reference manual.
30912 In GNAT, we are constrained to be exactly compatible with the standard,
30913 and this means we cannot provide this capability.  In HP Ada 83, the
30914 point of this definition is to deal with a call like:
30915
30916 @smallexample @c ada
30917 TO_ADDRESS (16#12777#);
30918 @end smallexample
30919
30920 @noindent
30921 Normally, according to the Ada 83 standard, one would expect this to be
30922 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
30923 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
30924 definition using @i{universal_integer} takes precedence.
30925
30926 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
30927 is not possible to be 100% compatible.  Since there are many programs using
30928 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
30929 to change the name of the function in the UNSIGNED_LONGWORD case, so the
30930 declarations provided in the GNAT version of AUX_Dec are:
30931
30932 @smallexample @c ada
30933 function To_Address (X : Integer) return Address;
30934 pragma Pure_Function (To_Address);
30935
30936 function To_Address_Long (X : Unsigned_Longword)
30937  return Address;
30938 pragma Pure_Function (To_Address_Long);
30939 @end smallexample
30940
30941 @noindent
30942 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
30943 change the name to TO_ADDRESS_LONG@.
30944
30945 @item Task_Id values
30946 The Task_Id values assigned will be different in the two systems, and GNAT
30947 does not provide a specified value for the Task_Id of the environment task,
30948 which in GNAT is treated like any other declared task.
30949 @end table
30950
30951 @noindent
30952 For full details on these and other less significant compatibility issues,
30953 see appendix E of the HP publication entitled @cite{HP Ada, Technical
30954 Overview and Comparison on HP Platforms}.
30955
30956 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
30957 attributes are recognized, although only a subset of them can sensibly
30958 be implemented.  The description of pragmas in @ref{Implementation
30959 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
30960 indicates whether or not they are applicable to non-VMS systems.
30961 @end ifclear
30962
30963 @ifset vms
30964 @node Transitioning to 64-Bit GNAT for OpenVMS
30965 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
30966
30967 @noindent
30968 This section is meant to assist users of pre-2006 @value{EDITION}
30969 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
30970 the version of the GNAT technology supplied in 2006 and later for
30971 OpenVMS on both Alpha and I64.
30972
30973 @menu
30974 * Introduction to transitioning::
30975 * Migration of 32 bit code::
30976 * Taking advantage of 64 bit addressing::
30977 * Technical details::
30978 @end menu
30979
30980 @node Introduction to transitioning
30981 @subsection Introduction
30982
30983 @noindent
30984 64-bit @value{EDITION} for Open VMS has been designed to meet
30985 three main goals:
30986
30987 @enumerate
30988 @item
30989 Providing a full conforming implementation of Ada 95 and Ada 2005
30990
30991 @item
30992 Allowing maximum backward compatibility, thus easing migration of existing
30993 Ada source code
30994
30995 @item
30996 Supplying a path for exploiting the full 64-bit address range
30997 @end enumerate
30998
30999 @noindent
31000 Ada's strong typing semantics has made it
31001 impractical to have different 32-bit and 64-bit modes. As soon as
31002 one object could possibly be outside the 32-bit address space, this
31003 would make it necessary for the @code{System.Address} type to be 64 bits.
31004 In particular, this would cause inconsistencies if 32-bit code is
31005 called from 64-bit code that raises an exception.
31006
31007 This issue has been resolved by always using 64-bit addressing
31008 at the system level, but allowing for automatic conversions between
31009 32-bit and 64-bit addresses where required. Thus users who
31010 do not currently require 64-bit addressing capabilities, can
31011 recompile their code with only minimal changes (and indeed
31012 if the code is written in portable Ada, with no assumptions about
31013 the size of the @code{Address} type, then no changes at all are necessary).
31014 At the same time,
31015 this approach provides a simple, gradual upgrade path to future
31016 use of larger memories than available for 32-bit systems.
31017 Also, newly written applications or libraries will by default
31018 be fully compatible with future systems exploiting 64-bit
31019 addressing capabilities.
31020
31021 @ref{Migration of 32 bit code}, will focus on porting applications
31022 that do not require more than 2 GB of
31023 addressable memory. This code will be referred to as
31024 @emph{32-bit code}.
31025 For applications intending to exploit the full 64-bit address space,
31026 @ref{Taking advantage of 64 bit addressing},
31027 will consider further changes that may be required.
31028 Such code will be referred to below as @emph{64-bit code}.
31029
31030 @node Migration of 32 bit code
31031 @subsection Migration of 32-bit code
31032
31033 @menu
31034 * Address types::
31035 * Access types::
31036 * Unchecked conversions::
31037 * Predefined constants::
31038 * Interfacing with C::
31039 * Experience with source compatibility::
31040 @end menu
31041
31042 @node Address types
31043 @subsubsection Address types
31044
31045 @noindent
31046 To solve the problem of mixing 64-bit and 32-bit addressing,
31047 while maintaining maximum backward compatibility, the following
31048 approach has been taken:
31049
31050 @itemize @bullet
31051 @item
31052 @code{System.Address} always has a size of 64 bits
31053
31054 @item
31055 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
31056 @end itemize
31057
31058 @noindent
31059 Since @code{System.Short_Address} is a subtype of @code{System.Address},
31060 a @code{Short_Address}
31061 may be used where an @code{Address} is required, and vice versa, without
31062 needing explicit type conversions.
31063 By virtue of the Open VMS parameter passing conventions,
31064 even imported
31065 and exported subprograms that have 32-bit address parameters are
31066 compatible with those that have 64-bit address parameters.
31067 (See @ref{Making code 64 bit clean} for details.)
31068
31069 The areas that may need attention are those where record types have
31070 been defined that contain components of the type @code{System.Address}, and
31071 where objects of this type are passed to code expecting a record layout with
31072 32-bit addresses.
31073
31074 Different compilers on different platforms cannot be
31075 expected to represent the same type in the same way,
31076 since alignment constraints
31077 and other system-dependent properties affect the compiler's decision.
31078 For that reason, Ada code
31079 generally uses representation clauses to specify the expected
31080 layout where required.
31081
31082 If such a representation clause uses 32 bits for a component having
31083 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
31084 will detect that error and produce a specific diagnostic message.
31085 The developer should then determine whether the representation
31086 should be 64 bits or not and make either of two changes:
31087 change the size to 64 bits and leave the type as @code{System.Address}, or
31088 leave the size as 32 bits and change the type to @code{System.Short_Address}.
31089 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
31090 required in any code setting or accessing the field; the compiler will
31091 automatically perform any needed conversions between address
31092 formats.
31093
31094 @node Access types
31095 @subsubsection Access types
31096
31097 @noindent
31098 By default, objects designated by access values are always
31099 allocated in the 32-bit
31100 address space. Thus legacy code will never contain
31101 any objects that are not addressable with 32-bit addresses, and
31102 the compiler will never raise exceptions as result of mixing
31103 32-bit and 64-bit addresses.
31104
31105 However, the access values themselves are represented in 64 bits, for optimum
31106 performance and future compatibility with 64-bit code. As was
31107 the case with @code{System.Address}, the compiler will give an error message
31108 if an object or record component has a representation clause that
31109 requires the access value to fit in 32 bits. In such a situation,
31110 an explicit size clause for the access type, specifying 32 bits,
31111 will have the desired effect.
31112
31113 General access types (declared with @code{access all}) can never be
31114 32 bits, as values of such types must be able to refer to any object
31115 of the  designated type,
31116 including objects residing outside the 32-bit address range.
31117 Existing Ada 83 code will not contain such type definitions,
31118 however, since general access types were introduced in Ada 95.
31119
31120 @node Unchecked conversions
31121 @subsubsection Unchecked conversions
31122
31123 @noindent
31124 In the case of an @code{Unchecked_Conversion} where the source type is a
31125 64-bit access type or the type @code{System.Address}, and the target
31126 type is a 32-bit type, the compiler will generate a warning.
31127 Even though the generated code will still perform the required
31128 conversions, it is highly recommended in these cases to use
31129 respectively a 32-bit access type or @code{System.Short_Address}
31130 as the source type.
31131
31132 @node Predefined constants
31133 @subsubsection Predefined constants
31134
31135 @noindent
31136 The following table shows the correspondence between pre-2006 versions of
31137 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
31138 (``New''):
31139
31140 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
31141 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
31142 @item   @code{System.Word_Size}          @tab 32      @tab 64
31143 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
31144 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
31145 @item   @code{System.Address_Size}       @tab 32      @tab 64
31146 @end multitable
31147
31148 @noindent
31149 If you need to refer to the specific
31150 memory size of a 32-bit implementation, instead of the
31151 actual memory size, use @code{System.Short_Memory_Size}
31152 rather than @code{System.Memory_Size}.
31153 Similarly, references to @code{System.Address_Size} may need
31154 to be replaced by @code{System.Short_Address'Size}.
31155 The program @command{gnatfind} may be useful for locating
31156 references to the above constants, so that you can verify that they
31157 are still correct.
31158
31159 @node Interfacing with C
31160 @subsubsection Interfacing with C
31161
31162 @noindent
31163 In order to minimize the impact of the transition to 64-bit addresses on
31164 legacy programs, some fundamental types in the @code{Interfaces.C}
31165 package hierarchy continue to be represented in 32 bits.
31166 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
31167 This eases integration with the default HP C layout choices, for example
31168 as found in the system routines in @code{DECC$SHR.EXE}.
31169 Because of this implementation choice, the type fully compatible with
31170 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
31171 Depending on the context the compiler will issue a
31172 warning or an error when type @code{Address} is used, alerting the user to a
31173 potential problem. Otherwise 32-bit programs that use
31174 @code{Interfaces.C} should normally not require code modifications
31175
31176 The other issue arising with C interfacing concerns pragma @code{Convention}.
31177 For VMS 64-bit systems, there is an issue of the appropriate default size
31178 of C convention pointers in the absence of an explicit size clause. The HP
31179 C compiler can choose either 32 or 64 bits depending on compiler options.
31180 GNAT chooses 32-bits rather than 64-bits in the default case where no size
31181 clause is given. This proves a better choice for porting 32-bit legacy
31182 applications. In order to have a 64-bit representation, it is necessary to
31183 specify a size representation clause. For example:
31184
31185 @smallexample @c ada
31186 type int_star is access Interfaces.C.int;
31187 pragma Convention(C, int_star);
31188 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
31189 @end smallexample
31190
31191 @node Experience with source compatibility
31192 @subsubsection Experience with source compatibility
31193
31194 @noindent
31195 The Security Server and STARLET on I64 provide an interesting ``test case''
31196 for source compatibility issues, since it is in such system code
31197 where assumptions about @code{Address} size might be expected to occur.
31198 Indeed, there were a small number of occasions in the Security Server
31199 file @file{jibdef.ads}
31200 where a representation clause for a record type specified
31201 32 bits for a component of type @code{Address}.
31202 All of these errors were detected by the compiler.
31203 The repair was obvious and immediate; to simply replace @code{Address} by
31204 @code{Short_Address}.
31205
31206 In the case of STARLET, there were several record types that should
31207 have had representation clauses but did not.  In these record types
31208 there was an implicit assumption that an @code{Address} value occupied
31209 32 bits.
31210 These compiled without error, but their usage resulted in run-time error
31211 returns from STARLET system calls.
31212 Future GNAT technology enhancements may include a tool that detects and flags
31213 these sorts of potential source code porting problems.
31214
31215 @c ****************************************
31216 @node Taking advantage of 64 bit addressing
31217 @subsection Taking advantage of 64-bit addressing
31218
31219 @menu
31220 * Making code 64 bit clean::
31221 * Allocating memory from the 64 bit storage pool::
31222 * Restrictions on use of 64 bit objects::
31223 * Using 64 bit storage pools by default::
31224 * General access types::
31225 * STARLET and other predefined libraries::
31226 @end menu
31227
31228 @node Making code 64 bit clean
31229 @subsubsection Making code 64-bit clean
31230
31231 @noindent
31232 In order to prevent problems that may occur when (parts of) a
31233 system start using memory outside the 32-bit address range,
31234 we recommend some additional guidelines:
31235
31236 @itemize @bullet
31237 @item
31238 For imported subprograms that take parameters of the
31239 type @code{System.Address}, ensure that these subprograms can
31240 indeed handle 64-bit addresses. If not, or when in doubt,
31241 change the subprogram declaration to specify
31242 @code{System.Short_Address} instead.
31243
31244 @item
31245 Resolve all warnings related to size mismatches in
31246 unchecked conversions. Failing to do so causes
31247 erroneous execution if the source object is outside
31248 the 32-bit address space.
31249
31250 @item
31251 (optional) Explicitly use the 32-bit storage pool
31252 for access types used in a 32-bit context, or use
31253 generic access types where possible
31254 (@pxref{Restrictions on use of 64 bit objects}).
31255 @end itemize
31256
31257 @noindent
31258 If these rules are followed, the compiler will automatically insert
31259 any necessary checks to ensure that no addresses or access values
31260 passed to 32-bit code ever refer to objects outside the 32-bit
31261 address range.
31262 Any attempt to do this will raise @code{Constraint_Error}.
31263
31264 @node Allocating memory from the 64 bit storage pool
31265 @subsubsection Allocating memory from the 64-bit storage pool
31266
31267 @noindent
31268 For any access type @code{T} that potentially requires memory allocations
31269 beyond the 32-bit address space,
31270 use the following representation clause:
31271
31272 @smallexample @c ada
31273    for T'Storage_Pool use System.Pool_64;
31274 @end smallexample
31275
31276 @node Restrictions on use of 64 bit objects
31277 @subsubsection Restrictions on use of 64-bit objects
31278
31279 @noindent
31280 Taking the address of an object allocated from a 64-bit storage pool,
31281 and then passing this address to a subprogram expecting
31282 @code{System.Short_Address},
31283 or assigning it to a variable of type @code{Short_Address}, will cause
31284 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
31285 (@pxref{Making code 64 bit clean}), or checks are suppressed,
31286 no exception is raised and execution
31287 will become erroneous.
31288
31289 @node Using 64 bit storage pools by default
31290 @subsubsection Using 64-bit storage pools by default
31291
31292 @noindent
31293 In some cases it may be desirable to have the compiler allocate
31294 from 64-bit storage pools by default. This may be the case for
31295 libraries that are 64-bit clean, but may be used in both 32-bit
31296 and 64-bit contexts. For these cases the following configuration
31297 pragma may be specified:
31298
31299 @smallexample @c ada
31300   pragma Pool_64_Default;
31301 @end smallexample
31302
31303 @noindent
31304 Any code compiled in the context of this pragma will by default
31305 use the @code{System.Pool_64} storage pool. This default may be overridden
31306 for a specific access type @code{T} by the representation clause:
31307
31308 @smallexample @c ada
31309    for T'Storage_Pool use System.Pool_32;
31310 @end smallexample
31311
31312 @noindent
31313 Any object whose address may be passed to a subprogram with a
31314 @code{Short_Address} argument, or assigned to a variable of type
31315 @code{Short_Address}, needs to be allocated from this pool.
31316
31317 @node General access types
31318 @subsubsection General access types
31319
31320 @noindent
31321 Objects designated by access values from a
31322 general access type (declared with @code{access all}) are never allocated
31323 from a 64-bit storage pool. Code that uses general access types will
31324 accept objects allocated in either 32-bit or 64-bit address spaces,
31325 but never allocate objects outside the 32-bit address space.
31326 Using general access types ensures maximum compatibility with both
31327 32-bit and 64-bit code.
31328
31329 @node STARLET and other predefined libraries
31330 @subsubsection STARLET and other predefined libraries
31331
31332 @noindent
31333 All code that comes as part of GNAT is 64-bit clean, but the
31334 restrictions given in @ref{Restrictions on use of 64 bit objects},
31335 still apply. Look at the package
31336 specs to see in which contexts objects allocated
31337 in 64-bit address space are acceptable.
31338
31339 @node Technical details
31340 @subsection Technical details
31341
31342 @noindent
31343 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
31344 Ada standard with respect to the type of @code{System.Address}. Previous
31345 versions of GNAT Pro have defined this type as private and implemented it as a
31346 modular type.
31347
31348 In order to allow defining @code{System.Short_Address} as a proper subtype,
31349 and to match the implicit sign extension in parameter passing,
31350 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
31351 visible (i.e., non-private) integer type.
31352 Standard operations on the type, such as the binary operators ``+'', ``-'',
31353 etc., that take @code{Address} operands and return an @code{Address} result,
31354 have been hidden by declaring these
31355 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
31356 ambiguities that would otherwise result from overloading.
31357 (Note that, although @code{Address} is a visible integer type,
31358 good programming practice dictates against exploiting the type's
31359 integer properties such as literals, since this will compromise
31360 code portability.)
31361
31362 Defining @code{Address} as a visible integer type helps achieve
31363 maximum compatibility for existing Ada code,
31364 without sacrificing the capabilities of the 64-bit architecture.
31365 @end ifset
31366
31367 @c ************************************************
31368 @ifset unw
31369 @node Microsoft Windows Topics
31370 @appendix Microsoft Windows Topics
31371 @cindex Windows NT
31372 @cindex Windows 95
31373 @cindex Windows 98
31374
31375 @noindent
31376 This chapter describes topics that are specific to the Microsoft Windows
31377 platforms (NT, 2000, and XP Professional).
31378
31379 @menu
31380 * Using GNAT on Windows::
31381 * Using a network installation of GNAT::
31382 * CONSOLE and WINDOWS subsystems::
31383 * Temporary Files::
31384 * Mixed-Language Programming on Windows::
31385 * Windows Calling Conventions::
31386 * Introduction to Dynamic Link Libraries (DLLs)::
31387 * Using DLLs with GNAT::
31388 * Building DLLs with GNAT::
31389 * Building DLLs with GNAT Project files::
31390 * Building DLLs with gnatdll::
31391 * GNAT and Windows Resources::
31392 * Debugging a DLL::
31393 * Setting Stack Size from gnatlink::
31394 * Setting Heap Size from gnatlink::
31395 @end menu
31396
31397 @node Using GNAT on Windows
31398 @section Using GNAT on Windows
31399
31400 @noindent
31401 One of the strengths of the GNAT technology is that its tool set
31402 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
31403 @code{gdb} debugger, etc.) is used in the same way regardless of the
31404 platform.
31405
31406 On Windows this tool set is complemented by a number of Microsoft-specific
31407 tools that have been provided to facilitate interoperability with Windows
31408 when this is required. With these tools:
31409
31410 @itemize @bullet
31411
31412 @item
31413 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
31414 subsystems.
31415
31416 @item
31417 You can use any Dynamically Linked Library (DLL) in your Ada code (both
31418 relocatable and non-relocatable DLLs are supported).
31419
31420 @item
31421 You can build Ada DLLs for use in other applications. These applications
31422 can be written in a language other than Ada (e.g., C, C++, etc). Again both
31423 relocatable and non-relocatable Ada DLLs are supported.
31424
31425 @item
31426 You can include Windows resources in your Ada application.
31427
31428 @item
31429 You can use or create COM/DCOM objects.
31430 @end itemize
31431
31432 @noindent
31433 Immediately below are listed all known general GNAT-for-Windows restrictions.
31434 Other restrictions about specific features like Windows Resources and DLLs
31435 are listed in separate sections below.
31436
31437 @itemize @bullet
31438
31439 @item
31440 It is not possible to use @code{GetLastError} and @code{SetLastError}
31441 when tasking, protected records, or exceptions are used. In these
31442 cases, in order to implement Ada semantics, the GNAT run-time system
31443 calls certain Win32 routines that set the last error variable to 0 upon
31444 success. It should be possible to use @code{GetLastError} and
31445 @code{SetLastError} when tasking, protected record, and exception
31446 features are not used, but it is not guaranteed to work.
31447
31448 @item
31449 It is not possible to link against Microsoft libraries except for
31450 import libraries. The library must be built to be compatible with
31451 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
31452 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
31453 not be compatible with the GNAT runtime. Even if the library is
31454 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
31455
31456 @item
31457 When the compilation environment is located on FAT32 drives, users may
31458 experience recompilations of the source files that have not changed if
31459 Daylight Saving Time (DST) state has changed since the last time files
31460 were compiled. NTFS drives do not have this problem.
31461
31462 @item
31463 No components of the GNAT toolset use any entries in the Windows
31464 registry. The only entries that can be created are file associations and
31465 PATH settings, provided the user has chosen to create them at installation
31466 time, as well as some minimal book-keeping information needed to correctly
31467 uninstall or integrate different GNAT products.
31468 @end itemize
31469
31470 @node Using a network installation of GNAT
31471 @section Using a network installation of GNAT
31472
31473 @noindent
31474 Make sure the system on which GNAT is installed is accessible from the
31475 current machine, i.e., the install location is shared over the network.
31476 Shared resources are accessed on Windows by means of UNC paths, which
31477 have the format @code{\\server\sharename\path}
31478
31479 In order to use such a network installation, simply add the UNC path of the
31480 @file{bin} directory of your GNAT installation in front of your PATH. For
31481 example, if GNAT is installed in @file{\GNAT} directory of a share location
31482 called @file{c-drive} on a machine @file{LOKI}, the following command will
31483 make it available:
31484
31485 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
31486
31487 Be aware that every compilation using the network installation results in the
31488 transfer of large amounts of data across the network and will likely cause
31489 serious performance penalty.
31490
31491 @node CONSOLE and WINDOWS subsystems
31492 @section CONSOLE and WINDOWS subsystems
31493 @cindex CONSOLE Subsystem
31494 @cindex WINDOWS Subsystem
31495 @cindex -mwindows
31496
31497 @noindent
31498 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
31499 (which is the default subsystem) will always create a console when
31500 launching the application. This is not something desirable when the
31501 application has a Windows GUI. To get rid of this console the
31502 application must be using the @code{WINDOWS} subsystem. To do so
31503 the @option{-mwindows} linker option must be specified.
31504
31505 @smallexample
31506 $ gnatmake winprog -largs -mwindows
31507 @end smallexample
31508
31509 @node Temporary Files
31510 @section Temporary Files
31511 @cindex Temporary files
31512
31513 @noindent
31514 It is possible to control where temporary files gets created by setting
31515 the @env{TMP} environment variable. The file will be created:
31516
31517 @itemize
31518 @item Under the directory pointed to by the @env{TMP} environment variable if
31519 this directory exists.
31520
31521 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
31522 set (or not pointing to a directory) and if this directory exists.
31523
31524 @item Under the current working directory otherwise.
31525 @end itemize
31526
31527 @noindent
31528 This allows you to determine exactly where the temporary
31529 file will be created. This is particularly useful in networked
31530 environments where you may not have write access to some
31531 directories.
31532
31533 @node Mixed-Language Programming on Windows
31534 @section Mixed-Language Programming on Windows
31535
31536 @noindent
31537 Developing pure Ada applications on Windows is no different than on
31538 other GNAT-supported platforms. However, when developing or porting an
31539 application that contains a mix of Ada and C/C++, the choice of your
31540 Windows C/C++ development environment conditions your overall
31541 interoperability strategy.
31542
31543 If you use @command{gcc} to compile the non-Ada part of your application,
31544 there are no Windows-specific restrictions that affect the overall
31545 interoperability with your Ada code. If you plan to use
31546 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
31547 the following limitations:
31548
31549 @itemize @bullet
31550 @item
31551 You cannot link your Ada code with an object or library generated with
31552 Microsoft tools if these use the @code{.tls} section (Thread Local
31553 Storage section) since the GNAT linker does not yet support this section.
31554
31555 @item
31556 You cannot link your Ada code with an object or library generated with
31557 Microsoft tools if these use I/O routines other than those provided in
31558 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
31559 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
31560 libraries can cause a conflict with @code{msvcrt.dll} services. For
31561 instance Visual C++ I/O stream routines conflict with those in
31562 @code{msvcrt.dll}.
31563 @end itemize
31564
31565 @noindent
31566 If you do want to use the Microsoft tools for your non-Ada code and hit one
31567 of the above limitations, you have two choices:
31568
31569 @enumerate
31570 @item
31571 Encapsulate your non-Ada code in a DLL to be linked with your Ada
31572 application. In this case, use the Microsoft or whatever environment to
31573 build the DLL and use GNAT to build your executable
31574 (@pxref{Using DLLs with GNAT}).
31575
31576 @item
31577 Or you can encapsulate your Ada code in a DLL to be linked with the
31578 other part of your application. In this case, use GNAT to build the DLL
31579 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
31580 environment to build your executable.
31581 @end enumerate
31582
31583 @node Windows Calling Conventions
31584 @section Windows Calling Conventions
31585 @findex Stdcall
31586 @findex APIENTRY
31587
31588 @menu
31589 * C Calling Convention::
31590 * Stdcall Calling Convention::
31591 * Win32 Calling Convention::
31592 * DLL Calling Convention::
31593 @end menu
31594
31595 @noindent
31596 When a subprogram @code{F} (caller) calls a subprogram @code{G}
31597 (callee), there are several ways to push @code{G}'s parameters on the
31598 stack and there are several possible scenarios to clean up the stack
31599 upon @code{G}'s return. A calling convention is an agreed upon software
31600 protocol whereby the responsibilities between the caller (@code{F}) and
31601 the callee (@code{G}) are clearly defined. Several calling conventions
31602 are available for Windows:
31603
31604 @itemize @bullet
31605 @item
31606 @code{C} (Microsoft defined)
31607
31608 @item
31609 @code{Stdcall} (Microsoft defined)
31610
31611 @item
31612 @code{Win32} (GNAT specific)
31613
31614 @item
31615 @code{DLL} (GNAT specific)
31616 @end itemize
31617
31618 @node C Calling Convention
31619 @subsection @code{C} Calling Convention
31620
31621 @noindent
31622 This is the default calling convention used when interfacing to C/C++
31623 routines compiled with either @command{gcc} or Microsoft Visual C++.
31624
31625 In the @code{C} calling convention subprogram parameters are pushed on the
31626 stack by the caller from right to left. The caller itself is in charge of
31627 cleaning up the stack after the call. In addition, the name of a routine
31628 with @code{C} calling convention is mangled by adding a leading underscore.
31629
31630 The name to use on the Ada side when importing (or exporting) a routine
31631 with @code{C} calling convention is the name of the routine. For
31632 instance the C function:
31633
31634 @smallexample
31635 int get_val (long);
31636 @end smallexample
31637
31638 @noindent
31639 should be imported from Ada as follows:
31640
31641 @smallexample @c ada
31642 @group
31643 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31644 pragma Import (C, Get_Val, External_Name => "get_val");
31645 @end group
31646 @end smallexample
31647
31648 @noindent
31649 Note that in this particular case the @code{External_Name} parameter could
31650 have been omitted since, when missing, this parameter is taken to be the
31651 name of the Ada entity in lower case. When the @code{Link_Name} parameter
31652 is missing, as in the above example, this parameter is set to be the
31653 @code{External_Name} with a leading underscore.
31654
31655 When importing a variable defined in C, you should always use the @code{C}
31656 calling convention unless the object containing the variable is part of a
31657 DLL (in which case you should use the @code{Stdcall} calling
31658 convention, @pxref{Stdcall Calling Convention}).
31659
31660 @node Stdcall Calling Convention
31661 @subsection @code{Stdcall} Calling Convention
31662
31663 @noindent
31664 This convention, which was the calling convention used for Pascal
31665 programs, is used by Microsoft for all the routines in the Win32 API for
31666 efficiency reasons. It must be used to import any routine for which this
31667 convention was specified.
31668
31669 In the @code{Stdcall} calling convention subprogram parameters are pushed
31670 on the stack by the caller from right to left. The callee (and not the
31671 caller) is in charge of cleaning the stack on routine exit. In addition,
31672 the name of a routine with @code{Stdcall} calling convention is mangled by
31673 adding a leading underscore (as for the @code{C} calling convention) and a
31674 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
31675 bytes) of the parameters passed to the routine.
31676
31677 The name to use on the Ada side when importing a C routine with a
31678 @code{Stdcall} calling convention is the name of the C routine. The leading
31679 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
31680 the compiler. For instance the Win32 function:
31681
31682 @smallexample
31683 @b{APIENTRY} int get_val (long);
31684 @end smallexample
31685
31686 @noindent
31687 should be imported from Ada as follows:
31688
31689 @smallexample @c ada
31690 @group
31691 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31692 pragma Import (Stdcall, Get_Val);
31693 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
31694 @end group
31695 @end smallexample
31696
31697 @noindent
31698 As for the @code{C} calling convention, when the @code{External_Name}
31699 parameter is missing, it is taken to be the name of the Ada entity in lower
31700 case. If instead of writing the above import pragma you write:
31701
31702 @smallexample @c ada
31703 @group
31704 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31705 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
31706 @end group
31707 @end smallexample
31708
31709 @noindent
31710 then the imported routine is @code{_retrieve_val@@4}. However, if instead
31711 of specifying the @code{External_Name} parameter you specify the
31712 @code{Link_Name} as in the following example:
31713
31714 @smallexample @c ada
31715 @group
31716 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31717 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
31718 @end group
31719 @end smallexample
31720
31721 @noindent
31722 then the imported routine is @code{retrieve_val}, that is, there is no
31723 decoration at all. No leading underscore and no Stdcall suffix
31724 @code{@@}@code{@var{nn}}.
31725
31726 @noindent
31727 This is especially important as in some special cases a DLL's entry
31728 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
31729 name generated for a call has it.
31730
31731 @noindent
31732 It is also possible to import variables defined in a DLL by using an
31733 import pragma for a variable. As an example, if a DLL contains a
31734 variable defined as:
31735
31736 @smallexample
31737 int my_var;
31738 @end smallexample
31739
31740 @noindent
31741 then, to access this variable from Ada you should write:
31742
31743 @smallexample @c ada
31744 @group
31745 My_Var : Interfaces.C.int;
31746 pragma Import (Stdcall, My_Var);
31747 @end group
31748 @end smallexample
31749
31750 @noindent
31751 Note that to ease building cross-platform bindings this convention
31752 will be handled as a @code{C} calling convention on non-Windows platforms.
31753
31754 @node Win32 Calling Convention
31755 @subsection @code{Win32} Calling Convention
31756
31757 @noindent
31758 This convention, which is GNAT-specific is fully equivalent to the
31759 @code{Stdcall} calling convention described above.
31760
31761 @node DLL Calling Convention
31762 @subsection @code{DLL} Calling Convention
31763
31764 @noindent
31765 This convention, which is GNAT-specific is fully equivalent to the
31766 @code{Stdcall} calling convention described above.
31767
31768 @node Introduction to Dynamic Link Libraries (DLLs)
31769 @section Introduction to Dynamic Link Libraries (DLLs)
31770 @findex DLL
31771
31772 @noindent
31773 A Dynamically Linked Library (DLL) is a library that can be shared by
31774 several applications running under Windows. A DLL can contain any number of
31775 routines and variables.
31776
31777 One advantage of DLLs is that you can change and enhance them without
31778 forcing all the applications that depend on them to be relinked or
31779 recompiled. However, you should be aware than all calls to DLL routines are
31780 slower since, as you will understand below, such calls are indirect.
31781
31782 To illustrate the remainder of this section, suppose that an application
31783 wants to use the services of a DLL @file{API.dll}. To use the services
31784 provided by @file{API.dll} you must statically link against the DLL or
31785 an import library which contains a jump table with an entry for each
31786 routine and variable exported by the DLL. In the Microsoft world this
31787 import library is called @file{API.lib}. When using GNAT this import
31788 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
31789 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
31790
31791 After you have linked your application with the DLL or the import library
31792 and you run your application, here is what happens:
31793
31794 @enumerate
31795 @item
31796 Your application is loaded into memory.
31797
31798 @item
31799 The DLL @file{API.dll} is mapped into the address space of your
31800 application. This means that:
31801
31802 @itemize @bullet
31803 @item
31804 The DLL will use the stack of the calling thread.
31805
31806 @item
31807 The DLL will use the virtual address space of the calling process.
31808
31809 @item
31810 The DLL will allocate memory from the virtual address space of the calling
31811 process.
31812
31813 @item
31814 Handles (pointers) can be safely exchanged between routines in the DLL
31815 routines and routines in the application using the DLL.
31816 @end itemize
31817
31818 @item
31819 The entries in the jump table (from the import library @file{libAPI.dll.a}
31820 or @file{API.lib} or automatically created when linking against a DLL)
31821 which is part of your application are initialized with the addresses
31822 of the routines and variables in @file{API.dll}.
31823
31824 @item
31825 If present in @file{API.dll}, routines @code{DllMain} or
31826 @code{DllMainCRTStartup} are invoked. These routines typically contain
31827 the initialization code needed for the well-being of the routines and
31828 variables exported by the DLL.
31829 @end enumerate
31830
31831 @noindent
31832 There is an additional point which is worth mentioning. In the Windows
31833 world there are two kind of DLLs: relocatable and non-relocatable
31834 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
31835 in the target application address space. If the addresses of two
31836 non-relocatable DLLs overlap and these happen to be used by the same
31837 application, a conflict will occur and the application will run
31838 incorrectly. Hence, when possible, it is always preferable to use and
31839 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
31840 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
31841 User's Guide) removes the debugging symbols from the DLL but the DLL can
31842 still be relocated.
31843
31844 As a side note, an interesting difference between Microsoft DLLs and
31845 Unix shared libraries, is the fact that on most Unix systems all public
31846 routines are exported by default in a Unix shared library, while under
31847 Windows it is possible (but not required) to list exported routines in
31848 a definition file (@pxref{The Definition File}).
31849
31850 @node Using DLLs with GNAT
31851 @section Using DLLs with GNAT
31852
31853 @menu
31854 * Creating an Ada Spec for the DLL Services::
31855 * Creating an Import Library::
31856 @end menu
31857
31858 @noindent
31859 To use the services of a DLL, say @file{API.dll}, in your Ada application
31860 you must have:
31861
31862 @enumerate
31863 @item
31864 The Ada spec for the routines and/or variables you want to access in
31865 @file{API.dll}. If not available this Ada spec must be built from the C/C++
31866 header files provided with the DLL.
31867
31868 @item
31869 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
31870 mentioned an import library is a statically linked library containing the
31871 import table which will be filled at load time to point to the actual
31872 @file{API.dll} routines. Sometimes you don't have an import library for the
31873 DLL you want to use. The following sections will explain how to build
31874 one. Note that this is optional.
31875
31876 @item
31877 The actual DLL, @file{API.dll}.
31878 @end enumerate
31879
31880 @noindent
31881 Once you have all the above, to compile an Ada application that uses the
31882 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
31883 you simply issue the command
31884
31885 @smallexample
31886 $ gnatmake my_ada_app -largs -lAPI
31887 @end smallexample
31888
31889 @noindent
31890 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
31891 tells the GNAT linker to look first for a library named @file{API.lib}
31892 (Microsoft-style name) and if not found for a libraries named
31893 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
31894 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
31895 contains the following pragma
31896
31897 @smallexample @c ada
31898 pragma Linker_Options ("-lAPI");
31899 @end smallexample
31900
31901 @noindent
31902 you do not have to add @option{-largs -lAPI} at the end of the
31903 @command{gnatmake} command.
31904
31905 If any one of the items above is missing you will have to create it
31906 yourself. The following sections explain how to do so using as an
31907 example a fictitious DLL called @file{API.dll}.
31908
31909 @node Creating an Ada Spec for the DLL Services
31910 @subsection Creating an Ada Spec for the DLL Services
31911
31912 @noindent
31913 A DLL typically comes with a C/C++ header file which provides the
31914 definitions of the routines and variables exported by the DLL. The Ada
31915 equivalent of this header file is a package spec that contains definitions
31916 for the imported entities. If the DLL you intend to use does not come with
31917 an Ada spec you have to generate one such spec yourself. For example if
31918 the header file of @file{API.dll} is a file @file{api.h} containing the
31919 following two definitions:
31920
31921 @smallexample
31922 @group
31923 @cartouche
31924 int some_var;
31925 int get (char *);
31926 @end cartouche
31927 @end group
31928 @end smallexample
31929
31930 @noindent
31931 then the equivalent Ada spec could be:
31932
31933 @smallexample @c ada
31934 @group
31935 @cartouche
31936 with Interfaces.C.Strings;
31937 package API is
31938    use Interfaces;
31939
31940    Some_Var : C.int;
31941    function Get (Str : C.Strings.Chars_Ptr) return C.int;
31942
31943 private
31944    pragma Import (C, Get);
31945    pragma Import (DLL, Some_Var);
31946 end API;
31947 @end cartouche
31948 @end group
31949 @end smallexample
31950
31951 @noindent
31952 Note that a variable is
31953 @strong{always imported with a Stdcall convention}. A function
31954 can have @code{C} or @code{Stdcall} convention.
31955 (@pxref{Windows Calling Conventions}).
31956
31957 @node Creating an Import Library
31958 @subsection Creating an Import Library
31959 @cindex Import library
31960
31961 @menu
31962 * The Definition File::
31963 * GNAT-Style Import Library::
31964 * Microsoft-Style Import Library::
31965 @end menu
31966
31967 @noindent
31968 If a Microsoft-style import library @file{API.lib} or a GNAT-style
31969 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
31970 with @file{API.dll} you can skip this section. You can also skip this
31971 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
31972 as in this case it is possible to link directly against the
31973 DLL. Otherwise read on.
31974
31975 @node The Definition File
31976 @subsubsection The Definition File
31977 @cindex Definition file
31978 @findex .def
31979
31980 @noindent
31981 As previously mentioned, and unlike Unix systems, the list of symbols
31982 that are exported from a DLL must be provided explicitly in Windows.
31983 The main goal of a definition file is precisely that: list the symbols
31984 exported by a DLL. A definition file (usually a file with a @code{.def}
31985 suffix) has the following structure:
31986
31987 @smallexample
31988 @group
31989 @cartouche
31990 @r{[}LIBRARY @var{name}@r{]}
31991 @r{[}DESCRIPTION @var{string}@r{]}
31992 EXPORTS
31993    @var{symbol1}
31994    @var{symbol2}
31995    @dots{}
31996 @end cartouche
31997 @end group
31998 @end smallexample
31999
32000 @table @code
32001 @item LIBRARY @var{name}
32002 This section, which is optional, gives the name of the DLL.
32003
32004 @item DESCRIPTION @var{string}
32005 This section, which is optional, gives a description string that will be
32006 embedded in the import library.
32007
32008 @item EXPORTS
32009 This section gives the list of exported symbols (procedures, functions or
32010 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
32011 section of @file{API.def} looks like:
32012
32013 @smallexample
32014 @group
32015 @cartouche
32016 EXPORTS
32017    some_var
32018    get
32019 @end cartouche
32020 @end group
32021 @end smallexample
32022 @end table
32023
32024 @noindent
32025 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
32026 (@pxref{Windows Calling Conventions}) for a Stdcall
32027 calling convention function in the exported symbols list.
32028
32029 @noindent
32030 There can actually be other sections in a definition file, but these
32031 sections are not relevant to the discussion at hand.
32032
32033 @node GNAT-Style Import Library
32034 @subsubsection GNAT-Style Import Library
32035
32036 @noindent
32037 To create a static import library from @file{API.dll} with the GNAT tools
32038 you should proceed as follows:
32039
32040 @enumerate
32041 @item
32042 Create the definition file @file{API.def} (@pxref{The Definition File}).
32043 For that use the @code{dll2def} tool as follows:
32044
32045 @smallexample
32046 $ dll2def API.dll > API.def
32047 @end smallexample
32048
32049 @noindent
32050 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
32051 to standard output the list of entry points in the DLL. Note that if
32052 some routines in the DLL have the @code{Stdcall} convention
32053 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
32054 suffix then you'll have to edit @file{api.def} to add it, and specify
32055 @option{-k} to @command{gnatdll} when creating the import library.
32056
32057 @noindent
32058 Here are some hints to find the right @code{@@}@var{nn} suffix.
32059
32060 @enumerate
32061 @item
32062 If you have the Microsoft import library (.lib), it is possible to get
32063 the right symbols by using Microsoft @code{dumpbin} tool (see the
32064 corresponding Microsoft documentation for further details).
32065
32066 @smallexample
32067 $ dumpbin /exports api.lib
32068 @end smallexample
32069
32070 @item
32071 If you have a message about a missing symbol at link time the compiler
32072 tells you what symbol is expected. You just have to go back to the
32073 definition file and add the right suffix.
32074 @end enumerate
32075
32076 @item
32077 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
32078 (@pxref{Using gnatdll}) as follows:
32079
32080 @smallexample
32081 $ gnatdll -e API.def -d API.dll
32082 @end smallexample
32083
32084 @noindent
32085 @code{gnatdll} takes as input a definition file @file{API.def} and the
32086 name of the DLL containing the services listed in the definition file
32087 @file{API.dll}. The name of the static import library generated is
32088 computed from the name of the definition file as follows: if the
32089 definition file name is @var{xyz}@code{.def}, the import library name will
32090 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
32091 @option{-e} could have been removed because the name of the definition
32092 file (before the ``@code{.def}'' suffix) is the same as the name of the
32093 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
32094 @end enumerate
32095
32096 @node Microsoft-Style Import Library
32097 @subsubsection Microsoft-Style Import Library
32098
32099 @noindent
32100 With GNAT you can either use a GNAT-style or Microsoft-style import
32101 library. A Microsoft import library is needed only if you plan to make an
32102 Ada DLL available to applications developed with Microsoft
32103 tools (@pxref{Mixed-Language Programming on Windows}).
32104
32105 To create a Microsoft-style import library for @file{API.dll} you
32106 should proceed as follows:
32107
32108 @enumerate
32109 @item
32110 Create the definition file @file{API.def} from the DLL. For this use either
32111 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
32112 tool (see the corresponding Microsoft documentation for further details).
32113
32114 @item
32115 Build the actual import library using Microsoft's @code{lib} utility:
32116
32117 @smallexample
32118 $ lib -machine:IX86 -def:API.def -out:API.lib
32119 @end smallexample
32120
32121 @noindent
32122 If you use the above command the definition file @file{API.def} must
32123 contain a line giving the name of the DLL:
32124
32125 @smallexample
32126 LIBRARY      "API"
32127 @end smallexample
32128
32129 @noindent
32130 See the Microsoft documentation for further details about the usage of
32131 @code{lib}.
32132 @end enumerate
32133
32134 @node Building DLLs with GNAT
32135 @section Building DLLs with GNAT
32136 @cindex DLLs, building
32137
32138 @noindent
32139 This section explain how to build DLLs using the GNAT built-in DLL
32140 support. With the following procedure it is straight forward to build
32141 and use DLLs with GNAT.
32142
32143 @enumerate
32144
32145 @item building object files
32146
32147 The first step is to build all objects files that are to be included
32148 into the DLL. This is done by using the standard @command{gnatmake} tool.
32149
32150 @item building the DLL
32151
32152 To build the DLL you must use @command{gcc}'s @option{-shared}
32153 option. It is quite simple to use this method:
32154
32155 @smallexample
32156 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
32157 @end smallexample
32158
32159 It is important to note that in this case all symbols found in the
32160 object files are automatically exported. It is possible to restrict
32161 the set of symbols to export by passing to @command{gcc} a definition
32162 file, @pxref{The Definition File}. For example:
32163
32164 @smallexample
32165 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
32166 @end smallexample
32167
32168 If you use a definition file you must export the elaboration procedures
32169 for every package that required one. Elaboration procedures are named
32170 using the package name followed by "_E".
32171
32172 @item preparing DLL to be used
32173
32174 For the DLL to be used by client programs the bodies must be hidden
32175 from it and the .ali set with read-only attribute. This is very important
32176 otherwise GNAT will recompile all packages and will not actually use
32177 the code in the DLL. For example:
32178
32179 @smallexample
32180 $ mkdir apilib
32181 $ copy *.ads *.ali api.dll apilib
32182 $ attrib +R apilib\*.ali
32183 @end smallexample
32184
32185 @end enumerate
32186
32187 At this point it is possible to use the DLL by directly linking
32188 against it. Note that you must use the GNAT shared runtime when using
32189 GNAT shared libraries. This is achieved by using @option{-shared} binder's
32190 option.
32191
32192 @smallexample
32193 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
32194 @end smallexample
32195
32196 @node Building DLLs with GNAT Project files
32197 @section Building DLLs with GNAT Project files
32198 @cindex DLLs, building
32199
32200 @noindent
32201 There is nothing specific to Windows in the build process.
32202 @pxref{Library Projects}.
32203
32204 @noindent
32205 Due to a system limitation, it is not possible under Windows to create threads
32206 when inside the @code{DllMain} routine which is used for auto-initialization
32207 of shared libraries, so it is not possible to have library level tasks in SALs.
32208
32209 @node Building DLLs with gnatdll
32210 @section Building DLLs with gnatdll
32211 @cindex DLLs, building
32212
32213 @menu
32214 * Limitations When Using Ada DLLs from Ada::
32215 * Exporting Ada Entities::
32216 * Ada DLLs and Elaboration::
32217 * Ada DLLs and Finalization::
32218 * Creating a Spec for Ada DLLs::
32219 * Creating the Definition File::
32220 * Using gnatdll::
32221 @end menu
32222
32223 @noindent
32224 Note that it is preferred to use the built-in GNAT DLL support
32225 (@pxref{Building DLLs with GNAT}) or GNAT Project files
32226 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
32227
32228 This section explains how to build DLLs containing Ada code using
32229 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
32230 remainder of this section.
32231
32232 The steps required to build an Ada DLL that is to be used by Ada as well as
32233 non-Ada applications are as follows:
32234
32235 @enumerate
32236 @item
32237 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
32238 @code{Stdcall} calling convention to avoid any Ada name mangling for the
32239 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
32240 skip this step if you plan to use the Ada DLL only from Ada applications.
32241
32242 @item
32243 Your Ada code must export an initialization routine which calls the routine
32244 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
32245 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
32246 routine exported by the Ada DLL must be invoked by the clients of the DLL
32247 to initialize the DLL.
32248
32249 @item
32250 When useful, the DLL should also export a finalization routine which calls
32251 routine @code{adafinal} generated by @command{gnatbind} to perform the
32252 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
32253 The finalization routine exported by the Ada DLL must be invoked by the
32254 clients of the DLL when the DLL services are no further needed.
32255
32256 @item
32257 You must provide a spec for the services exported by the Ada DLL in each
32258 of the programming languages to which you plan to make the DLL available.
32259
32260 @item
32261 You must provide a definition file listing the exported entities
32262 (@pxref{The Definition File}).
32263
32264 @item
32265 Finally you must use @code{gnatdll} to produce the DLL and the import
32266 library (@pxref{Using gnatdll}).
32267 @end enumerate
32268
32269 @noindent
32270 Note that a relocatable DLL stripped using the @code{strip}
32271 binutils tool will not be relocatable anymore. To build a DLL without
32272 debug information pass @code{-largs -s} to @code{gnatdll}. This
32273 restriction does not apply to a DLL built using a Library Project.
32274 @pxref{Library Projects}.
32275
32276 @node Limitations When Using Ada DLLs from Ada
32277 @subsection Limitations When Using Ada DLLs from Ada
32278
32279 @noindent
32280 When using Ada DLLs from Ada applications there is a limitation users
32281 should be aware of. Because on Windows the GNAT run time is not in a DLL of
32282 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
32283 each Ada DLL includes the services of the GNAT run time that are necessary
32284 to the Ada code inside the DLL. As a result, when an Ada program uses an
32285 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
32286 one in the main program.
32287
32288 It is therefore not possible to exchange GNAT run-time objects between the
32289 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
32290 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
32291 types, etc.
32292
32293 It is completely safe to exchange plain elementary, array or record types,
32294 Windows object handles, etc.
32295
32296 @node Exporting Ada Entities
32297 @subsection Exporting Ada Entities
32298 @cindex Export table
32299
32300 @noindent
32301 Building a DLL is a way to encapsulate a set of services usable from any
32302 application. As a result, the Ada entities exported by a DLL should be
32303 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
32304 any Ada name mangling. As an example here is an Ada package
32305 @code{API}, spec and body, exporting two procedures, a function, and a
32306 variable:
32307
32308 @smallexample @c ada
32309 @group
32310 @cartouche
32311 with Interfaces.C; use Interfaces;
32312 package API is
32313    Count : C.int := 0;
32314    function Factorial (Val : C.int) return C.int;
32315
32316    procedure Initialize_API;
32317    procedure Finalize_API;
32318    --  Initialization & Finalization routines. More in the next section.
32319 private
32320    pragma Export (C, Initialize_API);
32321    pragma Export (C, Finalize_API);
32322    pragma Export (C, Count);
32323    pragma Export (C, Factorial);
32324 end API;
32325 @end cartouche
32326 @end group
32327 @end smallexample
32328
32329 @smallexample @c ada
32330 @group
32331 @cartouche
32332 package body API is
32333    function Factorial (Val : C.int) return C.int is
32334       Fact : C.int := 1;
32335    begin
32336       Count := Count + 1;
32337       for K in 1 .. Val loop
32338          Fact := Fact * K;
32339       end loop;
32340       return Fact;
32341    end Factorial;
32342
32343    procedure Initialize_API is
32344       procedure Adainit;
32345       pragma Import (C, Adainit);
32346    begin
32347       Adainit;
32348    end Initialize_API;
32349
32350    procedure Finalize_API is
32351       procedure Adafinal;
32352       pragma Import (C, Adafinal);
32353    begin
32354       Adafinal;
32355    end Finalize_API;
32356 end API;
32357 @end cartouche
32358 @end group
32359 @end smallexample
32360
32361 @noindent
32362 If the Ada DLL you are building will only be used by Ada applications
32363 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
32364 convention. As an example, the previous package could be written as
32365 follows:
32366
32367 @smallexample @c ada
32368 @group
32369 @cartouche
32370 package API is
32371    Count : Integer := 0;
32372    function Factorial (Val : Integer) return Integer;
32373
32374    procedure Initialize_API;
32375    procedure Finalize_API;
32376    --  Initialization and Finalization routines.
32377 end API;
32378 @end cartouche
32379 @end group
32380 @end smallexample
32381
32382 @smallexample @c ada
32383 @group
32384 @cartouche
32385 package body API is
32386    function Factorial (Val : Integer) return Integer is
32387       Fact : Integer := 1;
32388    begin
32389       Count := Count + 1;
32390       for K in 1 .. Val loop
32391          Fact := Fact * K;
32392       end loop;
32393       return Fact;
32394    end Factorial;
32395
32396    @dots{}
32397    --  The remainder of this package body is unchanged.
32398 end API;
32399 @end cartouche
32400 @end group
32401 @end smallexample
32402
32403 @noindent
32404 Note that if you do not export the Ada entities with a @code{C} or
32405 @code{Stdcall} convention you will have to provide the mangled Ada names
32406 in the definition file of the Ada DLL
32407 (@pxref{Creating the Definition File}).
32408
32409 @node Ada DLLs and Elaboration
32410 @subsection Ada DLLs and Elaboration
32411 @cindex DLLs and elaboration
32412
32413 @noindent
32414 The DLL that you are building contains your Ada code as well as all the
32415 routines in the Ada library that are needed by it. The first thing a
32416 user of your DLL must do is elaborate the Ada code
32417 (@pxref{Elaboration Order Handling in GNAT}).
32418
32419 To achieve this you must export an initialization routine
32420 (@code{Initialize_API} in the previous example), which must be invoked
32421 before using any of the DLL services. This elaboration routine must call
32422 the Ada elaboration routine @code{adainit} generated by the GNAT binder
32423 (@pxref{Binding with Non-Ada Main Programs}). See the body of
32424 @code{Initialize_Api} for an example. Note that the GNAT binder is
32425 automatically invoked during the DLL build process by the @code{gnatdll}
32426 tool (@pxref{Using gnatdll}).
32427
32428 When a DLL is loaded, Windows systematically invokes a routine called
32429 @code{DllMain}. It would therefore be possible to call @code{adainit}
32430 directly from @code{DllMain} without having to provide an explicit
32431 initialization routine. Unfortunately, it is not possible to call
32432 @code{adainit} from the @code{DllMain} if your program has library level
32433 tasks because access to the @code{DllMain} entry point is serialized by
32434 the system (that is, only a single thread can execute ``through'' it at a
32435 time), which means that the GNAT run time will deadlock waiting for the
32436 newly created task to complete its initialization.
32437
32438 @node Ada DLLs and Finalization
32439 @subsection Ada DLLs and Finalization
32440 @cindex DLLs and finalization
32441
32442 @noindent
32443 When the services of an Ada DLL are no longer needed, the client code should
32444 invoke the DLL finalization routine, if available. The DLL finalization
32445 routine is in charge of releasing all resources acquired by the DLL. In the
32446 case of the Ada code contained in the DLL, this is achieved by calling
32447 routine @code{adafinal} generated by the GNAT binder
32448 (@pxref{Binding with Non-Ada Main Programs}).
32449 See the body of @code{Finalize_Api} for an
32450 example. As already pointed out the GNAT binder is automatically invoked
32451 during the DLL build process by the @code{gnatdll} tool
32452 (@pxref{Using gnatdll}).
32453
32454 @node Creating a Spec for Ada DLLs
32455 @subsection Creating a Spec for Ada DLLs
32456
32457 @noindent
32458 To use the services exported by the Ada DLL from another programming
32459 language (e.g.@: C), you have to translate the specs of the exported Ada
32460 entities in that language. For instance in the case of @code{API.dll},
32461 the corresponding C header file could look like:
32462
32463 @smallexample
32464 @group
32465 @cartouche
32466 extern int *_imp__count;
32467 #define count (*_imp__count)
32468 int factorial (int);
32469 @end cartouche
32470 @end group
32471 @end smallexample
32472
32473 @noindent
32474 It is important to understand that when building an Ada DLL to be used by
32475 other Ada applications, you need two different specs for the packages
32476 contained in the DLL: one for building the DLL and the other for using
32477 the DLL. This is because the @code{DLL} calling convention is needed to
32478 use a variable defined in a DLL, but when building the DLL, the variable
32479 must have either the @code{Ada} or @code{C} calling convention. As an
32480 example consider a DLL comprising the following package @code{API}:
32481
32482 @smallexample @c ada
32483 @group
32484 @cartouche
32485 package API is
32486    Count : Integer := 0;
32487    @dots{}
32488    --  Remainder of the package omitted.
32489 end API;
32490 @end cartouche
32491 @end group
32492 @end smallexample
32493
32494 @noindent
32495 After producing a DLL containing package @code{API}, the spec that
32496 must be used to import @code{API.Count} from Ada code outside of the
32497 DLL is:
32498
32499 @smallexample @c ada
32500 @group
32501 @cartouche
32502 package API is
32503    Count : Integer;
32504    pragma Import (DLL, Count);
32505 end API;
32506 @end cartouche
32507 @end group
32508 @end smallexample
32509
32510 @node Creating the Definition File
32511 @subsection Creating the Definition File
32512
32513 @noindent
32514 The definition file is the last file needed to build the DLL. It lists
32515 the exported symbols. As an example, the definition file for a DLL
32516 containing only package @code{API} (where all the entities are exported
32517 with a @code{C} calling convention) is:
32518
32519 @smallexample
32520 @group
32521 @cartouche
32522 EXPORTS
32523     count
32524     factorial
32525     finalize_api
32526     initialize_api
32527 @end cartouche
32528 @end group
32529 @end smallexample
32530
32531 @noindent
32532 If the @code{C} calling convention is missing from package @code{API},
32533 then the definition file contains the mangled Ada names of the above
32534 entities, which in this case are:
32535
32536 @smallexample
32537 @group
32538 @cartouche
32539 EXPORTS
32540     api__count
32541     api__factorial
32542     api__finalize_api
32543     api__initialize_api
32544 @end cartouche
32545 @end group
32546 @end smallexample
32547
32548 @node Using gnatdll
32549 @subsection Using @code{gnatdll}
32550 @findex gnatdll
32551
32552 @menu
32553 * gnatdll Example::
32554 * gnatdll behind the Scenes::
32555 * Using dlltool::
32556 @end menu
32557
32558 @noindent
32559 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
32560 and non-Ada sources that make up your DLL have been compiled.
32561 @code{gnatdll} is actually in charge of two distinct tasks: build the
32562 static import library for the DLL and the actual DLL. The form of the
32563 @code{gnatdll} command is
32564
32565 @smallexample
32566 @cartouche
32567 $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
32568 @end cartouche
32569 @end smallexample
32570
32571 @noindent
32572 where @var{list-of-files} is a list of ALI and object files. The object
32573 file list must be the exact list of objects corresponding to the non-Ada
32574 sources whose services are to be included in the DLL. The ALI file list
32575 must be the exact list of ALI files for the corresponding Ada sources
32576 whose services are to be included in the DLL. If @var{list-of-files} is
32577 missing, only the static import library is generated.
32578
32579 @noindent
32580 You may specify any of the following switches to @code{gnatdll}:
32581
32582 @table @code
32583 @item -a@ovar{address}
32584 @cindex @option{-a} (@code{gnatdll})
32585 Build a non-relocatable DLL at @var{address}. If @var{address} is not
32586 specified the default address @var{0x11000000} will be used. By default,
32587 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
32588 advise the reader to build relocatable DLL.
32589
32590 @item -b @var{address}
32591 @cindex @option{-b} (@code{gnatdll})
32592 Set the relocatable DLL base address. By default the address is
32593 @code{0x11000000}.
32594
32595 @item -bargs @var{opts}
32596 @cindex @option{-bargs} (@code{gnatdll})
32597 Binder options. Pass @var{opts} to the binder.
32598
32599 @item -d @var{dllfile}
32600 @cindex @option{-d} (@code{gnatdll})
32601 @var{dllfile} is the name of the DLL. This switch must be present for
32602 @code{gnatdll} to do anything. The name of the generated import library is
32603 obtained algorithmically from @var{dllfile} as shown in the following
32604 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
32605 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
32606 by option @option{-e}) is obtained algorithmically from @var{dllfile}
32607 as shown in the following example:
32608 if @var{dllfile} is @code{xyz.dll}, the definition
32609 file used is @code{xyz.def}.
32610
32611 @item -e @var{deffile}
32612 @cindex @option{-e} (@code{gnatdll})
32613 @var{deffile} is the name of the definition file.
32614
32615 @item -g
32616 @cindex @option{-g} (@code{gnatdll})
32617 Generate debugging information. This information is stored in the object
32618 file and copied from there to the final DLL file by the linker,
32619 where it can be read by the debugger. You must use the
32620 @option{-g} switch if you plan on using the debugger or the symbolic
32621 stack traceback.
32622
32623 @item -h
32624 @cindex @option{-h} (@code{gnatdll})
32625 Help mode. Displays @code{gnatdll} switch usage information.
32626
32627 @item -Idir
32628 @cindex @option{-I} (@code{gnatdll})
32629 Direct @code{gnatdll} to search the @var{dir} directory for source and
32630 object files needed to build the DLL.
32631 (@pxref{Search Paths and the Run-Time Library (RTL)}).
32632
32633 @item -k
32634 @cindex @option{-k} (@code{gnatdll})
32635 Removes the @code{@@}@var{nn} suffix from the import library's exported
32636 names, but keeps them for the link names. You must specify this
32637 option if you want to use a @code{Stdcall} function in a DLL for which
32638 the @code{@@}@var{nn} suffix has been removed. This is the case for most
32639 of the Windows NT DLL for example. This option has no effect when
32640 @option{-n} option is specified.
32641
32642 @item -l @var{file}
32643 @cindex @option{-l} (@code{gnatdll})
32644 The list of ALI and object files used to build the DLL are listed in
32645 @var{file}, instead of being given in the command line. Each line in
32646 @var{file} contains the name of an ALI or object file.
32647
32648 @item -n
32649 @cindex @option{-n} (@code{gnatdll})
32650 No Import. Do not create the import library.
32651
32652 @item -q
32653 @cindex @option{-q} (@code{gnatdll})
32654 Quiet mode. Do not display unnecessary messages.
32655
32656 @item -v
32657 @cindex @option{-v} (@code{gnatdll})
32658 Verbose mode. Display extra information.
32659
32660 @item -largs @var{opts}
32661 @cindex @option{-largs} (@code{gnatdll})
32662 Linker options. Pass @var{opts} to the linker.
32663 @end table
32664
32665 @node gnatdll Example
32666 @subsubsection @code{gnatdll} Example
32667
32668 @noindent
32669 As an example the command to build a relocatable DLL from @file{api.adb}
32670 once @file{api.adb} has been compiled and @file{api.def} created is
32671
32672 @smallexample
32673 $ gnatdll -d api.dll api.ali
32674 @end smallexample
32675
32676 @noindent
32677 The above command creates two files: @file{libapi.dll.a} (the import
32678 library) and @file{api.dll} (the actual DLL). If you want to create
32679 only the DLL, just type:
32680
32681 @smallexample
32682 $ gnatdll -d api.dll -n api.ali
32683 @end smallexample
32684
32685 @noindent
32686 Alternatively if you want to create just the import library, type:
32687
32688 @smallexample
32689 $ gnatdll -d api.dll
32690 @end smallexample
32691
32692 @node gnatdll behind the Scenes
32693 @subsubsection @code{gnatdll} behind the Scenes
32694
32695 @noindent
32696 This section details the steps involved in creating a DLL. @code{gnatdll}
32697 does these steps for you. Unless you are interested in understanding what
32698 goes on behind the scenes, you should skip this section.
32699
32700 We use the previous example of a DLL containing the Ada package @code{API},
32701 to illustrate the steps necessary to build a DLL. The starting point is a
32702 set of objects that will make up the DLL and the corresponding ALI
32703 files. In the case of this example this means that @file{api.o} and
32704 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
32705 the following:
32706
32707 @enumerate
32708 @item
32709 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
32710 the information necessary to generate relocation information for the
32711 DLL.
32712
32713 @smallexample
32714 @group
32715 $ gnatbind -n api
32716 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
32717 @end group
32718 @end smallexample
32719
32720 @noindent
32721 In addition to the base file, the @command{gnatlink} command generates an
32722 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
32723 asks @command{gnatlink} to generate the routines @code{DllMain} and
32724 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
32725 is loaded into memory.
32726
32727 @item
32728 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
32729 export table (@file{api.exp}). The export table contains the relocation
32730 information in a form which can be used during the final link to ensure
32731 that the Windows loader is able to place the DLL anywhere in memory.
32732
32733 @smallexample
32734 @group
32735 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32736           --output-exp api.exp
32737 @end group
32738 @end smallexample
32739
32740 @item
32741 @code{gnatdll} builds the base file using the new export table. Note that
32742 @command{gnatbind} must be called once again since the binder generated file
32743 has been deleted during the previous call to @command{gnatlink}.
32744
32745 @smallexample
32746 @group
32747 $ gnatbind -n api
32748 $ gnatlink api -o api.jnk api.exp -mdll
32749       -Wl,--base-file,api.base
32750 @end group
32751 @end smallexample
32752
32753 @item
32754 @code{gnatdll} builds the new export table using the new base file and
32755 generates the DLL import library @file{libAPI.dll.a}.
32756
32757 @smallexample
32758 @group
32759 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32760           --output-exp api.exp --output-lib libAPI.a
32761 @end group
32762 @end smallexample
32763
32764 @item
32765 Finally @code{gnatdll} builds the relocatable DLL using the final export
32766 table.
32767
32768 @smallexample
32769 @group
32770 $ gnatbind -n api
32771 $ gnatlink api api.exp -o api.dll -mdll
32772 @end group
32773 @end smallexample
32774 @end enumerate
32775
32776 @node Using dlltool
32777 @subsubsection Using @code{dlltool}
32778
32779 @noindent
32780 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
32781 DLLs and static import libraries. This section summarizes the most
32782 common @code{dlltool} switches. The form of the @code{dlltool} command
32783 is
32784
32785 @smallexample
32786 $ dlltool @ovar{switches}
32787 @end smallexample
32788
32789 @noindent
32790 @code{dlltool} switches include:
32791
32792 @table @option
32793 @item --base-file @var{basefile}
32794 @cindex @option{--base-file} (@command{dlltool})
32795 Read the base file @var{basefile} generated by the linker. This switch
32796 is used to create a relocatable DLL.
32797
32798 @item --def @var{deffile}
32799 @cindex @option{--def} (@command{dlltool})
32800 Read the definition file.
32801
32802 @item --dllname @var{name}
32803 @cindex @option{--dllname} (@command{dlltool})
32804 Gives the name of the DLL. This switch is used to embed the name of the
32805 DLL in the static import library generated by @code{dlltool} with switch
32806 @option{--output-lib}.
32807
32808 @item -k
32809 @cindex @option{-k} (@command{dlltool})
32810 Kill @code{@@}@var{nn} from exported names
32811 (@pxref{Windows Calling Conventions}
32812 for a discussion about @code{Stdcall}-style symbols.
32813
32814 @item --help
32815 @cindex @option{--help} (@command{dlltool})
32816 Prints the @code{dlltool} switches with a concise description.
32817
32818 @item --output-exp @var{exportfile}
32819 @cindex @option{--output-exp} (@command{dlltool})
32820 Generate an export file @var{exportfile}. The export file contains the
32821 export table (list of symbols in the DLL) and is used to create the DLL.
32822
32823 @item --output-lib @var{libfile}
32824 @cindex @option{--output-lib} (@command{dlltool})
32825 Generate a static import library @var{libfile}.
32826
32827 @item -v
32828 @cindex @option{-v} (@command{dlltool})
32829 Verbose mode.
32830
32831 @item --as @var{assembler-name}
32832 @cindex @option{--as} (@command{dlltool})
32833 Use @var{assembler-name} as the assembler. The default is @code{as}.
32834 @end table
32835
32836 @node GNAT and Windows Resources
32837 @section GNAT and Windows Resources
32838 @cindex Resources, windows
32839
32840 @menu
32841 * Building Resources::
32842 * Compiling Resources::
32843 * Using Resources::
32844 @end menu
32845
32846 @noindent
32847 Resources are an easy way to add Windows specific objects to your
32848 application. The objects that can be added as resources include:
32849
32850 @itemize @bullet
32851 @item
32852 menus
32853
32854 @item
32855 accelerators
32856
32857 @item
32858 dialog boxes
32859
32860 @item
32861 string tables
32862
32863 @item
32864 bitmaps
32865
32866 @item
32867 cursors
32868
32869 @item
32870 icons
32871
32872 @item
32873 fonts
32874 @end itemize
32875
32876 @noindent
32877 This section explains how to build, compile and use resources.
32878
32879 @node Building Resources
32880 @subsection Building Resources
32881 @cindex Resources, building
32882
32883 @noindent
32884 A resource file is an ASCII file. By convention resource files have an
32885 @file{.rc} extension.
32886 The easiest way to build a resource file is to use Microsoft tools
32887 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
32888 @code{dlgedit.exe} to build dialogs.
32889 It is always possible to build an @file{.rc} file yourself by writing a
32890 resource script.
32891
32892 It is not our objective to explain how to write a resource file. A
32893 complete description of the resource script language can be found in the
32894 Microsoft documentation.
32895
32896 @node Compiling Resources
32897 @subsection Compiling Resources
32898 @findex rc
32899 @findex windres
32900 @cindex Resources, compiling
32901
32902 @noindent
32903 This section describes how to build a GNAT-compatible (COFF) object file
32904 containing the resources. This is done using the Resource Compiler
32905 @code{windres} as follows:
32906
32907 @smallexample
32908 $ windres -i myres.rc -o myres.o
32909 @end smallexample
32910
32911 @noindent
32912 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
32913 file. You can specify an alternate preprocessor (usually named
32914 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
32915 parameter. A list of all possible options may be obtained by entering
32916 the command @code{windres} @option{--help}.
32917
32918 It is also possible to use the Microsoft resource compiler @code{rc.exe}
32919 to produce a @file{.res} file (binary resource file). See the
32920 corresponding Microsoft documentation for further details. In this case
32921 you need to use @code{windres} to translate the @file{.res} file to a
32922 GNAT-compatible object file as follows:
32923
32924 @smallexample
32925 $ windres -i myres.res -o myres.o
32926 @end smallexample
32927
32928 @node Using Resources
32929 @subsection Using Resources
32930 @cindex Resources, using
32931
32932 @noindent
32933 To include the resource file in your program just add the
32934 GNAT-compatible object file for the resource(s) to the linker
32935 arguments. With @command{gnatmake} this is done by using the @option{-largs}
32936 option:
32937
32938 @smallexample
32939 $ gnatmake myprog -largs myres.o
32940 @end smallexample
32941
32942 @node Debugging a DLL
32943 @section Debugging a DLL
32944 @cindex DLL debugging
32945
32946 @menu
32947 * Program and DLL Both Built with GCC/GNAT::
32948 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
32949 @end menu
32950
32951 @noindent
32952 Debugging a DLL is similar to debugging a standard program. But
32953 we have to deal with two different executable parts: the DLL and the
32954 program that uses it. We have the following four possibilities:
32955
32956 @enumerate 1
32957 @item
32958 The program and the DLL are built with @code{GCC/GNAT}.
32959 @item
32960 The program is built with foreign tools and the DLL is built with
32961 @code{GCC/GNAT}.
32962 @item
32963 The program is built with @code{GCC/GNAT} and the DLL is built with
32964 foreign tools.
32965 @item
32966 @end enumerate
32967
32968 @noindent
32969 In this section we address only cases one and two above.
32970 There is no point in trying to debug
32971 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
32972 information in it. To do so you must use a debugger compatible with the
32973 tools suite used to build the DLL.
32974
32975 @node Program and DLL Both Built with GCC/GNAT
32976 @subsection Program and DLL Both Built with GCC/GNAT
32977
32978 @noindent
32979 This is the simplest case. Both the DLL and the program have @code{GDB}
32980 compatible debugging information. It is then possible to break anywhere in
32981 the process. Let's suppose here that the main procedure is named
32982 @code{ada_main} and that in the DLL there is an entry point named
32983 @code{ada_dll}.
32984
32985 @noindent
32986 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
32987 program must have been built with the debugging information (see GNAT -g
32988 switch). Here are the step-by-step instructions for debugging it:
32989
32990 @enumerate 1
32991 @item Launch @code{GDB} on the main program.
32992
32993 @smallexample
32994 $ gdb -nw ada_main
32995 @end smallexample
32996
32997 @item Start the program and stop at the beginning of the main procedure
32998
32999 @smallexample
33000 (gdb) start
33001 @end smallexample
33002
33003 @noindent
33004 This step is required to be able to set a breakpoint inside the DLL. As long
33005 as the program is not run, the DLL is not loaded. This has the
33006 consequence that the DLL debugging information is also not loaded, so it is not
33007 possible to set a breakpoint in the DLL.
33008
33009 @item Set a breakpoint inside the DLL
33010
33011 @smallexample
33012 (gdb) break ada_dll
33013 (gdb) cont
33014 @end smallexample
33015
33016 @end enumerate
33017
33018 @noindent
33019 At this stage a breakpoint is set inside the DLL. From there on
33020 you can use the standard approach to debug the whole program
33021 (@pxref{Running and Debugging Ada Programs}).
33022
33023 @ignore
33024 @c This used to work, probably because the DLLs were non-relocatable
33025 @c keep this section around until the problem is sorted out.
33026
33027 To break on the @code{DllMain} routine it is not possible to follow
33028 the procedure above. At the time the program stop on @code{ada_main}
33029 the @code{DllMain} routine as already been called. Either you can use
33030 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
33031
33032 @enumerate 1
33033 @item Launch @code{GDB} on the main program.
33034
33035 @smallexample
33036 $ gdb ada_main
33037 @end smallexample
33038
33039 @item Load DLL symbols
33040
33041 @smallexample
33042 (gdb) add-sym api.dll
33043 @end smallexample
33044
33045 @item Set a breakpoint inside the DLL
33046
33047 @smallexample
33048 (gdb) break ada_dll.adb:45
33049 @end smallexample
33050
33051 Note that at this point it is not possible to break using the routine symbol
33052 directly as the program is not yet running. The solution is to break
33053 on the proper line (break in @file{ada_dll.adb} line 45).
33054
33055 @item Start the program
33056
33057 @smallexample
33058 (gdb) run
33059 @end smallexample
33060
33061 @end enumerate
33062 @end ignore
33063
33064 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
33065 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
33066
33067 @menu
33068 * Debugging the DLL Directly::
33069 * Attaching to a Running Process::
33070 @end menu
33071
33072 @noindent
33073 In this case things are slightly more complex because it is not possible to
33074 start the main program and then break at the beginning to load the DLL and the
33075 associated DLL debugging information. It is not possible to break at the
33076 beginning of the program because there is no @code{GDB} debugging information,
33077 and therefore there is no direct way of getting initial control. This
33078 section addresses this issue by describing some methods that can be used
33079 to break somewhere in the DLL to debug it.
33080
33081 @noindent
33082 First suppose that the main procedure is named @code{main} (this is for
33083 example some C code built with Microsoft Visual C) and that there is a
33084 DLL named @code{test.dll} containing an Ada entry point named
33085 @code{ada_dll}.
33086
33087 @noindent
33088 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
33089 been built with debugging information (see GNAT -g option).
33090
33091 @node Debugging the DLL Directly
33092 @subsubsection Debugging the DLL Directly
33093
33094 @enumerate 1
33095 @item
33096 Find out the executable starting address
33097
33098 @smallexample
33099 $ objdump --file-header main.exe
33100 @end smallexample
33101
33102 The starting address is reported on the last line. For example:
33103
33104 @smallexample
33105 main.exe:     file format pei-i386
33106 architecture: i386, flags 0x0000010a:
33107 EXEC_P, HAS_DEBUG, D_PAGED
33108 start address 0x00401010
33109 @end smallexample
33110
33111 @item
33112 Launch the debugger on the executable.
33113
33114 @smallexample
33115 $ gdb main.exe
33116 @end smallexample
33117
33118 @item
33119 Set a breakpoint at the starting address, and launch the program.
33120
33121 @smallexample
33122 $ (gdb) break *0x00401010
33123 $ (gdb) run
33124 @end smallexample
33125
33126 The program will stop at the given address.
33127
33128 @item
33129 Set a breakpoint on a DLL subroutine.
33130
33131 @smallexample
33132 (gdb) break ada_dll.adb:45
33133 @end smallexample
33134
33135 Or if you want to break using a symbol on the DLL, you need first to
33136 select the Ada language (language used by the DLL).
33137
33138 @smallexample
33139 (gdb) set language ada
33140 (gdb) break ada_dll
33141 @end smallexample
33142
33143 @item
33144 Continue the program.
33145
33146 @smallexample
33147 (gdb) cont
33148 @end smallexample
33149
33150 @noindent
33151 This will run the program until it reaches the breakpoint that has been
33152 set. From that point you can use the standard way to debug a program
33153 as described in (@pxref{Running and Debugging Ada Programs}).
33154
33155 @end enumerate
33156
33157 @noindent
33158 It is also possible to debug the DLL by attaching to a running process.
33159
33160 @node Attaching to a Running Process
33161 @subsubsection Attaching to a Running Process
33162 @cindex DLL debugging, attach to process
33163
33164 @noindent
33165 With @code{GDB} it is always possible to debug a running process by
33166 attaching to it. It is possible to debug a DLL this way. The limitation
33167 of this approach is that the DLL must run long enough to perform the
33168 attach operation. It may be useful for instance to insert a time wasting
33169 loop in the code of the DLL to meet this criterion.
33170
33171 @enumerate 1
33172
33173 @item Launch the main program @file{main.exe}.
33174
33175 @smallexample
33176 $ main
33177 @end smallexample
33178
33179 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
33180 that the process PID for @file{main.exe} is 208.
33181
33182 @item Launch gdb.
33183
33184 @smallexample
33185 $ gdb
33186 @end smallexample
33187
33188 @item Attach to the running process to be debugged.
33189
33190 @smallexample
33191 (gdb) attach 208
33192 @end smallexample
33193
33194 @item Load the process debugging information.
33195
33196 @smallexample
33197 (gdb) symbol-file main.exe
33198 @end smallexample
33199
33200 @item Break somewhere in the DLL.
33201
33202 @smallexample
33203 (gdb) break ada_dll
33204 @end smallexample
33205
33206 @item Continue process execution.
33207
33208 @smallexample
33209 (gdb) cont
33210 @end smallexample
33211
33212 @end enumerate
33213
33214 @noindent
33215 This last step will resume the process execution, and stop at
33216 the breakpoint we have set. From there you can use the standard
33217 approach to debug a program as described in
33218 (@pxref{Running and Debugging Ada Programs}).
33219
33220 @node Setting Stack Size from gnatlink
33221 @section Setting Stack Size from @command{gnatlink}
33222
33223 @noindent
33224 It is possible to specify the program stack size at link time. On modern
33225 versions of Windows, starting with XP, this is mostly useful to set the size of
33226 the main stack (environment task). The other task stacks are set with pragma
33227 Storage_Size or with the @command{gnatbind -d} command.
33228
33229 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
33230 reserve size of individual tasks, the link-time stack size applies to all
33231 tasks, and pragma Storage_Size has no effect.
33232 In particular, Stack Overflow checks are made against this
33233 link-time specified size.
33234
33235 This setting can be done with
33236 @command{gnatlink} using either:
33237
33238 @itemize @bullet
33239
33240 @item using @option{-Xlinker} linker option
33241
33242 @smallexample
33243 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
33244 @end smallexample
33245
33246 This sets the stack reserve size to 0x10000 bytes and the stack commit
33247 size to 0x1000 bytes.
33248
33249 @item using @option{-Wl} linker option
33250
33251 @smallexample
33252 $ gnatlink hello -Wl,--stack=0x1000000
33253 @end smallexample
33254
33255 This sets the stack reserve size to 0x1000000 bytes. Note that with
33256 @option{-Wl} option it is not possible to set the stack commit size
33257 because the coma is a separator for this option.
33258
33259 @end itemize
33260
33261 @node Setting Heap Size from gnatlink
33262 @section Setting Heap Size from @command{gnatlink}
33263
33264 @noindent
33265 Under Windows systems, it is possible to specify the program heap size from
33266 @command{gnatlink} using either:
33267
33268 @itemize @bullet
33269
33270 @item using @option{-Xlinker} linker option
33271
33272 @smallexample
33273 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
33274 @end smallexample
33275
33276 This sets the heap reserve size to 0x10000 bytes and the heap commit
33277 size to 0x1000 bytes.
33278
33279 @item using @option{-Wl} linker option
33280
33281 @smallexample
33282 $ gnatlink hello -Wl,--heap=0x1000000
33283 @end smallexample
33284
33285 This sets the heap reserve size to 0x1000000 bytes. Note that with
33286 @option{-Wl} option it is not possible to set the heap commit size
33287 because the coma is a separator for this option.
33288
33289 @end itemize
33290
33291 @end ifset
33292
33293 @c **********************************
33294 @c * GNU Free Documentation License *
33295 @c **********************************
33296 @include fdl.texi
33297 @c GNU Free Documentation License
33298
33299 @node Index,,GNU Free Documentation License, Top
33300 @unnumbered Index
33301
33302 @printindex cp
33303
33304 @contents
33305 @c Put table of contents at end, otherwise it precedes the "title page" in
33306 @c the .txt version
33307 @c Edit the pdf file to move the contents to the beginning, after the title
33308 @c page
33309
33310 @bye