OSDN Git Service

2009-08-07 Thomas Quinot <quinot@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.texi
1 f\input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c   GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com).   o
11 @c                                                                            o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
13
14 @setfilename gnat_ugn.info
15
16 @copying
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
18 Inc.
19
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.2 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts.  A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
26 @end copying
27
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
29 @c
30 @c                           GNAT_UGN Style Guide
31 @c
32 @c  1. Always put a @noindent on the line before the first paragraph
33 @c     after any of these commands:
34 @c
35 @c          @chapter
36 @c          @section
37 @c          @subsection
38 @c          @subsubsection
39 @c          @subsubsubsection
40 @c
41 @c          @end smallexample
42 @c          @end itemize
43 @c          @end enumerate
44 @c
45 @c  2. DO NOT use @example. Use @smallexample instead.
46 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c        context.  These can interfere with the readability of the texi
48 @c        source file.  Instead, use one of the following annotated
49 @c        @smallexample commands, and preprocess the texi file with the
50 @c        ada2texi tool (which generates appropriate highlighting):
51 @c        @smallexample @c ada
52 @c        @smallexample @c adanocomment
53 @c        @smallexample @c projectfile
54 @c     b) The "@c ada" markup will result in boldface for reserved words
55 @c        and italics for comments
56 @c     c) The "@c adanocomment" markup will result only in boldface for
57 @c        reserved words (comments are left alone)
58 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c        of reserved words include the new reserved words for project files
60 @c
61 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c     command must be preceded by two empty lines
63 @c
64 @c  4. The @item command should be on a line of its own if it is in an
65 @c     @itemize or @enumerate command.
66 @c
67 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
68 @c     or "ali".
69 @c
70 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
71 @c     cause the document build to fail.
72 @c
73 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c     This command inhibits page breaks, so long examples in a @cartouche can
75 @c     lead to large, ugly patches of empty space on a page.
76 @c
77 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c        or the unw flag set.  The unw flag covers topics for both Unix and
79 @c        Windows.
80 @c
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
82
83 @set NOW January 2007
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
89
90 @set FSFEDITION
91 @set EDITION GNAT
92 @set DEFAULTLANGUAGEVERSION Ada 2005
93 @set NONDEFAULTLANGUAGEVERSION Ada 95
94
95 @ifset unw
96 @set PLATFORM
97 @end ifset
98
99 @ifset vms
100 @set PLATFORM OpenVMS
101 @end ifset
102
103 @c @ovar(ARG)
104 @c ----------
105 @c The ARG is an optional argument.  To be used for macro arguments in
106 @c their documentation (@defmac).
107 @macro ovar{varname}
108 @r{[}@var{\varname\}@r{]}@c
109 @end macro
110
111 @settitle @value{EDITION} User's Guide @value{PLATFORM}
112 @dircategory GNU Ada tools
113 @direntry
114 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
115 @end direntry
116
117 @include gcc-common.texi
118
119 @setchapternewpage odd
120 @syncodeindex fn cp
121 @c %**end of header
122
123 @titlepage
124 @title @value{EDITION} User's Guide
125 @ifset vms
126 @sp 1
127 @flushright
128 @titlefont{@i{@value{PLATFORM}}}
129 @end flushright
130 @end ifset
131
132 @sp 2
133
134 @subtitle GNAT, The GNU Ada Compiler
135 @versionsubtitle
136 @author AdaCore
137
138 @page
139 @vskip 0pt plus 1filll
140
141 @insertcopying
142
143 @end titlepage
144
145 @ifnottex
146 @node Top, About This Guide, (dir), (dir)
147 @top @value{EDITION} User's Guide
148
149 @noindent
150 @value{EDITION} User's Guide @value{PLATFORM}
151
152 @noindent
153 GNAT, The GNU Ada Compiler@*
154 GCC version @value{version-GCC}@*
155
156 @noindent
157 AdaCore@*
158
159 @menu
160 * About This Guide::
161 * Getting Started with GNAT::
162 * The GNAT Compilation Model::
163 * Compiling Using gcc::
164 * Binding Using gnatbind::
165 * Linking Using gnatlink::
166 * The GNAT Make Program gnatmake::
167 * Improving Performance::
168 * Renaming Files Using gnatchop::
169 * Configuration Pragmas::
170 * Handling Arbitrary File Naming Conventions Using gnatname::
171 * GNAT Project Manager::
172 * The Cross-Referencing Tools gnatxref and gnatfind::
173 * The GNAT Pretty-Printer gnatpp::
174 * The GNAT Metric Tool gnatmetric::
175 * File Name Krunching Using gnatkr::
176 * Preprocessing Using gnatprep::
177 @ifset vms
178 * The GNAT Run-Time Library Builder gnatlbr::
179 @end ifset
180 * The GNAT Library Browser gnatls::
181 * Cleaning Up Using gnatclean::
182 @ifclear vms
183 * GNAT and Libraries::
184 * Using the GNU make Utility::
185 @end ifclear
186 * Memory Management Issues::
187 * Stack Related Facilities::
188 * Verifying Properties Using gnatcheck::
189 * Creating Sample Bodies Using gnatstub::
190 * Generating Ada Bindings for C and C++ headers::
191 * Other Utility Programs::
192 * Running and Debugging Ada Programs::
193 @ifclear vms
194 * Code Coverage and Profiling::
195 @end ifclear
196 @ifset vms
197 * Compatibility with HP Ada::
198 @end ifset
199 * Platform-Specific Information for the Run-Time Libraries::
200 * Example of Binder Output File::
201 * Elaboration Order Handling in GNAT::
202 * Conditional Compilation::
203 * Inline Assembler::
204 * Compatibility and Porting Guide::
205 @ifset unw
206 * Microsoft Windows Topics::
207 @end ifset
208 * GNU Free Documentation License::
209 * Index::
210
211  --- The Detailed Node Listing ---
212
213 About This Guide
214
215 * What This Guide Contains::
216 * What You Should Know before Reading This Guide::
217 * Related Information::
218 * Conventions::
219
220 Getting Started with GNAT
221
222 * Running GNAT::
223 * Running a Simple Ada Program::
224 * Running a Program with Multiple Units::
225 * Using the gnatmake Utility::
226 @ifset vms
227 * Editing with Emacs::
228 @end ifset
229 @ifclear vms
230 * Introduction to GPS::
231 @end ifclear
232
233 The GNAT Compilation Model
234
235 * Source Representation::
236 * Foreign Language Representation::
237 * File Naming Rules::
238 * Using Other File Names::
239 * Alternative File Naming Schemes::
240 * Generating Object Files::
241 * Source Dependencies::
242 * The Ada Library Information Files::
243 * Binding an Ada Program::
244 * Mixed Language Programming::
245 @ifclear vms
246 * Building Mixed Ada & C++ Programs::
247 * Comparison between GNAT and C/C++ Compilation Models::
248 @end ifclear
249 * Comparison between GNAT and Conventional Ada Library Models::
250 @ifset vms
251 * Placement of temporary files::
252 @end ifset
253
254 Foreign Language Representation
255
256 * Latin-1::
257 * Other 8-Bit Codes::
258 * Wide Character Encodings::
259
260 Compiling Ada Programs With gcc
261
262 * Compiling Programs::
263 * Switches for gcc::
264 * Search Paths and the Run-Time Library (RTL)::
265 * Order of Compilation Issues::
266 * Examples::
267
268 Switches for gcc
269
270 * Output and Error Message Control::
271 * Warning Message Control::
272 * Debugging and Assertion Control::
273 * Validity Checking::
274 * Style Checking::
275 * Run-Time Checks::
276 * Using gcc for Syntax Checking::
277 * Using gcc for Semantic Checking::
278 * Compiling Different Versions of Ada::
279 * Character Set Control::
280 * File Naming Control::
281 * Subprogram Inlining Control::
282 * Auxiliary Output Control::
283 * Debugging Control::
284 * Exception Handling Control::
285 * Units to Sources Mapping Files::
286 * Integrated Preprocessing::
287 @ifset vms
288 * Return Codes::
289 @end ifset
290
291 Binding Ada Programs With gnatbind
292
293 * Running gnatbind::
294 * Switches for gnatbind::
295 * Command-Line Access::
296 * Search Paths for gnatbind::
297 * Examples of gnatbind Usage::
298
299 Switches for gnatbind
300
301 * Consistency-Checking Modes::
302 * Binder Error Message Control::
303 * Elaboration Control::
304 * Output Control::
305 * Binding with Non-Ada Main Programs::
306 * Binding Programs with No Main Subprogram::
307
308 Linking Using gnatlink
309
310 * Running gnatlink::
311 * Switches for gnatlink::
312
313 The GNAT Make Program gnatmake
314
315 * Running gnatmake::
316 * Switches for gnatmake::
317 * Mode Switches for gnatmake::
318 * Notes on the Command Line::
319 * How gnatmake Works::
320 * Examples of gnatmake Usage::
321
322 Improving Performance
323 * Performance Considerations::
324 * Text_IO Suggestions::
325 * Reducing Size of Ada Executables with gnatelim::
326 * Reducing Size of Executables with unused subprogram/data elimination::
327
328 Performance Considerations
329 * Controlling Run-Time Checks::
330 * Use of Restrictions::
331 * Optimization Levels::
332 * Debugging Optimized Code::
333 * Inlining of Subprograms::
334 * Other Optimization Switches::
335 * Optimization and Strict Aliasing::
336 @ifset vms
337 * Coverage Analysis::
338 @end ifset
339
340 Reducing Size of Ada Executables with gnatelim
341 * About gnatelim::
342 * Running gnatelim::
343 * Correcting the List of Eliminate Pragmas::
344 * Making Your Executables Smaller::
345 * Summary of the gnatelim Usage Cycle::
346
347 Reducing Size of Executables with unused subprogram/data elimination
348 * About unused subprogram/data elimination::
349 * Compilation options::
350
351 Renaming Files Using gnatchop
352
353 * Handling Files with Multiple Units::
354 * Operating gnatchop in Compilation Mode::
355 * Command Line for gnatchop::
356 * Switches for gnatchop::
357 * Examples of gnatchop Usage::
358
359 Configuration Pragmas
360
361 * Handling of Configuration Pragmas::
362 * The Configuration Pragmas Files::
363
364 Handling Arbitrary File Naming Conventions Using gnatname
365
366 * Arbitrary File Naming Conventions::
367 * Running gnatname::
368 * Switches for gnatname::
369 * Examples of gnatname Usage::
370
371 GNAT Project Manager
372
373 * Introduction::
374 * Examples of Project Files::
375 * Project File Syntax::
376 * Objects and Sources in Project Files::
377 * Importing Projects::
378 * Project Extension::
379 * Project Hierarchy Extension::
380 * External References in Project Files::
381 * Packages in Project Files::
382 * Variables from Imported Projects::
383 * Naming Schemes::
384 * Library Projects::
385 * Stand-alone Library Projects::
386 * Switches Related to Project Files::
387 * Tools Supporting Project Files::
388 * An Extended Example::
389 * Project File Complete Syntax::
390
391 The Cross-Referencing Tools gnatxref and gnatfind
392
393 * gnatxref Switches::
394 * gnatfind Switches::
395 * Project Files for gnatxref and gnatfind::
396 * Regular Expressions in gnatfind and gnatxref::
397 * Examples of gnatxref Usage::
398 * Examples of gnatfind Usage::
399
400 The GNAT Pretty-Printer gnatpp
401
402 * Switches for gnatpp::
403 * Formatting Rules::
404
405 The GNAT Metrics Tool gnatmetric
406
407 * Switches for gnatmetric::
408
409 File Name Krunching Using gnatkr
410
411 * About gnatkr::
412 * Using gnatkr::
413 * Krunching Method::
414 * Examples of gnatkr Usage::
415
416 Preprocessing Using gnatprep
417 * Preprocessing Symbols::
418 * Using gnatprep::
419 * Switches for gnatprep::
420 * Form of Definitions File::
421 * Form of Input Text for gnatprep::
422
423 @ifset vms
424 The GNAT Run-Time Library Builder gnatlbr
425
426 * Running gnatlbr::
427 * Switches for gnatlbr::
428 * Examples of gnatlbr Usage::
429 @end ifset
430
431 The GNAT Library Browser gnatls
432
433 * Running gnatls::
434 * Switches for gnatls::
435 * Examples of gnatls Usage::
436
437 Cleaning Up Using gnatclean
438
439 * Running gnatclean::
440 * Switches for gnatclean::
441 @c * Examples of gnatclean Usage::
442
443 @ifclear vms
444
445 GNAT and Libraries
446
447 * Introduction to Libraries in GNAT::
448 * General Ada Libraries::
449 * Stand-alone Ada Libraries::
450 * Rebuilding the GNAT Run-Time Library::
451
452 Using the GNU make Utility
453
454 * Using gnatmake in a Makefile::
455 * Automatically Creating a List of Directories::
456 * Generating the Command Line Switches::
457 * Overcoming Command Line Length Limits::
458 @end ifclear
459
460 Memory Management Issues
461
462 * Some Useful Memory Pools::
463 * The GNAT Debug Pool Facility::
464 @ifclear vms
465 * The gnatmem Tool::
466 @end ifclear
467
468 Stack Related Facilities
469
470 * Stack Overflow Checking::
471 * Static Stack Usage Analysis::
472 * Dynamic Stack Usage Analysis::
473
474 Some Useful Memory Pools
475
476 The GNAT Debug Pool Facility
477
478 @ifclear vms
479 The gnatmem Tool
480
481 * Running gnatmem::
482 * Switches for gnatmem::
483 * Example of gnatmem Usage::
484 @end ifclear
485
486 Verifying Properties Using gnatcheck
487
488 * Format of the Report File::
489 * General gnatcheck Switches::
490 * gnatcheck Rule Options::
491 * Adding the Results of Compiler Checks to gnatcheck Output::
492 * Project-Wide Checks::
493 * Rule exemption::
494 * Predefined Rules::
495
496 Sample Bodies Using gnatstub
497
498 * Running gnatstub::
499 * Switches for gnatstub::
500
501 Other Utility Programs
502
503 * Using Other Utility Programs with GNAT::
504 * The External Symbol Naming Scheme of GNAT::
505 * Converting Ada Files to html with gnathtml::
506
507 @ifclear vms
508 Code Coverage and Profiling
509
510 * Code Coverage of Ada Programs using gcov::
511 * Profiling an Ada Program using gprof::
512 @end ifclear
513
514 Running and Debugging Ada Programs
515
516 * The GNAT Debugger GDB::
517 * Running GDB::
518 * Introduction to GDB Commands::
519 * Using Ada Expressions::
520 * Calling User-Defined Subprograms::
521 * Using the Next Command in a Function::
522 * Ada Exceptions::
523 * Ada Tasks::
524 * Debugging Generic Units::
525 * GNAT Abnormal Termination or Failure to Terminate::
526 * Naming Conventions for GNAT Source Files::
527 * Getting Internal Debugging Information::
528 * Stack Traceback::
529
530 @ifset vms
531 * LSE::
532 @end ifset
533
534 @ifset vms
535 Compatibility with HP Ada
536
537 * Ada Language Compatibility::
538 * Differences in the Definition of Package System::
539 * Language-Related Features::
540 * The Package STANDARD::
541 * The Package SYSTEM::
542 * Tasking and Task-Related Features::
543 * Pragmas and Pragma-Related Features::
544 * Library of Predefined Units::
545 * Bindings::
546 * Main Program Definition::
547 * Implementation-Defined Attributes::
548 * Compiler and Run-Time Interfacing::
549 * Program Compilation and Library Management::
550 * Input-Output::
551 * Implementation Limits::
552 * Tools and Utilities::
553
554 Language-Related Features
555
556 * Integer Types and Representations::
557 * Floating-Point Types and Representations::
558 * Pragmas Float_Representation and Long_Float::
559 * Fixed-Point Types and Representations::
560 * Record and Array Component Alignment::
561 * Address Clauses::
562 * Other Representation Clauses::
563
564 Tasking and Task-Related Features
565
566 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
567 * Assigning Task IDs::
568 * Task IDs and Delays::
569 * Task-Related Pragmas::
570 * Scheduling and Task Priority::
571 * The Task Stack::
572 * External Interrupts::
573
574 Pragmas and Pragma-Related Features
575
576 * Restrictions on the Pragma INLINE::
577 * Restrictions on the Pragma INTERFACE::
578 * Restrictions on the Pragma SYSTEM_NAME::
579
580 Library of Predefined Units
581
582 * Changes to DECLIB::
583
584 Bindings
585
586 * Shared Libraries and Options Files::
587 * Interfaces to C::
588 @end ifset
589
590 Platform-Specific Information for the Run-Time Libraries
591
592 * Summary of Run-Time Configurations::
593 * Specifying a Run-Time Library::
594 * Choosing the Scheduling Policy::
595 * Solaris-Specific Considerations::
596 * Linux-Specific Considerations::
597 * AIX-Specific Considerations::
598 * Irix-Specific Considerations::
599
600 Example of Binder Output File
601
602 Elaboration Order Handling in GNAT
603
604 * Elaboration Code::
605 * Checking the Elaboration Order::
606 * Controlling the Elaboration Order::
607 * Controlling Elaboration in GNAT - Internal Calls::
608 * Controlling Elaboration in GNAT - External Calls::
609 * Default Behavior in GNAT - Ensuring Safety::
610 * Treatment of Pragma Elaborate::
611 * Elaboration Issues for Library Tasks::
612 * Mixing Elaboration Models::
613 * What to Do If the Default Elaboration Behavior Fails::
614 * Elaboration for Access-to-Subprogram Values::
615 * Summary of Procedures for Elaboration Control::
616 * Other Elaboration Order Considerations::
617
618 Conditional Compilation
619 * Use of Boolean Constants::
620 * Debugging - A Special Case::
621 * Conditionalizing Declarations::
622 * Use of Alternative Implementations::
623 * Preprocessing::
624
625 Inline Assembler
626
627 * Basic Assembler Syntax::
628 * A Simple Example of Inline Assembler::
629 * Output Variables in Inline Assembler::
630 * Input Variables in Inline Assembler::
631 * Inlining Inline Assembler Code::
632 * Other Asm Functionality::
633
634 Compatibility and Porting Guide
635
636 * Compatibility with Ada 83::
637 * Compatibility between Ada 95 and Ada 2005::
638 * Implementation-dependent characteristics::
639 @ifclear vms
640 @c This brief section is only in the non-VMS version
641 @c The complete chapter on HP Ada issues is in the VMS version
642 * Compatibility with HP Ada 83::
643 @end ifclear
644 * Compatibility with Other Ada Systems::
645 * Representation Clauses::
646 @ifset vms
647 * Transitioning to 64-Bit GNAT for OpenVMS::
648 @end ifset
649
650 @ifset unw
651 Microsoft Windows Topics
652
653 * Using GNAT on Windows::
654 * CONSOLE and WINDOWS subsystems::
655 * Temporary Files::
656 * Mixed-Language Programming on Windows::
657 * Windows Calling Conventions::
658 * Introduction to Dynamic Link Libraries (DLLs)::
659 * Using DLLs with GNAT::
660 * Building DLLs with GNAT::
661 * GNAT and Windows Resources::
662 * Debugging a DLL::
663 * Setting Stack Size from gnatlink::
664 * Setting Heap Size from gnatlink::
665 @end ifset
666
667 * Index::
668 @end menu
669 @end ifnottex
670
671 @node About This Guide
672 @unnumbered About This Guide
673
674 @noindent
675 @ifset vms
676 This guide describes the use of @value{EDITION},
677 a compiler and software development toolset for the full Ada
678 programming language, implemented on OpenVMS for HP's Alpha and
679 Integrity server (I64) platforms.
680 @end ifset
681 @ifclear vms
682 This guide describes the use of @value{EDITION},
683 a compiler and software development
684 toolset for the full Ada programming language.
685 @end ifclear
686 It documents the features of the compiler and tools, and explains
687 how to use them to build Ada applications.
688
689 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
690 Ada 83 compatibility mode.
691 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
692 but you can override with a compiler switch
693 (@pxref{Compiling Different Versions of Ada})
694 to explicitly specify the language version.
695 Throughout this manual, references to ``Ada'' without a year suffix
696 apply to both the Ada 95 and Ada 2005 versions of the language.
697
698
699 @ifclear FSFEDITION
700 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
701 ``GNAT'' in the remainder of this document.
702 @end ifclear
703
704
705
706
707 @menu
708 * What This Guide Contains::
709 * What You Should Know before Reading This Guide::
710 * Related Information::
711 * Conventions::
712 @end menu
713
714 @node What This Guide Contains
715 @unnumberedsec What This Guide Contains
716
717 @noindent
718 This guide contains the following chapters:
719 @itemize @bullet
720
721 @item
722 @ref{Getting Started with GNAT}, describes how to get started compiling
723 and running Ada programs with the GNAT Ada programming environment.
724 @item
725 @ref{The GNAT Compilation Model}, describes the compilation model used
726 by GNAT.
727
728 @item
729 @ref{Compiling Using gcc}, describes how to compile
730 Ada programs with @command{gcc}, the Ada compiler.
731
732 @item
733 @ref{Binding Using gnatbind}, describes how to
734 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
735 utility.
736
737 @item
738 @ref{Linking Using gnatlink},
739 describes @command{gnatlink}, a
740 program that provides for linking using the GNAT run-time library to
741 construct a program. @command{gnatlink} can also incorporate foreign language
742 object units into the executable.
743
744 @item
745 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
746 utility that automatically determines the set of sources
747 needed by an Ada compilation unit, and executes the necessary compilations
748 binding and link.
749
750 @item
751 @ref{Improving Performance}, shows various techniques for making your
752 Ada program run faster or take less space.
753 It discusses the effect of the compiler's optimization switch and
754 also describes the @command{gnatelim} tool and unused subprogram/data
755 elimination.
756
757 @item
758 @ref{Renaming Files Using gnatchop}, describes
759 @code{gnatchop}, a utility that allows you to preprocess a file that
760 contains Ada source code, and split it into one or more new files, one
761 for each compilation unit.
762
763 @item
764 @ref{Configuration Pragmas}, describes the configuration pragmas
765 handled by GNAT.
766
767 @item
768 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
769 shows how to override the default GNAT file naming conventions,
770 either for an individual unit or globally.
771
772 @item
773 @ref{GNAT Project Manager}, describes how to use project files
774 to organize large projects.
775
776 @item
777 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
778 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
779 way to navigate through sources.
780
781 @item
782 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
783 version of an Ada source file with control over casing, indentation,
784 comment placement, and other elements of program presentation style.
785
786 @item
787 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
788 metrics for an Ada source file, such as the number of types and subprograms,
789 and assorted complexity measures.
790
791 @item
792 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
793 file name krunching utility, used to handle shortened
794 file names on operating systems with a limit on the length of names.
795
796 @item
797 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
798 preprocessor utility that allows a single source file to be used to
799 generate multiple or parameterized source files by means of macro
800 substitution.
801
802 @ifset vms
803 @item
804 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
805 a tool for rebuilding the GNAT run time with user-supplied
806 configuration pragmas.
807 @end ifset
808
809 @item
810 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
811 utility that displays information about compiled units, including dependences
812 on the corresponding sources files, and consistency of compilations.
813
814 @item
815 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
816 to delete files that are produced by the compiler, binder and linker.
817
818 @ifclear vms
819 @item
820 @ref{GNAT and Libraries}, describes the process of creating and using
821 Libraries with GNAT. It also describes how to recompile the GNAT run-time
822 library.
823
824 @item
825 @ref{Using the GNU make Utility}, describes some techniques for using
826 the GNAT toolset in Makefiles.
827 @end ifclear
828
829 @item
830 @ref{Memory Management Issues}, describes some useful predefined storage pools
831 and in particular the GNAT Debug Pool facility, which helps detect incorrect
832 memory references.
833 @ifclear vms
834 It also describes @command{gnatmem}, a utility that monitors dynamic
835 allocation and deallocation and helps detect ``memory leaks''.
836 @end ifclear
837
838 @item
839 @ref{Stack Related Facilities}, describes some useful tools associated with
840 stack checking and analysis.
841
842 @item
843 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
844 a utility that checks Ada code against a set of rules.
845
846 @item
847 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
848 a utility that generates empty but compilable bodies for library units.
849
850 @item
851 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
852 generate automatically Ada bindings from C and C++ headers.
853
854 @item
855 @ref{Other Utility Programs}, discusses several other GNAT utilities,
856 including @code{gnathtml}.
857
858 @ifclear vms
859 @item
860 @ref{Code Coverage and Profiling}, describes how to perform a structural
861 coverage and profile the execution of Ada programs.
862 @end ifclear
863
864 @item
865 @ref{Running and Debugging Ada Programs}, describes how to run and debug
866 Ada programs.
867
868 @ifset vms
869 @item
870 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
871 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
872 developed by Digital Equipment Corporation and currently supported by HP.}
873 for OpenVMS Alpha. This product was formerly known as DEC Ada,
874 @cindex DEC Ada
875 and for
876 historical compatibility reasons, the relevant libraries still use the
877 DEC prefix.
878 @end ifset
879
880 @item
881 @ref{Platform-Specific Information for the Run-Time Libraries},
882 describes the various run-time
883 libraries supported by GNAT on various platforms and explains how to
884 choose a particular library.
885
886 @item
887 @ref{Example of Binder Output File}, shows the source code for the binder
888 output file for a sample program.
889
890 @item
891 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
892 you deal with elaboration order issues.
893
894 @item
895 @ref{Conditional Compilation}, describes how to model conditional compilation,
896 both with Ada in general and with GNAT facilities in particular.
897
898 @item
899 @ref{Inline Assembler}, shows how to use the inline assembly facility
900 in an Ada program.
901
902 @item
903 @ref{Compatibility and Porting Guide}, contains sections on compatibility
904 of GNAT with other Ada development environments (including Ada 83 systems),
905 to assist in porting code from those environments.
906
907 @ifset unw
908 @item
909 @ref{Microsoft Windows Topics}, presents information relevant to the
910 Microsoft Windows platform.
911 @end ifset
912 @end itemize
913
914 @c *************************************************
915 @node What You Should Know before Reading This Guide
916 @c *************************************************
917 @unnumberedsec What You Should Know before Reading This Guide
918
919 @cindex Ada 95 Language Reference Manual
920 @cindex Ada 2005 Language Reference Manual
921 @noindent
922 This guide assumes a basic familiarity with the Ada 95 language, as
923 described in the International Standard ANSI/ISO/IEC-8652:1995, January
924 1995.
925 It does not require knowledge of the new features introduced by Ada 2005,
926 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
927 and Amendment 1).
928 Both reference manuals are included in the GNAT documentation
929 package.
930
931 @node Related Information
932 @unnumberedsec Related Information
933
934 @noindent
935 For further information about related tools, refer to the following
936 documents:
937
938 @itemize @bullet
939 @item
940 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
941 Reference Manual}, which contains all reference material for the GNAT
942 implementation of Ada.
943
944 @ifset unw
945 @item
946 @cite{Using the GNAT Programming Studio}, which describes the GPS
947 Integrated Development Environment.
948
949 @item
950 @cite{GNAT Programming Studio Tutorial}, which introduces the
951 main GPS features through examples.
952 @end ifset
953
954 @item
955 @cite{Ada 95 Reference Manual}, which contains reference
956 material for the Ada 95 programming language.
957
958 @item
959 @cite{Ada 2005 Reference Manual}, which contains reference
960 material for the Ada 2005 programming language.
961
962 @item
963 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
964 @ifset vms
965 in the GNU:[DOCS] directory,
966 @end ifset
967 for all details on the use of the GNU source-level debugger.
968
969 @item
970 @xref{Top,, The extensible self-documenting text editor, emacs,
971 GNU Emacs Manual},
972 @ifset vms
973 located in the GNU:[DOCS] directory if the EMACS kit is installed,
974 @end ifset
975 for full information on the extensible editor and programming
976 environment Emacs.
977
978 @end itemize
979
980 @c **************
981 @node Conventions
982 @unnumberedsec Conventions
983 @cindex Conventions
984 @cindex Typographical conventions
985
986 @noindent
987 Following are examples of the typographical and graphic conventions used
988 in this guide:
989
990 @itemize @bullet
991 @item
992 @code{Functions}, @command{utility program names}, @code{standard names},
993 and @code{classes}.
994
995 @item
996 @option{Option flags}
997
998 @item
999 @file{File names}, @samp{button names}, and @samp{field names}.
1000
1001 @item
1002 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1003 variables}.
1004
1005 @item
1006 @emph{Emphasis}.
1007
1008 @item
1009 @r{[}optional information or parameters@r{]}
1010
1011 @item
1012 Examples are described by text
1013 @smallexample
1014 and then shown this way.
1015 @end smallexample
1016 @end itemize
1017
1018 @noindent
1019 Commands that are entered by the user are preceded in this manual by the
1020 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1021 uses this sequence as a prompt, then the commands will appear exactly as
1022 you see them in the manual. If your system uses some other prompt, then
1023 the command will appear with the @code{$} replaced by whatever prompt
1024 character you are using.
1025
1026 @ifset unw
1027 Full file names are shown with the ``@code{/}'' character
1028 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1029 If you are using GNAT on a Windows platform, please note that
1030 the ``@code{\}'' character should be used instead.
1031 @end ifset
1032
1033 @c ****************************
1034 @node Getting Started with GNAT
1035 @chapter Getting Started with GNAT
1036
1037 @noindent
1038 This chapter describes some simple ways of using GNAT to build
1039 executable Ada programs.
1040 @ifset unw
1041 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1042 show how to use the command line environment.
1043 @ref{Introduction to GPS}, provides a brief
1044 introduction to the GNAT Programming Studio, a visually-oriented
1045 Integrated Development Environment for GNAT.
1046 GPS offers a graphical ``look and feel'', support for development in
1047 other programming languages, comprehensive browsing features, and
1048 many other capabilities.
1049 For information on GPS please refer to
1050 @cite{Using the GNAT Programming Studio}.
1051 @end ifset
1052
1053 @menu
1054 * Running GNAT::
1055 * Running a Simple Ada Program::
1056 * Running a Program with Multiple Units::
1057 * Using the gnatmake Utility::
1058 @ifset vms
1059 * Editing with Emacs::
1060 @end ifset
1061 @ifclear vms
1062 * Introduction to GPS::
1063 @end ifclear
1064 @end menu
1065
1066 @node Running GNAT
1067 @section Running GNAT
1068
1069 @noindent
1070 Three steps are needed to create an executable file from an Ada source
1071 file:
1072
1073 @enumerate
1074 @item
1075 The source file(s) must be compiled.
1076 @item
1077 The file(s) must be bound using the GNAT binder.
1078 @item
1079 All appropriate object files must be linked to produce an executable.
1080 @end enumerate
1081
1082 @noindent
1083 All three steps are most commonly handled by using the @command{gnatmake}
1084 utility program that, given the name of the main program, automatically
1085 performs the necessary compilation, binding and linking steps.
1086
1087 @node Running a Simple Ada Program
1088 @section Running a Simple Ada Program
1089
1090 @noindent
1091 Any text editor may be used to prepare an Ada program.
1092 (If @code{Emacs} is
1093 used, the optional Ada mode may be helpful in laying out the program.)
1094 The
1095 program text is a normal text file. We will assume in our initial
1096 example that you have used your editor to prepare the following
1097 standard format text file:
1098
1099 @smallexample @c ada
1100 @cartouche
1101 with Ada.Text_IO; use Ada.Text_IO;
1102 procedure Hello is
1103 begin
1104    Put_Line ("Hello WORLD!");
1105 end Hello;
1106 @end cartouche
1107 @end smallexample
1108
1109 @noindent
1110 This file should be named @file{hello.adb}.
1111 With the normal default file naming conventions, GNAT requires
1112 that each file
1113 contain a single compilation unit whose file name is the
1114 unit name,
1115 with periods replaced by hyphens; the
1116 extension is @file{ads} for a
1117 spec and @file{adb} for a body.
1118 You can override this default file naming convention by use of the
1119 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1120 Alternatively, if you want to rename your files according to this default
1121 convention, which is probably more convenient if you will be using GNAT
1122 for all your compilations, then the @code{gnatchop} utility
1123 can be used to generate correctly-named source files
1124 (@pxref{Renaming Files Using gnatchop}).
1125
1126 You can compile the program using the following command (@code{$} is used
1127 as the command prompt in the examples in this document):
1128
1129 @smallexample
1130 $ gcc -c hello.adb
1131 @end smallexample
1132
1133 @noindent
1134 @command{gcc} is the command used to run the compiler. This compiler is
1135 capable of compiling programs in several languages, including Ada and
1136 C. It assumes that you have given it an Ada program if the file extension is
1137 either @file{.ads} or @file{.adb}, and it will then call
1138 the GNAT compiler to compile the specified file.
1139
1140 @ifclear vms
1141 The @option{-c} switch is required. It tells @command{gcc} to only do a
1142 compilation. (For C programs, @command{gcc} can also do linking, but this
1143 capability is not used directly for Ada programs, so the @option{-c}
1144 switch must always be present.)
1145 @end ifclear
1146
1147 This compile command generates a file
1148 @file{hello.o}, which is the object
1149 file corresponding to your Ada program. It also generates
1150 an ``Ada Library Information'' file @file{hello.ali},
1151 which contains additional information used to check
1152 that an Ada program is consistent.
1153 To build an executable file,
1154 use @code{gnatbind} to bind the program
1155 and @command{gnatlink} to link it. The
1156 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1157 @file{ALI} file, but the default extension of @file{.ali} can
1158 be omitted. This means that in the most common case, the argument
1159 is simply the name of the main program:
1160
1161 @smallexample
1162 $ gnatbind hello
1163 $ gnatlink hello
1164 @end smallexample
1165
1166 @noindent
1167 A simpler method of carrying out these steps is to use
1168 @command{gnatmake},
1169 a master program that invokes all the required
1170 compilation, binding and linking tools in the correct order. In particular,
1171 @command{gnatmake} automatically recompiles any sources that have been
1172 modified since they were last compiled, or sources that depend
1173 on such modified sources, so that ``version skew'' is avoided.
1174 @cindex Version skew (avoided by @command{gnatmake})
1175
1176 @smallexample
1177 $ gnatmake hello.adb
1178 @end smallexample
1179
1180 @noindent
1181 The result is an executable program called @file{hello}, which can be
1182 run by entering:
1183
1184 @smallexample
1185 $ ^hello^RUN HELLO^
1186 @end smallexample
1187
1188 @noindent
1189 assuming that the current directory is on the search path
1190 for executable programs.
1191
1192 @noindent
1193 and, if all has gone well, you will see
1194
1195 @smallexample
1196 Hello WORLD!
1197 @end smallexample
1198
1199 @noindent
1200 appear in response to this command.
1201
1202 @c ****************************************
1203 @node Running a Program with Multiple Units
1204 @section Running a Program with Multiple Units
1205
1206 @noindent
1207 Consider a slightly more complicated example that has three files: a
1208 main program, and the spec and body of a package:
1209
1210 @smallexample @c ada
1211 @cartouche
1212 @group
1213 package Greetings is
1214    procedure Hello;
1215    procedure Goodbye;
1216 end Greetings;
1217
1218 with Ada.Text_IO; use Ada.Text_IO;
1219 package body Greetings is
1220    procedure Hello is
1221    begin
1222       Put_Line ("Hello WORLD!");
1223    end Hello;
1224
1225    procedure Goodbye is
1226    begin
1227       Put_Line ("Goodbye WORLD!");
1228    end Goodbye;
1229 end Greetings;
1230 @end group
1231
1232 @group
1233 with Greetings;
1234 procedure Gmain is
1235 begin
1236    Greetings.Hello;
1237    Greetings.Goodbye;
1238 end Gmain;
1239 @end group
1240 @end cartouche
1241 @end smallexample
1242
1243 @noindent
1244 Following the one-unit-per-file rule, place this program in the
1245 following three separate files:
1246
1247 @table @file
1248 @item greetings.ads
1249 spec of package @code{Greetings}
1250
1251 @item greetings.adb
1252 body of package @code{Greetings}
1253
1254 @item gmain.adb
1255 body of main program
1256 @end table
1257
1258 @noindent
1259 To build an executable version of
1260 this program, we could use four separate steps to compile, bind, and link
1261 the program, as follows:
1262
1263 @smallexample
1264 $ gcc -c gmain.adb
1265 $ gcc -c greetings.adb
1266 $ gnatbind gmain
1267 $ gnatlink gmain
1268 @end smallexample
1269
1270 @noindent
1271 Note that there is no required order of compilation when using GNAT.
1272 In particular it is perfectly fine to compile the main program first.
1273 Also, it is not necessary to compile package specs in the case where
1274 there is an accompanying body; you only need to compile the body. If you want
1275 to submit these files to the compiler for semantic checking and not code
1276 generation, then use the
1277 @option{-gnatc} switch:
1278
1279 @smallexample
1280 $ gcc -c greetings.ads -gnatc
1281 @end smallexample
1282
1283 @noindent
1284 Although the compilation can be done in separate steps as in the
1285 above example, in practice it is almost always more convenient
1286 to use the @command{gnatmake} tool. All you need to know in this case
1287 is the name of the main program's source file. The effect of the above four
1288 commands can be achieved with a single one:
1289
1290 @smallexample
1291 $ gnatmake gmain.adb
1292 @end smallexample
1293
1294 @noindent
1295 In the next section we discuss the advantages of using @command{gnatmake} in
1296 more detail.
1297
1298 @c *****************************
1299 @node Using the gnatmake Utility
1300 @section Using the @command{gnatmake} Utility
1301
1302 @noindent
1303 If you work on a program by compiling single components at a time using
1304 @command{gcc}, you typically keep track of the units you modify. In order to
1305 build a consistent system, you compile not only these units, but also any
1306 units that depend on the units you have modified.
1307 For example, in the preceding case,
1308 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1309 you edit @file{greetings.ads}, you must recompile both
1310 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1311 units that depend on @file{greetings.ads}.
1312
1313 @code{gnatbind} will warn you if you forget one of these compilation
1314 steps, so that it is impossible to generate an inconsistent program as a
1315 result of forgetting to do a compilation. Nevertheless it is tedious and
1316 error-prone to keep track of dependencies among units.
1317 One approach to handle the dependency-bookkeeping is to use a
1318 makefile. However, makefiles present maintenance problems of their own:
1319 if the dependencies change as you change the program, you must make
1320 sure that the makefile is kept up-to-date manually, which is also an
1321 error-prone process.
1322
1323 The @command{gnatmake} utility takes care of these details automatically.
1324 Invoke it using either one of the following forms:
1325
1326 @smallexample
1327 $ gnatmake gmain.adb
1328 $ gnatmake ^gmain^GMAIN^
1329 @end smallexample
1330
1331 @noindent
1332 The argument is the name of the file containing the main program;
1333 you may omit the extension. @command{gnatmake}
1334 examines the environment, automatically recompiles any files that need
1335 recompiling, and binds and links the resulting set of object files,
1336 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1337 In a large program, it
1338 can be extremely helpful to use @command{gnatmake}, because working out by hand
1339 what needs to be recompiled can be difficult.
1340
1341 Note that @command{gnatmake}
1342 takes into account all the Ada rules that
1343 establish dependencies among units. These include dependencies that result
1344 from inlining subprogram bodies, and from
1345 generic instantiation. Unlike some other
1346 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1347 found by the compiler on a previous compilation, which may possibly
1348 be wrong when sources change. @command{gnatmake} determines the exact set of
1349 dependencies from scratch each time it is run.
1350
1351 @ifset vms
1352 @node Editing with Emacs
1353 @section Editing with Emacs
1354 @cindex Emacs
1355
1356 @noindent
1357 Emacs is an extensible self-documenting text editor that is available in a
1358 separate VMSINSTAL kit.
1359
1360 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1361 click on the Emacs Help menu and run the Emacs Tutorial.
1362 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1363 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1364
1365 Documentation on Emacs and other tools is available in Emacs under the
1366 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1367 use the middle mouse button to select a topic (e.g.@: Emacs).
1368
1369 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1370 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1371 get to the Emacs manual.
1372 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1373 prompt.
1374
1375 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1376 which is sufficiently extensible to provide for a complete programming
1377 environment and shell for the sophisticated user.
1378 @end ifset
1379
1380 @ifclear vms
1381 @node Introduction to GPS
1382 @section Introduction to GPS
1383 @cindex GPS (GNAT Programming Studio)
1384 @cindex GNAT Programming Studio (GPS)
1385 @noindent
1386 Although the command line interface (@command{gnatmake}, etc.) alone
1387 is sufficient, a graphical Interactive Development
1388 Environment can make it easier for you to compose, navigate, and debug
1389 programs.  This section describes the main features of GPS
1390 (``GNAT Programming Studio''), the GNAT graphical IDE.
1391 You will see how to use GPS to build and debug an executable, and
1392 you will also learn some of the basics of the GNAT ``project'' facility.
1393
1394 GPS enables you to do much more than is presented here;
1395 e.g., you can produce a call graph, interface to a third-party
1396 Version Control System, and inspect the generated assembly language
1397 for a program.
1398 Indeed, GPS also supports languages other than Ada.
1399 Such additional information, and an explanation of all of the GPS menu
1400 items. may be found in the on-line help, which includes
1401 a user's guide and a tutorial (these are also accessible from the GNAT
1402 startup menu).
1403
1404 @menu
1405 * Building a New Program with GPS::
1406 * Simple Debugging with GPS::
1407 @end menu
1408
1409 @node Building a New Program with GPS
1410 @subsection Building a New Program with GPS
1411 @noindent
1412 GPS invokes the GNAT compilation tools using information
1413 contained in a @emph{project} (also known as a @emph{project file}):
1414 a collection of properties such
1415 as source directories, identities of main subprograms, tool switches, etc.,
1416 and their associated values.
1417 See @ref{GNAT Project Manager} for details.
1418 In order to run GPS, you will need to either create a new project
1419 or else open an existing one.
1420
1421 This section will explain how you can use GPS to create a project,
1422 to associate Ada source files with a project, and to build and run
1423 programs.
1424
1425 @enumerate
1426 @item @emph{Creating a project}
1427
1428 Invoke GPS, either from the command line or the platform's IDE.
1429 After it starts, GPS will display a ``Welcome'' screen with three
1430 radio buttons:
1431
1432 @itemize @bullet
1433 @item
1434 @code{Start with default project in directory}
1435
1436 @item
1437 @code{Create new project with wizard}
1438
1439 @item
1440 @code{Open existing project}
1441 @end itemize
1442
1443 @noindent
1444 Select @code{Create new project with wizard} and press @code{OK}.
1445 A new window will appear.  In the text box labeled with
1446 @code{Enter the name of the project to create}, type @file{sample}
1447 as the project name.
1448 In the next box, browse to choose the directory in which you
1449 would like to create the project file.
1450 After selecting an appropriate directory, press @code{Forward}.
1451
1452 A window will appear with the title
1453 @code{Version Control System Configuration}.
1454 Simply press @code{Forward}.
1455
1456 A window will appear with the title
1457 @code{Please select the source directories for this project}.
1458 The directory that you specified for the project file will be selected
1459 by default as the one to use for sources; simply press @code{Forward}.
1460
1461 A window will appear with the title
1462 @code{Please select the build directory for this project}.
1463 The directory that you specified for the project file will be selected
1464 by default for object files and executables;
1465 simply press @code{Forward}.
1466
1467 A window will appear with the title
1468 @code{Please select the main units for this project}.
1469 You will supply this information later, after creating the source file.
1470 Simply press @code{Forward} for now.
1471
1472 A window will appear with the title
1473 @code{Please select the switches to build the project}.
1474 Press @code{Apply}.  This will create a project file named
1475 @file{sample.prj} in the directory that you had specified.
1476
1477 @item @emph{Creating and saving the source file}
1478
1479 After you create the new project, a GPS window will appear, which is
1480 partitioned into two main sections:
1481
1482 @itemize @bullet
1483 @item
1484 A @emph{Workspace area}, initially greyed out, which you will use for
1485 creating and editing source files
1486
1487 @item
1488 Directly below, a @emph{Messages area}, which initially displays a
1489 ``Welcome'' message.
1490 (If the Messages area is not visible, drag its border upward to expand it.)
1491 @end itemize
1492
1493 @noindent
1494 Select @code{File} on the menu bar, and then the @code{New} command.
1495 The Workspace area will become white, and you can now
1496 enter the source program explicitly.
1497 Type the following text
1498
1499 @smallexample @c ada
1500 @group
1501 with Ada.Text_IO; use Ada.Text_IO;
1502 procedure Hello is
1503 begin
1504   Put_Line("Hello from GPS!");
1505 end Hello;
1506 @end group
1507 @end smallexample
1508
1509 @noindent
1510 Select @code{File}, then @code{Save As}, and enter the source file name
1511 @file{hello.adb}.
1512 The file will be saved in the same directory you specified as the
1513 location of the default project file.
1514
1515 @item @emph{Updating the project file}
1516
1517 You need to add the new source file to the project.
1518 To do this, select
1519 the @code{Project} menu and then @code{Edit project properties}.
1520 Click the @code{Main files} tab on the left, and then the
1521 @code{Add} button.
1522 Choose @file{hello.adb} from the list, and press @code{Open}.
1523 The project settings window will reflect this action.
1524 Click @code{OK}.
1525
1526 @item @emph{Building and running the program}
1527
1528 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1529 and select @file{hello.adb}.
1530 The Messages window will display the resulting invocations of @command{gcc},
1531 @command{gnatbind}, and @command{gnatlink}
1532 (reflecting the default switch settings from the
1533 project file that you created) and then a ``successful compilation/build''
1534 message.
1535
1536 To run the program, choose the @code{Build} menu, then @code{Run}, and
1537 select @command{hello}.
1538 An @emph{Arguments Selection} window will appear.
1539 There are no command line arguments, so just click @code{OK}.
1540
1541 The Messages window will now display the program's output (the string
1542 @code{Hello from GPS}), and at the bottom of the GPS window a status
1543 update is displayed (@code{Run: hello}).
1544 Close the GPS window (or select @code{File}, then @code{Exit}) to
1545 terminate this GPS session.
1546 @end enumerate
1547
1548 @node Simple Debugging with GPS
1549 @subsection Simple Debugging with GPS
1550 @noindent
1551 This section illustrates basic debugging techniques (setting breakpoints,
1552 examining/modifying variables, single stepping).
1553
1554 @enumerate
1555 @item @emph{Opening a project}
1556
1557 Start GPS and select @code{Open existing project}; browse to
1558 specify the project file @file{sample.prj} that you had created in the
1559 earlier example.
1560
1561 @item @emph{Creating a source file}
1562
1563 Select @code{File}, then @code{New}, and type in the following program:
1564
1565 @smallexample @c ada
1566 @group
1567 with Ada.Text_IO; use Ada.Text_IO;
1568 procedure Example is
1569    Line : String (1..80);
1570    N    : Natural;
1571 begin
1572    Put_Line("Type a line of text at each prompt; an empty line to exit");
1573    loop
1574       Put(": ");
1575       Get_Line (Line, N);
1576       Put_Line (Line (1..N) );
1577       exit when N=0;
1578    end loop;
1579 end Example;
1580 @end group
1581 @end smallexample
1582
1583 @noindent
1584 Select @code{File}, then @code{Save as}, and enter the file name
1585 @file{example.adb}.
1586
1587 @item @emph{Updating the project file}
1588
1589 Add @code{Example} as a new main unit for the project:
1590 @enumerate a
1591 @item
1592 Select @code{Project}, then @code{Edit Project Properties}.
1593
1594 @item
1595 Select the @code{Main files} tab, click @code{Add}, then
1596 select the file @file{example.adb} from the list, and
1597 click @code{Open}.
1598 You will see the file name appear in the list of main units
1599
1600 @item
1601 Click @code{OK}
1602 @end enumerate
1603
1604 @item @emph{Building/running the executable}
1605
1606 To build the executable
1607 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1608
1609 Run the program to see its effect (in the Messages area).
1610 Each line that you enter is displayed; an empty line will
1611 cause the loop to exit and the program to terminate.
1612
1613 @item @emph{Debugging the program}
1614
1615 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1616 which are required for debugging, are on by default when you create
1617 a new project.
1618 Thus unless you intentionally remove these settings, you will be able
1619 to debug any program that you develop using GPS.
1620
1621 @enumerate a
1622 @item @emph{Initializing}
1623
1624 Select @code{Debug}, then @code{Initialize}, then @file{example}
1625
1626 @item @emph{Setting a breakpoint}
1627
1628 After performing the initialization step, you will observe a small
1629 icon to the right of each line number.
1630 This serves as a toggle for breakpoints; clicking the icon will
1631 set a breakpoint at the corresponding line (the icon will change to
1632 a red circle with an ``x''), and clicking it again
1633 will remove the breakpoint / reset the icon.
1634
1635 For purposes of this example, set a breakpoint at line 10 (the
1636 statement @code{Put_Line@ (Line@ (1..N));}
1637
1638 @item @emph{Starting program execution}
1639
1640 Select @code{Debug}, then @code{Run}.  When the
1641 @code{Program Arguments} window appears, click @code{OK}.
1642 A console window will appear; enter some line of text,
1643 e.g.@: @code{abcde}, at the prompt.
1644 The program will pause execution when it gets to the
1645 breakpoint, and the corresponding line is highlighted.
1646
1647 @item @emph{Examining a variable}
1648
1649 Move the mouse over one of the occurrences of the variable @code{N}.
1650 You will see the value (5) displayed, in ``tool tip'' fashion.
1651 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1652 You will see information about @code{N} appear in the @code{Debugger Data}
1653 pane, showing the value as 5.
1654
1655 @item @emph{Assigning a new value to a variable}
1656
1657 Right click on the @code{N} in the @code{Debugger Data} pane, and
1658 select @code{Set value of N}.
1659 When the input window appears, enter the value @code{4} and click
1660 @code{OK}.
1661 This value does not automatically appear in the @code{Debugger Data}
1662 pane; to see it, right click again on the @code{N} in the
1663 @code{Debugger Data} pane and select @code{Update value}.
1664 The new value, 4, will appear in red.
1665
1666 @item @emph{Single stepping}
1667
1668 Select @code{Debug}, then @code{Next}.
1669 This will cause the next statement to be executed, in this case the
1670 call of @code{Put_Line} with the string slice.
1671 Notice in the console window that the displayed string is simply
1672 @code{abcd} and not @code{abcde} which you had entered.
1673 This is because the upper bound of the slice is now 4 rather than 5.
1674
1675 @item @emph{Removing a breakpoint}
1676
1677 Toggle the breakpoint icon at line 10.
1678
1679 @item @emph{Resuming execution from a breakpoint}
1680
1681 Select @code{Debug}, then @code{Continue}.
1682 The program will reach the next iteration of the loop, and
1683 wait for input after displaying the prompt.
1684 This time, just hit the @kbd{Enter} key.
1685 The value of @code{N} will be 0, and the program will terminate.
1686 The console window will disappear.
1687 @end enumerate
1688 @end enumerate
1689 @end ifclear
1690
1691 @node The GNAT Compilation Model
1692 @chapter The GNAT Compilation Model
1693 @cindex GNAT compilation model
1694 @cindex Compilation model
1695
1696 @menu
1697 * Source Representation::
1698 * Foreign Language Representation::
1699 * File Naming Rules::
1700 * Using Other File Names::
1701 * Alternative File Naming Schemes::
1702 * Generating Object Files::
1703 * Source Dependencies::
1704 * The Ada Library Information Files::
1705 * Binding an Ada Program::
1706 * Mixed Language Programming::
1707 @ifclear vms
1708 * Building Mixed Ada & C++ Programs::
1709 * Comparison between GNAT and C/C++ Compilation Models::
1710 @end ifclear
1711 * Comparison between GNAT and Conventional Ada Library Models::
1712 @ifset vms
1713 * Placement of temporary files::
1714 @end ifset
1715 @end menu
1716
1717 @noindent
1718 This chapter describes the compilation model used by GNAT. Although
1719 similar to that used by other languages, such as C and C++, this model
1720 is substantially different from the traditional Ada compilation models,
1721 which are based on a library. The model is initially described without
1722 reference to the library-based model. If you have not previously used an
1723 Ada compiler, you need only read the first part of this chapter. The
1724 last section describes and discusses the differences between the GNAT
1725 model and the traditional Ada compiler models. If you have used other
1726 Ada compilers, this section will help you to understand those
1727 differences, and the advantages of the GNAT model.
1728
1729 @node Source Representation
1730 @section Source Representation
1731 @cindex Latin-1
1732
1733 @noindent
1734 Ada source programs are represented in standard text files, using
1735 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1736 7-bit ASCII set, plus additional characters used for
1737 representing foreign languages (@pxref{Foreign Language Representation}
1738 for support of non-USA character sets). The format effector characters
1739 are represented using their standard ASCII encodings, as follows:
1740
1741 @table @code
1742 @item VT
1743 @findex VT
1744 Vertical tab, @code{16#0B#}
1745
1746 @item HT
1747 @findex HT
1748 Horizontal tab, @code{16#09#}
1749
1750 @item CR
1751 @findex CR
1752 Carriage return, @code{16#0D#}
1753
1754 @item LF
1755 @findex LF
1756 Line feed, @code{16#0A#}
1757
1758 @item FF
1759 @findex FF
1760 Form feed, @code{16#0C#}
1761 @end table
1762
1763 @noindent
1764 Source files are in standard text file format. In addition, GNAT will
1765 recognize a wide variety of stream formats, in which the end of
1766 physical lines is marked by any of the following sequences:
1767 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1768 in accommodating files that are imported from other operating systems.
1769
1770 @cindex End of source file
1771 @cindex Source file, end
1772 @findex SUB
1773 The end of a source file is normally represented by the physical end of
1774 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1775 recognized as signalling the end of the source file. Again, this is
1776 provided for compatibility with other operating systems where this
1777 code is used to represent the end of file.
1778
1779 Each file contains a single Ada compilation unit, including any pragmas
1780 associated with the unit. For example, this means you must place a
1781 package declaration (a package @dfn{spec}) and the corresponding body in
1782 separate files. An Ada @dfn{compilation} (which is a sequence of
1783 compilation units) is represented using a sequence of files. Similarly,
1784 you will place each subunit or child unit in a separate file.
1785
1786 @node Foreign Language Representation
1787 @section Foreign Language Representation
1788
1789 @noindent
1790 GNAT supports the standard character sets defined in Ada as well as
1791 several other non-standard character sets for use in localized versions
1792 of the compiler (@pxref{Character Set Control}).
1793 @menu
1794 * Latin-1::
1795 * Other 8-Bit Codes::
1796 * Wide Character Encodings::
1797 @end menu
1798
1799 @node Latin-1
1800 @subsection Latin-1
1801 @cindex Latin-1
1802
1803 @noindent
1804 The basic character set is Latin-1. This character set is defined by ISO
1805 standard 8859, part 1. The lower half (character codes @code{16#00#}
1806 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1807 is used to represent additional characters. These include extended letters
1808 used by European languages, such as French accents, the vowels with umlauts
1809 used in German, and the extra letter A-ring used in Swedish.
1810
1811 @findex Ada.Characters.Latin_1
1812 For a complete list of Latin-1 codes and their encodings, see the source
1813 file of library unit @code{Ada.Characters.Latin_1} in file
1814 @file{a-chlat1.ads}.
1815 You may use any of these extended characters freely in character or
1816 string literals. In addition, the extended characters that represent
1817 letters can be used in identifiers.
1818
1819 @node Other 8-Bit Codes
1820 @subsection Other 8-Bit Codes
1821
1822 @noindent
1823 GNAT also supports several other 8-bit coding schemes:
1824
1825 @table @asis
1826 @item ISO 8859-2 (Latin-2)
1827 @cindex Latin-2
1828 @cindex ISO 8859-2
1829 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1830 equivalence.
1831
1832 @item ISO 8859-3 (Latin-3)
1833 @cindex Latin-3
1834 @cindex ISO 8859-3
1835 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1836 equivalence.
1837
1838 @item ISO 8859-4 (Latin-4)
1839 @cindex Latin-4
1840 @cindex ISO 8859-4
1841 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1842 equivalence.
1843
1844 @item ISO 8859-5 (Cyrillic)
1845 @cindex ISO 8859-5
1846 @cindex Cyrillic
1847 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1848 lowercase equivalence.
1849
1850 @item ISO 8859-15 (Latin-9)
1851 @cindex ISO 8859-15
1852 @cindex Latin-9
1853 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1854 lowercase equivalence
1855
1856 @item IBM PC (code page 437)
1857 @cindex code page 437
1858 This code page is the normal default for PCs in the U.S. It corresponds
1859 to the original IBM PC character set. This set has some, but not all, of
1860 the extended Latin-1 letters, but these letters do not have the same
1861 encoding as Latin-1. In this mode, these letters are allowed in
1862 identifiers with uppercase and lowercase equivalence.
1863
1864 @item IBM PC (code page 850)
1865 @cindex code page 850
1866 This code page is a modification of 437 extended to include all the
1867 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1868 mode, all these letters are allowed in identifiers with uppercase and
1869 lowercase equivalence.
1870
1871 @item Full Upper 8-bit
1872 Any character in the range 80-FF allowed in identifiers, and all are
1873 considered distinct. In other words, there are no uppercase and lowercase
1874 equivalences in this range. This is useful in conjunction with
1875 certain encoding schemes used for some foreign character sets (e.g.,
1876 the typical method of representing Chinese characters on the PC).
1877
1878 @item No Upper-Half
1879 No upper-half characters in the range 80-FF are allowed in identifiers.
1880 This gives Ada 83 compatibility for identifier names.
1881 @end table
1882
1883 @noindent
1884 For precise data on the encodings permitted, and the uppercase and lowercase
1885 equivalences that are recognized, see the file @file{csets.adb} in
1886 the GNAT compiler sources. You will need to obtain a full source release
1887 of GNAT to obtain this file.
1888
1889 @node Wide Character Encodings
1890 @subsection Wide Character Encodings
1891
1892 @noindent
1893 GNAT allows wide character codes to appear in character and string
1894 literals, and also optionally in identifiers, by means of the following
1895 possible encoding schemes:
1896
1897 @table @asis
1898
1899 @item Hex Coding
1900 In this encoding, a wide character is represented by the following five
1901 character sequence:
1902
1903 @smallexample
1904 ESC a b c d
1905 @end smallexample
1906
1907 @noindent
1908 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1909 characters (using uppercase letters) of the wide character code. For
1910 example, ESC A345 is used to represent the wide character with code
1911 @code{16#A345#}.
1912 This scheme is compatible with use of the full Wide_Character set.
1913
1914 @item Upper-Half Coding
1915 @cindex Upper-Half Coding
1916 The wide character with encoding @code{16#abcd#} where the upper bit is on
1917 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1918 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1919 character, but is not required to be in the upper half. This method can
1920 be also used for shift-JIS or EUC, where the internal coding matches the
1921 external coding.
1922
1923 @item Shift JIS Coding
1924 @cindex Shift JIS Coding
1925 A wide character is represented by a two-character sequence,
1926 @code{16#ab#} and
1927 @code{16#cd#}, with the restrictions described for upper-half encoding as
1928 described above. The internal character code is the corresponding JIS
1929 character according to the standard algorithm for Shift-JIS
1930 conversion. Only characters defined in the JIS code set table can be
1931 used with this encoding method.
1932
1933 @item EUC Coding
1934 @cindex EUC Coding
1935 A wide character is represented by a two-character sequence
1936 @code{16#ab#} and
1937 @code{16#cd#}, with both characters being in the upper half. The internal
1938 character code is the corresponding JIS character according to the EUC
1939 encoding algorithm. Only characters defined in the JIS code set table
1940 can be used with this encoding method.
1941
1942 @item UTF-8 Coding
1943 A wide character is represented using
1944 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1945 10646-1/Am.2. Depending on the character value, the representation
1946 is a one, two, or three byte sequence:
1947 @smallexample
1948 @iftex
1949 @leftskip=.7cm
1950 @end iftex
1951 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1952 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1953 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1954
1955 @end smallexample
1956
1957 @noindent
1958 where the @var{xxx} bits correspond to the left-padded bits of the
1959 16-bit character value. Note that all lower half ASCII characters
1960 are represented as ASCII bytes and all upper half characters and
1961 other wide characters are represented as sequences of upper-half
1962 (The full UTF-8 scheme allows for encoding 31-bit characters as
1963 6-byte sequences, but in this implementation, all UTF-8 sequences
1964 of four or more bytes length will be treated as illegal).
1965 @item Brackets Coding
1966 In this encoding, a wide character is represented by the following eight
1967 character sequence:
1968
1969 @smallexample
1970 [ " a b c d " ]
1971 @end smallexample
1972
1973 @noindent
1974 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1975 characters (using uppercase letters) of the wide character code. For
1976 example, [``A345''] is used to represent the wide character with code
1977 @code{16#A345#}. It is also possible (though not required) to use the
1978 Brackets coding for upper half characters. For example, the code
1979 @code{16#A3#} can be represented as @code{[``A3'']}.
1980
1981 This scheme is compatible with use of the full Wide_Character set,
1982 and is also the method used for wide character encoding in the standard
1983 ACVC (Ada Compiler Validation Capability) test suite distributions.
1984
1985 @end table
1986
1987 @noindent
1988 Note: Some of these coding schemes do not permit the full use of the
1989 Ada character set. For example, neither Shift JIS, nor EUC allow the
1990 use of the upper half of the Latin-1 set.
1991
1992 @node File Naming Rules
1993 @section File Naming Rules
1994
1995 @noindent
1996 The default file name is determined by the name of the unit that the
1997 file contains. The name is formed by taking the full expanded name of
1998 the unit and replacing the separating dots with hyphens and using
1999 ^lowercase^uppercase^ for all letters.
2000
2001 An exception arises if the file name generated by the above rules starts
2002 with one of the characters
2003 @ifset vms
2004 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2005 @end ifset
2006 @ifclear vms
2007 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2008 @end ifclear
2009 and the second character is a
2010 minus. In this case, the character ^tilde^dollar sign^ is used in place
2011 of the minus. The reason for this special rule is to avoid clashes with
2012 the standard names for child units of the packages System, Ada,
2013 Interfaces, and GNAT, which use the prefixes
2014 @ifset vms
2015 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2016 @end ifset
2017 @ifclear vms
2018 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2019 @end ifclear
2020 respectively.
2021
2022 The file extension is @file{.ads} for a spec and
2023 @file{.adb} for a body. The following list shows some
2024 examples of these rules.
2025
2026 @table @file
2027 @item main.ads
2028 Main (spec)
2029 @item main.adb
2030 Main (body)
2031 @item arith_functions.ads
2032 Arith_Functions (package spec)
2033 @item arith_functions.adb
2034 Arith_Functions (package body)
2035 @item func-spec.ads
2036 Func.Spec (child package spec)
2037 @item func-spec.adb
2038 Func.Spec (child package body)
2039 @item main-sub.adb
2040 Sub (subunit of Main)
2041 @item ^a~bad.adb^A$BAD.ADB^
2042 A.Bad (child package body)
2043 @end table
2044
2045 @noindent
2046 Following these rules can result in excessively long
2047 file names if corresponding
2048 unit names are long (for example, if child units or subunits are
2049 heavily nested). An option is available to shorten such long file names
2050 (called file name ``krunching''). This may be particularly useful when
2051 programs being developed with GNAT are to be used on operating systems
2052 with limited file name lengths. @xref{Using gnatkr}.
2053
2054 Of course, no file shortening algorithm can guarantee uniqueness over
2055 all possible unit names; if file name krunching is used, it is your
2056 responsibility to ensure no name clashes occur. Alternatively you
2057 can specify the exact file names that you want used, as described
2058 in the next section. Finally, if your Ada programs are migrating from a
2059 compiler with a different naming convention, you can use the gnatchop
2060 utility to produce source files that follow the GNAT naming conventions.
2061 (For details @pxref{Renaming Files Using gnatchop}.)
2062
2063 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2064 systems, case is not significant. So for example on @code{Windows XP}
2065 if the canonical name is @code{main-sub.adb}, you can use the file name
2066 @code{Main-Sub.adb} instead. However, case is significant for other
2067 operating systems, so for example, if you want to use other than
2068 canonically cased file names on a Unix system, you need to follow
2069 the procedures described in the next section.
2070
2071 @node Using Other File Names
2072 @section Using Other File Names
2073 @cindex File names
2074
2075 @noindent
2076 In the previous section, we have described the default rules used by
2077 GNAT to determine the file name in which a given unit resides. It is
2078 often convenient to follow these default rules, and if you follow them,
2079 the compiler knows without being explicitly told where to find all
2080 the files it needs.
2081
2082 However, in some cases, particularly when a program is imported from
2083 another Ada compiler environment, it may be more convenient for the
2084 programmer to specify which file names contain which units. GNAT allows
2085 arbitrary file names to be used by means of the Source_File_Name pragma.
2086 The form of this pragma is as shown in the following examples:
2087 @cindex Source_File_Name pragma
2088
2089 @smallexample @c ada
2090 @cartouche
2091 pragma Source_File_Name (My_Utilities.Stacks,
2092   Spec_File_Name => "myutilst_a.ada");
2093 pragma Source_File_name (My_Utilities.Stacks,
2094   Body_File_Name => "myutilst.ada");
2095 @end cartouche
2096 @end smallexample
2097
2098 @noindent
2099 As shown in this example, the first argument for the pragma is the unit
2100 name (in this example a child unit). The second argument has the form
2101 of a named association. The identifier
2102 indicates whether the file name is for a spec or a body;
2103 the file name itself is given by a string literal.
2104
2105 The source file name pragma is a configuration pragma, which means that
2106 normally it will be placed in the @file{gnat.adc}
2107 file used to hold configuration
2108 pragmas that apply to a complete compilation environment.
2109 For more details on how the @file{gnat.adc} file is created and used
2110 see @ref{Handling of Configuration Pragmas}.
2111 @cindex @file{gnat.adc}
2112
2113 @ifclear vms
2114 GNAT allows completely arbitrary file names to be specified using the
2115 source file name pragma. However, if the file name specified has an
2116 extension other than @file{.ads} or @file{.adb} it is necessary to use
2117 a special syntax when compiling the file. The name in this case must be
2118 preceded by the special sequence @option{-x} followed by a space and the name
2119 of the language, here @code{ada}, as in:
2120
2121 @smallexample
2122 $ gcc -c -x ada peculiar_file_name.sim
2123 @end smallexample
2124 @end ifclear
2125
2126 @noindent
2127 @command{gnatmake} handles non-standard file names in the usual manner (the
2128 non-standard file name for the main program is simply used as the
2129 argument to gnatmake). Note that if the extension is also non-standard,
2130 then it must be included in the @command{gnatmake} command, it may not
2131 be omitted.
2132
2133 @node Alternative File Naming Schemes
2134 @section Alternative File Naming Schemes
2135 @cindex File naming schemes, alternative
2136 @cindex File names
2137
2138 In the previous section, we described the use of the @code{Source_File_Name}
2139 pragma to allow arbitrary names to be assigned to individual source files.
2140 However, this approach requires one pragma for each file, and especially in
2141 large systems can result in very long @file{gnat.adc} files, and also create
2142 a maintenance problem.
2143
2144 GNAT also provides a facility for specifying systematic file naming schemes
2145 other than the standard default naming scheme previously described. An
2146 alternative scheme for naming is specified by the use of
2147 @code{Source_File_Name} pragmas having the following format:
2148 @cindex Source_File_Name pragma
2149
2150 @smallexample @c ada
2151 pragma Source_File_Name (
2152    Spec_File_Name  => FILE_NAME_PATTERN
2153  @r{[},Casing          => CASING_SPEC@r{]}
2154  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2155
2156 pragma Source_File_Name (
2157    Body_File_Name  => FILE_NAME_PATTERN
2158  @r{[},Casing          => CASING_SPEC@r{]}
2159  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2160
2161 pragma Source_File_Name (
2162    Subunit_File_Name  => FILE_NAME_PATTERN
2163  @r{[},Casing             => CASING_SPEC@r{]}
2164  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2165
2166 FILE_NAME_PATTERN ::= STRING_LITERAL
2167 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2168 @end smallexample
2169
2170 @noindent
2171 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2172 It contains a single asterisk character, and the unit name is substituted
2173 systematically for this asterisk. The optional parameter
2174 @code{Casing} indicates
2175 whether the unit name is to be all upper-case letters, all lower-case letters,
2176 or mixed-case. If no
2177 @code{Casing} parameter is used, then the default is all
2178 ^lower-case^upper-case^.
2179
2180 The optional @code{Dot_Replacement} string is used to replace any periods
2181 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2182 argument is used then separating dots appear unchanged in the resulting
2183 file name.
2184 Although the above syntax indicates that the
2185 @code{Casing} argument must appear
2186 before the @code{Dot_Replacement} argument, but it
2187 is also permissible to write these arguments in the opposite order.
2188
2189 As indicated, it is possible to specify different naming schemes for
2190 bodies, specs, and subunits. Quite often the rule for subunits is the
2191 same as the rule for bodies, in which case, there is no need to give
2192 a separate @code{Subunit_File_Name} rule, and in this case the
2193 @code{Body_File_name} rule is used for subunits as well.
2194
2195 The separate rule for subunits can also be used to implement the rather
2196 unusual case of a compilation environment (e.g.@: a single directory) which
2197 contains a subunit and a child unit with the same unit name. Although
2198 both units cannot appear in the same partition, the Ada Reference Manual
2199 allows (but does not require) the possibility of the two units coexisting
2200 in the same environment.
2201
2202 The file name translation works in the following steps:
2203
2204 @itemize @bullet
2205
2206 @item
2207 If there is a specific @code{Source_File_Name} pragma for the given unit,
2208 then this is always used, and any general pattern rules are ignored.
2209
2210 @item
2211 If there is a pattern type @code{Source_File_Name} pragma that applies to
2212 the unit, then the resulting file name will be used if the file exists. If
2213 more than one pattern matches, the latest one will be tried first, and the
2214 first attempt resulting in a reference to a file that exists will be used.
2215
2216 @item
2217 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2218 for which the corresponding file exists, then the standard GNAT default
2219 naming rules are used.
2220
2221 @end itemize
2222
2223 @noindent
2224 As an example of the use of this mechanism, consider a commonly used scheme
2225 in which file names are all lower case, with separating periods copied
2226 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2227 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2228 two pragmas appear:
2229
2230 @smallexample @c ada
2231 pragma Source_File_Name
2232   (Spec_File_Name => "*.1.ada");
2233 pragma Source_File_Name
2234   (Body_File_Name => "*.2.ada");
2235 @end smallexample
2236
2237 @noindent
2238 The default GNAT scheme is actually implemented by providing the following
2239 default pragmas internally:
2240
2241 @smallexample @c ada
2242 pragma Source_File_Name
2243   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2244 pragma Source_File_Name
2245   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2246 @end smallexample
2247
2248 @noindent
2249 Our final example implements a scheme typically used with one of the
2250 Ada 83 compilers, where the separator character for subunits was ``__''
2251 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2252 by adding @file{.ADA}, and subunits by
2253 adding @file{.SEP}. All file names were
2254 upper case. Child units were not present of course since this was an
2255 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2256 the same double underscore separator for child units.
2257
2258 @smallexample @c ada
2259 pragma Source_File_Name
2260   (Spec_File_Name => "*_.ADA",
2261    Dot_Replacement => "__",
2262    Casing = Uppercase);
2263 pragma Source_File_Name
2264   (Body_File_Name => "*.ADA",
2265    Dot_Replacement => "__",
2266    Casing = Uppercase);
2267 pragma Source_File_Name
2268   (Subunit_File_Name => "*.SEP",
2269    Dot_Replacement => "__",
2270    Casing = Uppercase);
2271 @end smallexample
2272
2273 @node Generating Object Files
2274 @section Generating Object Files
2275
2276 @noindent
2277 An Ada program consists of a set of source files, and the first step in
2278 compiling the program is to generate the corresponding object files.
2279 These are generated by compiling a subset of these source files.
2280 The files you need to compile are the following:
2281
2282 @itemize @bullet
2283 @item
2284 If a package spec has no body, compile the package spec to produce the
2285 object file for the package.
2286
2287 @item
2288 If a package has both a spec and a body, compile the body to produce the
2289 object file for the package. The source file for the package spec need
2290 not be compiled in this case because there is only one object file, which
2291 contains the code for both the spec and body of the package.
2292
2293 @item
2294 For a subprogram, compile the subprogram body to produce the object file
2295 for the subprogram. The spec, if one is present, is as usual in a
2296 separate file, and need not be compiled.
2297
2298 @item
2299 @cindex Subunits
2300 In the case of subunits, only compile the parent unit. A single object
2301 file is generated for the entire subunit tree, which includes all the
2302 subunits.
2303
2304 @item
2305 Compile child units independently of their parent units
2306 (though, of course, the spec of all the ancestor unit must be present in order
2307 to compile a child unit).
2308
2309 @item
2310 @cindex Generics
2311 Compile generic units in the same manner as any other units. The object
2312 files in this case are small dummy files that contain at most the
2313 flag used for elaboration checking. This is because GNAT always handles generic
2314 instantiation by means of macro expansion. However, it is still necessary to
2315 compile generic units, for dependency checking and elaboration purposes.
2316 @end itemize
2317
2318 @noindent
2319 The preceding rules describe the set of files that must be compiled to
2320 generate the object files for a program. Each object file has the same
2321 name as the corresponding source file, except that the extension is
2322 @file{.o} as usual.
2323
2324 You may wish to compile other files for the purpose of checking their
2325 syntactic and semantic correctness. For example, in the case where a
2326 package has a separate spec and body, you would not normally compile the
2327 spec. However, it is convenient in practice to compile the spec to make
2328 sure it is error-free before compiling clients of this spec, because such
2329 compilations will fail if there is an error in the spec.
2330
2331 GNAT provides an option for compiling such files purely for the
2332 purposes of checking correctness; such compilations are not required as
2333 part of the process of building a program. To compile a file in this
2334 checking mode, use the @option{-gnatc} switch.
2335
2336 @node Source Dependencies
2337 @section Source Dependencies
2338
2339 @noindent
2340 A given object file clearly depends on the source file which is compiled
2341 to produce it. Here we are using @dfn{depends} in the sense of a typical
2342 @code{make} utility; in other words, an object file depends on a source
2343 file if changes to the source file require the object file to be
2344 recompiled.
2345 In addition to this basic dependency, a given object may depend on
2346 additional source files as follows:
2347
2348 @itemize @bullet
2349 @item
2350 If a file being compiled @code{with}'s a unit @var{X}, the object file
2351 depends on the file containing the spec of unit @var{X}. This includes
2352 files that are @code{with}'ed implicitly either because they are parents
2353 of @code{with}'ed child units or they are run-time units required by the
2354 language constructs used in a particular unit.
2355
2356 @item
2357 If a file being compiled instantiates a library level generic unit, the
2358 object file depends on both the spec and body files for this generic
2359 unit.
2360
2361 @item
2362 If a file being compiled instantiates a generic unit defined within a
2363 package, the object file depends on the body file for the package as
2364 well as the spec file.
2365
2366 @item
2367 @findex Inline
2368 @cindex @option{-gnatn} switch
2369 If a file being compiled contains a call to a subprogram for which
2370 pragma @code{Inline} applies and inlining is activated with the
2371 @option{-gnatn} switch, the object file depends on the file containing the
2372 body of this subprogram as well as on the file containing the spec. Note
2373 that for inlining to actually occur as a result of the use of this switch,
2374 it is necessary to compile in optimizing mode.
2375
2376 @cindex @option{-gnatN} switch
2377 The use of @option{-gnatN} activates  inlining optimization
2378 that is performed by the front end of the compiler. This inlining does
2379 not require that the code generation be optimized. Like @option{-gnatn},
2380 the use of this switch generates additional dependencies.
2381
2382 When using a gcc-based back end (in practice this means using any version
2383 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2384 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2385 Historically front end inlining was more extensive than the gcc back end
2386 inlining, but that is no longer the case.
2387
2388 @item
2389 If an object file @file{O} depends on the proper body of a subunit through
2390 inlining or instantiation, it depends on the parent unit of the subunit.
2391 This means that any modification of the parent unit or one of its subunits
2392 affects the compilation of @file{O}.
2393
2394 @item
2395 The object file for a parent unit depends on all its subunit body files.
2396
2397 @item
2398 The previous two rules meant that for purposes of computing dependencies and
2399 recompilation, a body and all its subunits are treated as an indivisible whole.
2400
2401 @noindent
2402 These rules are applied transitively: if unit @code{A} @code{with}'s
2403 unit @code{B}, whose elaboration calls an inlined procedure in package
2404 @code{C}, the object file for unit @code{A} will depend on the body of
2405 @code{C}, in file @file{c.adb}.
2406
2407 The set of dependent files described by these rules includes all the
2408 files on which the unit is semantically dependent, as dictated by the
2409 Ada language standard. However, it is a superset of what the
2410 standard describes, because it includes generic, inline, and subunit
2411 dependencies.
2412
2413 An object file must be recreated by recompiling the corresponding source
2414 file if any of the source files on which it depends are modified. For
2415 example, if the @code{make} utility is used to control compilation,
2416 the rule for an Ada object file must mention all the source files on
2417 which the object file depends, according to the above definition.
2418 The determination of the necessary
2419 recompilations is done automatically when one uses @command{gnatmake}.
2420 @end itemize
2421
2422 @node The Ada Library Information Files
2423 @section The Ada Library Information Files
2424 @cindex Ada Library Information files
2425 @cindex @file{ALI} files
2426
2427 @noindent
2428 Each compilation actually generates two output files. The first of these
2429 is the normal object file that has a @file{.o} extension. The second is a
2430 text file containing full dependency information. It has the same
2431 name as the source file, but an @file{.ali} extension.
2432 This file is known as the Ada Library Information (@file{ALI}) file.
2433 The following information is contained in the @file{ALI} file.
2434
2435 @itemize @bullet
2436 @item
2437 Version information (indicates which version of GNAT was used to compile
2438 the unit(s) in question)
2439
2440 @item
2441 Main program information (including priority and time slice settings,
2442 as well as the wide character encoding used during compilation).
2443
2444 @item
2445 List of arguments used in the @command{gcc} command for the compilation
2446
2447 @item
2448 Attributes of the unit, including configuration pragmas used, an indication
2449 of whether the compilation was successful, exception model used etc.
2450
2451 @item
2452 A list of relevant restrictions applying to the unit (used for consistency)
2453 checking.
2454
2455 @item
2456 Categorization information (e.g.@: use of pragma @code{Pure}).
2457
2458 @item
2459 Information on all @code{with}'ed units, including presence of
2460 @code{Elaborate} or @code{Elaborate_All} pragmas.
2461
2462 @item
2463 Information from any @code{Linker_Options} pragmas used in the unit
2464
2465 @item
2466 Information on the use of @code{Body_Version} or @code{Version}
2467 attributes in the unit.
2468
2469 @item
2470 Dependency information. This is a list of files, together with
2471 time stamp and checksum information. These are files on which
2472 the unit depends in the sense that recompilation is required
2473 if any of these units are modified.
2474
2475 @item
2476 Cross-reference data. Contains information on all entities referenced
2477 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2478 provide cross-reference information.
2479
2480 @end itemize
2481
2482 @noindent
2483 For a full detailed description of the format of the @file{ALI} file,
2484 see the source of the body of unit @code{Lib.Writ}, contained in file
2485 @file{lib-writ.adb} in the GNAT compiler sources.
2486
2487 @node Binding an Ada Program
2488 @section Binding an Ada Program
2489
2490 @noindent
2491 When using languages such as C and C++, once the source files have been
2492 compiled the only remaining step in building an executable program
2493 is linking the object modules together. This means that it is possible to
2494 link an inconsistent version of a program, in which two units have
2495 included different versions of the same header.
2496
2497 The rules of Ada do not permit such an inconsistent program to be built.
2498 For example, if two clients have different versions of the same package,
2499 it is illegal to build a program containing these two clients.
2500 These rules are enforced by the GNAT binder, which also determines an
2501 elaboration order consistent with the Ada rules.
2502
2503 The GNAT binder is run after all the object files for a program have
2504 been created. It is given the name of the main program unit, and from
2505 this it determines the set of units required by the program, by reading the
2506 corresponding ALI files. It generates error messages if the program is
2507 inconsistent or if no valid order of elaboration exists.
2508
2509 If no errors are detected, the binder produces a main program, in Ada by
2510 default, that contains calls to the elaboration procedures of those
2511 compilation unit that require them, followed by
2512 a call to the main program. This Ada program is compiled to generate the
2513 object file for the main program. The name of
2514 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2515 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2516 main program unit.
2517
2518 Finally, the linker is used to build the resulting executable program,
2519 using the object from the main program from the bind step as well as the
2520 object files for the Ada units of the program.
2521
2522 @node Mixed Language Programming
2523 @section Mixed Language Programming
2524 @cindex Mixed Language Programming
2525
2526 @noindent
2527 This section describes how to develop a mixed-language program,
2528 specifically one that comprises units in both Ada and C.
2529
2530 @menu
2531 * Interfacing to C::
2532 * Calling Conventions::
2533 @end menu
2534
2535 @node Interfacing to C
2536 @subsection Interfacing to C
2537 @noindent
2538 Interfacing Ada with a foreign language such as C involves using
2539 compiler directives to import and/or export entity definitions in each
2540 language---using @code{extern} statements in C, for instance, and the
2541 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2542 A full treatment of these topics is provided in Appendix B, section 1
2543 of the Ada Reference Manual.
2544
2545 There are two ways to build a program using GNAT that contains some Ada
2546 sources and some foreign language sources, depending on whether or not
2547 the main subprogram is written in Ada.  Here is a source example with
2548 the main subprogram in Ada:
2549
2550 @smallexample
2551 /* file1.c */
2552 #include <stdio.h>
2553
2554 void print_num (int num)
2555 @{
2556   printf ("num is %d.\n", num);
2557   return;
2558 @}
2559
2560 /* file2.c */
2561
2562 /* num_from_Ada is declared in my_main.adb */
2563 extern int num_from_Ada;
2564
2565 int get_num (void)
2566 @{
2567   return num_from_Ada;
2568 @}
2569 @end smallexample
2570
2571 @smallexample @c ada
2572 --  my_main.adb
2573 procedure My_Main is
2574
2575    --  Declare then export an Integer entity called num_from_Ada
2576    My_Num : Integer := 10;
2577    pragma Export (C, My_Num, "num_from_Ada");
2578
2579    --  Declare an Ada function spec for Get_Num, then use
2580    --  C function get_num for the implementation.
2581    function Get_Num return Integer;
2582    pragma Import (C, Get_Num, "get_num");
2583
2584    --  Declare an Ada procedure spec for Print_Num, then use
2585    --  C function print_num for the implementation.
2586    procedure Print_Num (Num : Integer);
2587    pragma Import (C, Print_Num, "print_num");
2588
2589 begin
2590    Print_Num (Get_Num);
2591 end My_Main;
2592 @end smallexample
2593
2594 @enumerate
2595 @item
2596 To build this example, first compile the foreign language files to
2597 generate object files:
2598 @smallexample
2599 ^gcc -c file1.c^gcc -c FILE1.C^
2600 ^gcc -c file2.c^gcc -c FILE2.C^
2601 @end smallexample
2602
2603 @item
2604 Then, compile the Ada units to produce a set of object files and ALI
2605 files:
2606 @smallexample
2607 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2608 @end smallexample
2609
2610 @item
2611 Run the Ada binder on the Ada main program:
2612 @smallexample
2613 gnatbind my_main.ali
2614 @end smallexample
2615
2616 @item
2617 Link the Ada main program, the Ada objects and the other language
2618 objects:
2619 @smallexample
2620 gnatlink my_main.ali file1.o file2.o
2621 @end smallexample
2622 @end enumerate
2623
2624 The last three steps can be grouped in a single command:
2625 @smallexample
2626 gnatmake my_main.adb -largs file1.o file2.o
2627 @end smallexample
2628
2629 @cindex Binder output file
2630 @noindent
2631 If the main program is in a language other than Ada, then you may have
2632 more than one entry point into the Ada subsystem. You must use a special
2633 binder option to generate callable routines that initialize and
2634 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2635 Calls to the initialization and finalization routines must be inserted
2636 in the main program, or some other appropriate point in the code. The
2637 call to initialize the Ada units must occur before the first Ada
2638 subprogram is called, and the call to finalize the Ada units must occur
2639 after the last Ada subprogram returns. The binder will place the
2640 initialization and finalization subprograms into the
2641 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2642 sources.  To illustrate, we have the following example:
2643
2644 @smallexample
2645 /* main.c */
2646 extern void adainit (void);
2647 extern void adafinal (void);
2648 extern int add (int, int);
2649 extern int sub (int, int);
2650
2651 int main (int argc, char *argv[])
2652 @{
2653   int a = 21, b = 7;
2654
2655   adainit();
2656
2657   /* Should print "21 + 7 = 28" */
2658   printf ("%d + %d = %d\n", a, b, add (a, b));
2659   /* Should print "21 - 7 = 14" */
2660   printf ("%d - %d = %d\n", a, b, sub (a, b));
2661
2662   adafinal();
2663 @}
2664 @end smallexample
2665
2666 @smallexample @c ada
2667 --  unit1.ads
2668 package Unit1 is
2669    function Add (A, B : Integer) return Integer;
2670    pragma Export (C, Add, "add");
2671 end Unit1;
2672
2673 --  unit1.adb
2674 package body Unit1 is
2675    function Add (A, B : Integer) return Integer is
2676    begin
2677       return A + B;
2678    end Add;
2679 end Unit1;
2680
2681 --  unit2.ads
2682 package Unit2 is
2683    function Sub (A, B : Integer) return Integer;
2684    pragma Export (C, Sub, "sub");
2685 end Unit2;
2686
2687 --  unit2.adb
2688 package body Unit2 is
2689    function Sub (A, B : Integer) return Integer is
2690    begin
2691       return A - B;
2692    end Sub;
2693 end Unit2;
2694 @end smallexample
2695
2696 @enumerate
2697 @item
2698 The build procedure for this application is similar to the last
2699 example's.  First, compile the foreign language files to generate object
2700 files:
2701 @smallexample
2702 ^gcc -c main.c^gcc -c main.c^
2703 @end smallexample
2704
2705 @item
2706 Next, compile the Ada units to produce a set of object files and ALI
2707 files:
2708 @smallexample
2709 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2710 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2711 @end smallexample
2712
2713 @item
2714 Run the Ada binder on every generated ALI file.  Make sure to use the
2715 @option{-n} option to specify a foreign main program:
2716 @smallexample
2717 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2718 @end smallexample
2719
2720 @item
2721 Link the Ada main program, the Ada objects and the foreign language
2722 objects. You need only list the last ALI file here:
2723 @smallexample
2724 gnatlink unit2.ali main.o -o exec_file
2725 @end smallexample
2726
2727 This procedure yields a binary executable called @file{exec_file}.
2728 @end enumerate
2729
2730 @noindent
2731 Depending on the circumstances (for example when your non-Ada main object
2732 does not provide symbol @code{main}), you may also need to instruct the
2733 GNAT linker not to include the standard startup objects by passing the
2734 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2735
2736 @node Calling Conventions
2737 @subsection Calling Conventions
2738 @cindex Foreign Languages
2739 @cindex Calling Conventions
2740 GNAT follows standard calling sequence conventions and will thus interface
2741 to any other language that also follows these conventions. The following
2742 Convention identifiers are recognized by GNAT:
2743
2744 @table @code
2745 @cindex Interfacing to Ada
2746 @cindex Other Ada compilers
2747 @cindex Convention Ada
2748 @item Ada
2749 This indicates that the standard Ada calling sequence will be
2750 used and all Ada data items may be passed without any limitations in the
2751 case where GNAT is used to generate both the caller and callee. It is also
2752 possible to mix GNAT generated code and code generated by another Ada
2753 compiler. In this case, the data types should be restricted to simple
2754 cases, including primitive types. Whether complex data types can be passed
2755 depends on the situation. Probably it is safe to pass simple arrays, such
2756 as arrays of integers or floats. Records may or may not work, depending
2757 on whether both compilers lay them out identically. Complex structures
2758 involving variant records, access parameters, tasks, or protected types,
2759 are unlikely to be able to be passed.
2760
2761 Note that in the case of GNAT running
2762 on a platform that supports HP Ada 83, a higher degree of compatibility
2763 can be guaranteed, and in particular records are layed out in an identical
2764 manner in the two compilers. Note also that if output from two different
2765 compilers is mixed, the program is responsible for dealing with elaboration
2766 issues. Probably the safest approach is to write the main program in the
2767 version of Ada other than GNAT, so that it takes care of its own elaboration
2768 requirements, and then call the GNAT-generated adainit procedure to ensure
2769 elaboration of the GNAT components. Consult the documentation of the other
2770 Ada compiler for further details on elaboration.
2771
2772 However, it is not possible to mix the tasking run time of GNAT and
2773 HP Ada 83, All the tasking operations must either be entirely within
2774 GNAT compiled sections of the program, or entirely within HP Ada 83
2775 compiled sections of the program.
2776
2777 @cindex Interfacing to Assembly
2778 @cindex Convention Assembler
2779 @item Assembler
2780 Specifies assembler as the convention. In practice this has the
2781 same effect as convention Ada (but is not equivalent in the sense of being
2782 considered the same convention).
2783
2784 @cindex Convention Asm
2785 @findex Asm
2786 @item Asm
2787 Equivalent to Assembler.
2788
2789 @cindex Interfacing to COBOL
2790 @cindex Convention COBOL
2791 @findex COBOL
2792 @item COBOL
2793 Data will be passed according to the conventions described
2794 in section B.4 of the Ada Reference Manual.
2795
2796 @findex C
2797 @cindex Interfacing to C
2798 @cindex Convention C
2799 @item C
2800 Data will be passed according to the conventions described
2801 in section B.3 of the Ada Reference Manual.
2802
2803 A note on interfacing to a C ``varargs'' function:
2804 @findex C varargs function
2805 @cindex Interfacing to C varargs function
2806 @cindex varargs function interfaces
2807
2808 @itemize @bullet
2809 @item
2810 In C, @code{varargs} allows a function to take a variable number of
2811 arguments. There is no direct equivalent in this to Ada. One
2812 approach that can be used is to create a C wrapper for each
2813 different profile and then interface to this C wrapper. For
2814 example, to print an @code{int} value using @code{printf},
2815 create a C function @code{printfi} that takes two arguments, a
2816 pointer to a string and an int, and calls @code{printf}.
2817 Then in the Ada program, use pragma @code{Import} to
2818 interface to @code{printfi}.
2819
2820 @item
2821 It may work on some platforms to directly interface to
2822 a @code{varargs} function by providing a specific Ada profile
2823 for a particular call. However, this does not work on
2824 all platforms, since there is no guarantee that the
2825 calling sequence for a two argument normal C function
2826 is the same as for calling a @code{varargs} C function with
2827 the same two arguments.
2828 @end itemize
2829
2830 @cindex Convention Default
2831 @findex Default
2832 @item Default
2833 Equivalent to C.
2834
2835 @cindex Convention External
2836 @findex External
2837 @item External
2838 Equivalent to C.
2839
2840 @ifclear vms
2841 @findex C++
2842 @cindex Interfacing to C++
2843 @cindex Convention C++
2844 @item C_Plus_Plus (or CPP)
2845 This stands for C++. For most purposes this is identical to C.
2846 See the separate description of the specialized GNAT pragmas relating to
2847 C++ interfacing for further details.
2848 @end ifclear
2849
2850 @findex Fortran
2851 @cindex Interfacing to Fortran
2852 @cindex Convention Fortran
2853 @item Fortran
2854 Data will be passed according to the conventions described
2855 in section B.5 of the Ada Reference Manual.
2856
2857 @item Intrinsic
2858 This applies to an intrinsic operation, as defined in the Ada
2859 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2860 this means that the body of the subprogram is provided by the compiler itself,
2861 usually by means of an efficient code sequence, and that the user does not
2862 supply an explicit body for it. In an application program, the pragma may
2863 be applied to the following sets of names:
2864
2865 @itemize @bullet
2866 @item
2867 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2868 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2869 two formal parameters. The
2870 first one must be a signed integer type or a modular type with a binary
2871 modulus, and the second parameter must be of type Natural.
2872 The return type must be the same as the type of the first argument. The size
2873 of this type can only be 8, 16, 32, or 64.
2874
2875 @item
2876 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2877 The corresponding operator declaration must have parameters and result type
2878 that have the same root numeric type (for example, all three are long_float
2879 types). This simplifies the definition of operations that use type checking
2880 to perform dimensional checks:
2881
2882 @smallexample @c ada
2883 type Distance is new Long_Float;
2884 type Time     is new Long_Float;
2885 type Velocity is new Long_Float;
2886 function "/" (D : Distance; T : Time)
2887   return Velocity;
2888 pragma Import (Intrinsic, "/");
2889 @end smallexample
2890
2891 @noindent
2892 This common idiom is often programmed with a generic definition and an
2893 explicit body. The pragma makes it simpler to introduce such declarations.
2894 It incurs no overhead in compilation time or code size, because it is
2895 implemented as a single machine instruction.
2896
2897 @item
2898 General subprogram entities, to bind an Ada subprogram declaration to
2899 a compiler builtin by name with back-ends where such interfaces are
2900 available. A typical example is the set of ``__builtin'' functions
2901 exposed by the GCC back-end, as in the following example:
2902
2903 @smallexample @c ada
2904    function builtin_sqrt (F : Float) return Float;
2905    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2906 @end smallexample
2907
2908 Most of the GCC builtins are accessible this way, and as for other
2909 import conventions (e.g. C), it is the user's responsibility to ensure
2910 that the Ada subprogram profile matches the underlying builtin
2911 expectations.
2912 @end itemize
2913
2914 @noindent
2915
2916 @ifset unw
2917 @findex Stdcall
2918 @cindex Convention Stdcall
2919 @item Stdcall
2920 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2921 and specifies that the @code{Stdcall} calling sequence will be used,
2922 as defined by the NT API. Nevertheless, to ease building
2923 cross-platform bindings this convention will be handled as a @code{C} calling
2924 convention on non-Windows platforms.
2925
2926 @findex DLL
2927 @cindex Convention DLL
2928 @item DLL
2929 This is equivalent to @code{Stdcall}.
2930
2931 @findex Win32
2932 @cindex Convention Win32
2933 @item Win32
2934 This is equivalent to @code{Stdcall}.
2935 @end ifset
2936
2937 @findex Stubbed
2938 @cindex Convention Stubbed
2939 @item Stubbed
2940 This is a special convention that indicates that the compiler
2941 should provide a stub body that raises @code{Program_Error}.
2942 @end table
2943
2944 @noindent
2945 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2946 that can be used to parametrize conventions and allow additional synonyms
2947 to be specified. For example if you have legacy code in which the convention
2948 identifier Fortran77 was used for Fortran, you can use the configuration
2949 pragma:
2950
2951 @smallexample @c ada
2952 pragma Convention_Identifier (Fortran77, Fortran);
2953 @end smallexample
2954
2955 @noindent
2956 And from now on the identifier Fortran77 may be used as a convention
2957 identifier (for example in an @code{Import} pragma) with the same
2958 meaning as Fortran.
2959
2960 @ifclear vms
2961 @node Building Mixed Ada & C++ Programs
2962 @section Building Mixed Ada and C++ Programs
2963
2964 @noindent
2965 A programmer inexperienced with mixed-language development may find that
2966 building an application containing both Ada and C++ code can be a
2967 challenge.  This section gives a few
2968 hints that should make this task easier. The first section addresses
2969 the differences between interfacing with C and interfacing with C++.
2970 The second section
2971 looks into the delicate problem of linking the complete application from
2972 its Ada and C++ parts. The last section gives some hints on how the GNAT
2973 run-time library can be adapted in order to allow inter-language dispatching
2974 with a new C++ compiler.
2975
2976 @menu
2977 * Interfacing to C++::
2978 * Linking a Mixed C++ & Ada Program::
2979 * A Simple Example::
2980 * Interfacing with C++ constructors::
2981 * Interfacing with C++ at the Class Level::
2982 @end menu
2983
2984 @node Interfacing to C++
2985 @subsection Interfacing to C++
2986
2987 @noindent
2988 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2989 generating code that is compatible with the G++ Application Binary
2990 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2991
2992 @noindent
2993 Interfacing can be done at 3 levels: simple data, subprograms, and
2994 classes. In the first two cases, GNAT offers a specific @code{Convention
2995 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2996 Usually, C++ mangles the names of subprograms. To generate proper mangled
2997 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2998 This problem can also be addressed manually in two ways:
2999
3000 @itemize @bullet
3001 @item
3002 by modifying the C++ code in order to force a C convention using
3003 the @code{extern "C"} syntax.
3004
3005 @item
3006 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
3007 Link_Name argument of the pragma import.
3008 @end itemize
3009
3010 @noindent
3011 Interfacing at the class level can be achieved by using the GNAT specific
3012 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3013 gnat_rm, GNAT Reference Manual}, for additional information.
3014
3015 @node Linking a Mixed C++ & Ada Program
3016 @subsection Linking a Mixed C++ & Ada Program
3017
3018 @noindent
3019 Usually the linker of the C++ development system must be used to link
3020 mixed applications because most C++ systems will resolve elaboration
3021 issues (such as calling constructors on global class instances)
3022 transparently during the link phase. GNAT has been adapted to ease the
3023 use of a foreign linker for the last phase. Three cases can be
3024 considered:
3025 @enumerate
3026
3027 @item
3028 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3029 The C++ linker can simply be called by using the C++ specific driver
3030 called @code{g++}.
3031
3032 Note that if the C++ code uses inline functions, you will need to
3033 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3034 order to provide an existing function implementation that the Ada code can
3035 link with.
3036
3037 @smallexample
3038 $ g++ -c -fkeep-inline-functions file1.C
3039 $ g++ -c -fkeep-inline-functions file2.C
3040 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3041 @end smallexample
3042
3043 @item
3044 Using GNAT and G++ from two different GCC installations: If both
3045 compilers are on the @env{PATH}, the previous method may be used. It is
3046 important to note that environment variables such as
3047 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3048 @env{GCC_ROOT} will affect both compilers
3049 at the same time and may make one of the two compilers operate
3050 improperly if set during invocation of the wrong compiler.  It is also
3051 very important that the linker uses the proper @file{libgcc.a} GCC
3052 library -- that is, the one from the C++ compiler installation. The
3053 implicit link command as suggested in the @command{gnatmake} command
3054 from the former example can be replaced by an explicit link command with
3055 the full-verbosity option in order to verify which library is used:
3056 @smallexample
3057 $ gnatbind ada_unit
3058 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3059 @end smallexample
3060 If there is a problem due to interfering environment variables, it can
3061 be worked around by using an intermediate script. The following example
3062 shows the proper script to use when GNAT has not been installed at its
3063 default location and g++ has been installed at its default location:
3064
3065 @smallexample
3066 $ cat ./my_script
3067 #!/bin/sh
3068 unset BINUTILS_ROOT
3069 unset GCC_ROOT
3070 c++ $*
3071 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3072 @end smallexample
3073
3074 @item
3075 Using a non-GNU C++ compiler: The commands previously described can be
3076 used to insure that the C++ linker is used. Nonetheless, you need to add
3077 a few more parameters to the link command line, depending on the exception
3078 mechanism used.
3079
3080 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3081 to the libgcc libraries are required:
3082
3083 @smallexample
3084 $ cat ./my_script
3085 #!/bin/sh
3086 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3087 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3088 @end smallexample
3089
3090 Where CC is the name of the non-GNU C++ compiler.
3091
3092 If the @code{zero cost} exception mechanism is used, and the platform
3093 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3094 paths to more objects are required:
3095
3096 @smallexample
3097 $ cat ./my_script
3098 #!/bin/sh
3099 CC `gcc -print-file-name=crtbegin.o` $* \
3100 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3101 `gcc -print-file-name=crtend.o`
3102 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3103 @end smallexample
3104
3105 If the @code{zero cost} exception mechanism is used, and the platform
3106 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3107 Tru64 or AIX), the simple approach described above will not work and
3108 a pre-linking phase using GNAT will be necessary.
3109
3110 @end enumerate
3111
3112 Another alternative is to use the @command{gprbuild} multi-language builder
3113 which has a large knowledge base and knows how to link Ada and C++ code
3114 together automatically in most cases.
3115
3116 @node A Simple Example
3117 @subsection  A Simple Example
3118 @noindent
3119 The following example, provided as part of the GNAT examples, shows how
3120 to achieve procedural interfacing between Ada and C++ in both
3121 directions. The C++ class A has two methods. The first method is exported
3122 to Ada by the means of an extern C wrapper function. The second method
3123 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3124 a limited record with a layout comparable to the C++ class. The Ada
3125 subprogram, in turn, calls the C++ method. So, starting from the C++
3126 main program, the process passes back and forth between the two
3127 languages.
3128
3129 @noindent
3130 Here are the compilation commands:
3131 @smallexample
3132 $ gnatmake -c simple_cpp_interface
3133 $ g++ -c cpp_main.C
3134 $ g++ -c ex7.C
3135 $ gnatbind -n simple_cpp_interface
3136 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3137       -lstdc++ ex7.o cpp_main.o
3138 @end smallexample
3139
3140 @noindent
3141 Here are the corresponding sources:
3142 @smallexample
3143
3144 //cpp_main.C
3145
3146 #include "ex7.h"
3147
3148 extern "C" @{
3149   void adainit (void);
3150   void adafinal (void);
3151   void method1 (A *t);
3152 @}
3153
3154 void method1 (A *t)
3155 @{
3156   t->method1 ();
3157 @}
3158
3159 int main ()
3160 @{
3161   A obj;
3162   adainit ();
3163   obj.method2 (3030);
3164   adafinal ();
3165 @}
3166
3167 //ex7.h
3168
3169 class Origin @{
3170  public:
3171   int o_value;
3172 @};
3173 class A : public Origin @{
3174  public:
3175   void method1 (void);
3176   void method2 (int v);
3177   A();
3178   int   a_value;
3179 @};
3180
3181 //ex7.C
3182
3183 #include "ex7.h"
3184 #include <stdio.h>
3185
3186 extern "C" @{ void ada_method2 (A *t, int v);@}
3187
3188 void A::method1 (void)
3189 @{
3190   a_value = 2020;
3191   printf ("in A::method1, a_value = %d \n",a_value);
3192
3193 @}
3194
3195 void A::method2 (int v)
3196 @{
3197    ada_method2 (this, v);
3198    printf ("in A::method2, a_value = %d \n",a_value);
3199
3200 @}
3201
3202 A::A(void)
3203 @{
3204    a_value = 1010;
3205   printf ("in A::A, a_value = %d \n",a_value);
3206 @}
3207 @end smallexample
3208
3209 @smallexample @c ada
3210 -- Ada sources
3211 package body Simple_Cpp_Interface is
3212
3213    procedure Ada_Method2 (This : in out A; V : Integer) is
3214    begin
3215       Method1 (This);
3216       This.A_Value := V;
3217    end Ada_Method2;
3218
3219 end Simple_Cpp_Interface;
3220
3221 with System;
3222 package Simple_Cpp_Interface is
3223    type A is limited
3224       record
3225          Vptr    : System.Address;
3226          O_Value : Integer;
3227          A_Value : Integer;
3228       end record;
3229    pragma Convention (C, A);
3230
3231    procedure Method1 (This : in out A);
3232    pragma Import (C, Method1);
3233
3234    procedure Ada_Method2 (This : in out A; V : Integer);
3235    pragma Export (C, Ada_Method2);
3236
3237 end Simple_Cpp_Interface;
3238 @end smallexample
3239
3240 @node Interfacing with C++ constructors
3241 @subsection Interfacing with C++ constructors
3242 @noindent
3243
3244 In order to interface with C++ constructors GNAT provides the
3245 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3246 gnat_rm, GNAT Reference Manual}, for additional information).
3247 In this section we present some common uses of C++ constructors
3248 in mixed-languages programs in GNAT.
3249
3250 Let us assume that we need to interface with the following
3251 C++ class:
3252
3253 @smallexample
3254 @b{class} Root @{
3255 @b{public}:
3256   int  a_value;
3257   int  b_value;
3258   @b{virtual} int Get_Value ();
3259   Root();              // Default constructor
3260   Root(int v);         // 1st non-default constructor
3261   Root(int v, int w);  // 2nd non-default constructor
3262 @};
3263 @end smallexample
3264
3265 For this purpose we can write the following package spec (further
3266 information on how to build this spec is available in
3267 @ref{Interfacing with C++ at the Class Level} and
3268 @ref{Generating Ada Bindings for C and C++ headers}).
3269
3270 @smallexample @c ada
3271 with Interfaces.C; use Interfaces.C;
3272 package Pkg_Root is
3273   type Root is tagged limited record
3274      A_Value : int;
3275      B_Value : int;
3276   end record;
3277   pragma Import (CPP, Root);
3278
3279   function Get_Value (Obj : Root) return int;
3280   pragma Import (CPP, Get_Value);
3281
3282   function Constructor return Root;
3283   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3284
3285   function Constructor (v : Integer) return Root;
3286   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3287
3288   function Constructor (v, w : Integer) return Root;
3289   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3290 end Pkg_Root;
3291 @end smallexample
3292
3293 On the Ada side the constructor is represented by a function (whose
3294 name is arbitrary) that returns the classwide type corresponding to
3295 the imported C++ class. Although the constructor is described as a
3296 function, it is typically a procedure with an extra implicit argument
3297 (the object being initialized) at the implementation level. GNAT
3298 issues the appropriate call, whatever it is, to get the object
3299 properly initialized.
3300
3301 Constructors can only appear in the following contexts:
3302
3303 @itemize @bullet
3304 @item
3305 On the right side of an initialization of an object of type @var{T}.
3306 @item
3307 On the right side of an initialization of a record component of type @var{T}.
3308 @item
3309 In an Ada 2005 limited aggregate.
3310 @item
3311 In an Ada 2005 nested limited aggregate.
3312 @item
3313 In an Ada 2005 limited aggregate that initializes an object built in
3314 place by an extended return statement.
3315 @end itemize
3316
3317 @noindent
3318 In a declaration of an object whose type is a class imported from C++,
3319 either the default C++ constructor is implicitly called by GNAT, or
3320 else the required C++ constructor must be explicitly called in the
3321 expression that initializes the object. For example:
3322
3323 @smallexample @c ada
3324   Obj1 : Root;
3325   Obj2 : Root := Constructor;
3326   Obj3 : Root := Constructor (v => 10);
3327   Obj4 : Root := Constructor (30, 40);
3328 @end smallexample
3329
3330 The first two declarations are equivalent: in both cases the default C++
3331 constructor is invoked (in the former case the call to the constructor is
3332 implicit, and in the latter case the call is explicit in the object
3333 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3334 that takes an integer argument, and @code{Obj4} is initialized by the
3335 non-default C++ constructor that takes two integers.
3336
3337 Let us derive the imported C++ class in the Ada side. For example:
3338
3339 @smallexample @c ada
3340   type DT is new Root with record
3341      C_Value : Natural := 2009;
3342   end record;
3343 @end smallexample
3344
3345 In this case the components DT inherited from the C++ side must be
3346 initialized by a C++ constructor, and the additional Ada components
3347 of type DT are initialized by GNAT. The initialization of such an
3348 object is done either by default, or by means of a function returning
3349 an aggregate of type DT, or by means of an extension aggregate.
3350
3351 @smallexample @c ada
3352   Obj5 : DT;
3353   Obj6 : DT := Function_Returning_DT (50);
3354   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3355 @end smallexample
3356
3357 The declaration of @code{Obj5} invokes the default constructors: the
3358 C++ default constructor of the parent type takes care of the initialization
3359 of the components inherited from Root, and GNAT takes care of the default
3360 initialization of the additional Ada components of type DT (that is,
3361 @code{C_Value} is initialized to value 2009). The order of invocation of
3362 the constructors is consistent with the order of elaboration required by
3363 Ada and C++. That is, the constructor of the parent type is always called
3364 before the constructor of the derived type.
3365
3366 Let us now consider a record that has components whose type is imported
3367 from C++. For example:
3368
3369 @smallexample @c ada
3370   type Rec1 is limited record
3371      Data1 : Root := Constructor (10);
3372      Value : Natural := 1000;
3373   end record;
3374
3375   type Rec2 (D : Integer := 20) is limited record
3376      Rec   : Rec1;
3377      Data2 : Root := Constructor (D, 30);
3378   end record;
3379 @end smallexample
3380
3381 The initialization of an object of type @code{Rec2} will call the
3382 non-default C++ constructors specified for the imported components.
3383 For example:
3384
3385 @smallexample @c ada
3386   Obj8 : Rec2 (40);
3387 @end smallexample
3388
3389 Using Ada 2005 we can use limited aggregates to initialize an object
3390 invoking C++ constructors that differ from those specified in the type
3391 declarations. For example:
3392
3393 @smallexample @c ada
3394   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3395                           others => <>),
3396                   others => <>);
3397 @end smallexample
3398
3399 The above declaration uses an Ada 2005 limited aggregate to
3400 initialize @code{Obj9}, and the C++ constructor that has two integer
3401 arguments is invoked to initialize the @code{Data1} component instead
3402 of the constructor specified in the declaration of type @code{Rec1}. In
3403 Ada 2005 the box in the aggregate indicates that unspecified components
3404 are initialized using the expression (if any) available in the component
3405 declaration. That is, in this case discriminant @code{D} is initialized
3406 to value @code{20}, @code{Value} is initialized to value 1000, and the
3407 non-default C++ constructor that handles two integers takes care of
3408 initializing component @code{Data2} with values @code{20,30}.
3409
3410 In Ada 2005 we can use the extended return statement to build the Ada
3411 equivalent to C++ non-default constructors. For example:
3412
3413 @smallexample @c ada
3414   function Constructor (V : Integer) return Rec2 is
3415   begin
3416      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3417                                    others => <>),
3418                            others => <>) do
3419         --  Further actions required for construction of
3420         --  objects of type Rec2
3421         ...
3422      end record;
3423   end Constructor;
3424 @end smallexample
3425
3426 In this example the extended return statement construct is used to
3427 build in place the returned object whose components are initialized
3428 by means of a limited aggregate. Any further action associated with
3429 the constructor can be placed inside the construct.
3430
3431 @node Interfacing with C++ at the Class Level
3432 @subsection Interfacing with C++ at the Class Level
3433 @noindent
3434 In this section we demonstrate the GNAT features for interfacing with
3435 C++ by means of an example making use of Ada 2005 abstract interface
3436 types. This example consists of a classification of animals; classes
3437 have been used to model our main classification of animals, and
3438 interfaces provide support for the management of secondary
3439 classifications. We first demonstrate a case in which the types and
3440 constructors are defined on the C++ side and imported from the Ada
3441 side, and latter the reverse case.
3442
3443 The root of our derivation will be the @code{Animal} class, with a
3444 single private attribute (the @code{Age} of the animal) and two public
3445 primitives to set and get the value of this attribute.
3446
3447 @smallexample
3448 @b{class} Animal @{
3449  @b{public}:
3450    @b{virtual} void Set_Age (int New_Age);
3451    @b{virtual} int Age ();
3452  @b{private}:
3453    int Age_Count;
3454 @};
3455 @end smallexample
3456
3457 Abstract interface types are defined in C++ by means of classes with pure
3458 virtual functions and no data members. In our example we will use two
3459 interfaces that provide support for the common management of @code{Carnivore}
3460 and @code{Domestic} animals:
3461
3462 @smallexample
3463 @b{class} Carnivore @{
3464 @b{public}:
3465    @b{virtual} int Number_Of_Teeth () = 0;
3466 @};
3467
3468 @b{class} Domestic @{
3469 @b{public}:
3470    @b{virtual void} Set_Owner (char* Name) = 0;
3471 @};
3472 @end smallexample
3473
3474 Using these declarations, we can now say that a @code{Dog} is an animal that is
3475 both Carnivore and Domestic, that is:
3476
3477 @smallexample
3478 @b{class} Dog : Animal, Carnivore, Domestic @{
3479  @b{public}:
3480    @b{virtual} int  Number_Of_Teeth ();
3481    @b{virtual} void Set_Owner (char* Name);
3482
3483    Dog(); // Constructor
3484  @b{private}:
3485    int  Tooth_Count;
3486    char *Owner;
3487 @};
3488 @end smallexample
3489
3490 In the following examples we will assume that the previous declarations are
3491 located in a file named @code{animals.h}. The following package demonstrates
3492 how to import these C++ declarations from the Ada side:
3493
3494 @smallexample @c ada
3495 with Interfaces.C.Strings; use Interfaces.C.Strings;
3496 package Animals is
3497   type Carnivore is interface;
3498   pragma Convention (C_Plus_Plus, Carnivore);
3499   function Number_Of_Teeth (X : Carnivore)
3500      return Natural is abstract;
3501
3502   type Domestic is interface;
3503   pragma Convention (C_Plus_Plus, Set_Owner);
3504   procedure Set_Owner
3505     (X    : in out Domestic;
3506      Name : Chars_Ptr) is abstract;
3507
3508   type Animal is tagged record
3509     Age : Natural := 0;
3510   end record;
3511   pragma Import (C_Plus_Plus, Animal);
3512
3513   procedure Set_Age (X : in out Animal; Age : Integer);
3514   pragma Import (C_Plus_Plus, Set_Age);
3515
3516   function Age (X : Animal) return Integer;
3517   pragma Import (C_Plus_Plus, Age);
3518
3519   type Dog is new Animal and Carnivore and Domestic with record
3520     Tooth_Count : Natural;
3521     Owner       : String (1 .. 30);
3522   end record;
3523   pragma Import (C_Plus_Plus, Dog);
3524
3525   function Number_Of_Teeth (A : Dog) return Integer;
3526   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3527
3528   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3529   pragma Import (C_Plus_Plus, Set_Owner);
3530
3531   function New_Dog return Dog;
3532   pragma CPP_Constructor (New_Dog);
3533   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3534 end Animals;
3535 @end smallexample
3536
3537 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3538 interfacing with these C++ classes is easy. The only requirement is that all
3539 the primitives and components must be declared exactly in the same order in
3540 the two languages.
3541
3542 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3543 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3544 the arguments to the called primitives will be the same as for C++. For the
3545 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3546 to indicate that they have been defined on the C++ side; this is required
3547 because the dispatch table associated with these tagged types will be built
3548 in the C++ side and therefore will not contain the predefined Ada primitives
3549 which Ada would otherwise expect.
3550
3551 As the reader can see there is no need to indicate the C++ mangled names
3552 associated with each subprogram because it is assumed that all the calls to
3553 these primitives will be dispatching calls. The only exception is the
3554 constructor, which must be registered with the compiler by means of
3555 @code{pragma CPP_Constructor} and needs to provide its associated C++
3556 mangled name because the Ada compiler generates direct calls to it.
3557
3558 With the above packages we can now declare objects of type Dog on the Ada side
3559 and dispatch calls to the corresponding subprograms on the C++ side. We can
3560 also extend the tagged type Dog with further fields and primitives, and
3561 override some of its C++ primitives on the Ada side. For example, here we have
3562 a type derivation defined on the Ada side that inherits all the dispatching
3563 primitives of the ancestor from the C++ side.
3564
3565 @smallexample
3566 @b{with} Animals; @b{use} Animals;
3567 @b{package} Vaccinated_Animals @b{is}
3568   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3569   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3570 @b{end} Vaccinated_Animals;
3571 @end smallexample
3572
3573 It is important to note that, because of the ABI compatibility, the programmer
3574 does not need to add any further information to indicate either the object
3575 layout or the dispatch table entry associated with each dispatching operation.
3576
3577 Now let us define all the types and constructors on the Ada side and export
3578 them to C++, using the same hierarchy of our previous example:
3579
3580 @smallexample @c ada
3581 with Interfaces.C.Strings;
3582 use Interfaces.C.Strings;
3583 package Animals is
3584   type Carnivore is interface;
3585   pragma Convention (C_Plus_Plus, Carnivore);
3586   function Number_Of_Teeth (X : Carnivore)
3587      return Natural is abstract;
3588
3589   type Domestic is interface;
3590   pragma Convention (C_Plus_Plus, Set_Owner);
3591   procedure Set_Owner
3592     (X    : in out Domestic;
3593      Name : Chars_Ptr) is abstract;
3594
3595   type Animal is tagged record
3596     Age : Natural := 0;
3597   end record;
3598   pragma Convention (C_Plus_Plus, Animal);
3599
3600   procedure Set_Age (X : in out Animal; Age : Integer);
3601   pragma Export (C_Plus_Plus, Set_Age);
3602
3603   function Age (X : Animal) return Integer;
3604   pragma Export (C_Plus_Plus, Age);
3605
3606   type Dog is new Animal and Carnivore and Domestic with record
3607     Tooth_Count : Natural;
3608     Owner       : String (1 .. 30);
3609   end record;
3610   pragma Convention (C_Plus_Plus, Dog);
3611
3612   function Number_Of_Teeth (A : Dog) return Integer;
3613   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3614
3615   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3616   pragma Export (C_Plus_Plus, Set_Owner);
3617
3618   function New_Dog return Dog'Class;
3619   pragma Export (C_Plus_Plus, New_Dog);
3620 end Animals;
3621 @end smallexample
3622
3623 Compared with our previous example the only difference is the use of
3624 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3625 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3626 nothing else to be done; as explained above, the only requirement is that all
3627 the primitives and components are declared in exactly the same order.
3628
3629 For completeness, let us see a brief C++ main program that uses the
3630 declarations available in @code{animals.h} (presented in our first example) to
3631 import and use the declarations from the Ada side, properly initializing and
3632 finalizing the Ada run-time system along the way:
3633
3634 @smallexample
3635 @b{#include} "animals.h"
3636 @b{#include} <iostream>
3637 @b{using namespace} std;
3638
3639 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3640 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3641 void Check_Animal (Animal *obj)       @{@dots{}@}
3642 void Check_Dog (Dog *obj)             @{@dots{}@}
3643
3644 @b{extern} "C" @{
3645   void adainit (void);
3646   void adafinal (void);
3647   Dog* new_dog ();
3648 @}
3649
3650 void test ()
3651 @{
3652   Dog *obj = new_dog();  // Ada constructor
3653   Check_Carnivore (obj); // Check secondary DT
3654   Check_Domestic (obj);  // Check secondary DT
3655   Check_Animal (obj);    // Check primary DT
3656   Check_Dog (obj);       // Check primary DT
3657 @}
3658
3659 int main ()
3660 @{
3661   adainit ();  test();  adafinal ();
3662   return 0;
3663 @}
3664 @end smallexample
3665
3666 @node Comparison between GNAT and C/C++ Compilation Models
3667 @section Comparison between GNAT and C/C++ Compilation Models
3668
3669 @noindent
3670 The GNAT model of compilation is close to the C and C++ models. You can
3671 think of Ada specs as corresponding to header files in C. As in C, you
3672 don't need to compile specs; they are compiled when they are used. The
3673 Ada @code{with} is similar in effect to the @code{#include} of a C
3674 header.
3675
3676 One notable difference is that, in Ada, you may compile specs separately
3677 to check them for semantic and syntactic accuracy. This is not always
3678 possible with C headers because they are fragments of programs that have
3679 less specific syntactic or semantic rules.
3680
3681 The other major difference is the requirement for running the binder,
3682 which performs two important functions. First, it checks for
3683 consistency. In C or C++, the only defense against assembling
3684 inconsistent programs lies outside the compiler, in a makefile, for
3685 example. The binder satisfies the Ada requirement that it be impossible
3686 to construct an inconsistent program when the compiler is used in normal
3687 mode.
3688
3689 @cindex Elaboration order control
3690 The other important function of the binder is to deal with elaboration
3691 issues. There are also elaboration issues in C++ that are handled
3692 automatically. This automatic handling has the advantage of being
3693 simpler to use, but the C++ programmer has no control over elaboration.
3694 Where @code{gnatbind} might complain there was no valid order of
3695 elaboration, a C++ compiler would simply construct a program that
3696 malfunctioned at run time.
3697 @end ifclear
3698
3699 @node Comparison between GNAT and Conventional Ada Library Models
3700 @section Comparison between GNAT and Conventional Ada Library Models
3701
3702 @noindent
3703 This section is intended for Ada programmers who have
3704 used an Ada compiler implementing the traditional Ada library
3705 model, as described in the Ada Reference Manual.
3706
3707 @cindex GNAT library
3708 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3709 source files themselves acts as the library. Compiling Ada programs does
3710 not generate any centralized information, but rather an object file and
3711 a ALI file, which are of interest only to the binder and linker.
3712 In a traditional system, the compiler reads information not only from
3713 the source file being compiled, but also from the centralized library.
3714 This means that the effect of a compilation depends on what has been
3715 previously compiled. In particular:
3716
3717 @itemize @bullet
3718 @item
3719 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3720 to the version of the unit most recently compiled into the library.
3721
3722 @item
3723 Inlining is effective only if the necessary body has already been
3724 compiled into the library.
3725
3726 @item
3727 Compiling a unit may obsolete other units in the library.
3728 @end itemize
3729
3730 @noindent
3731 In GNAT, compiling one unit never affects the compilation of any other
3732 units because the compiler reads only source files. Only changes to source
3733 files can affect the results of a compilation. In particular:
3734
3735 @itemize @bullet
3736 @item
3737 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3738 to the source version of the unit that is currently accessible to the
3739 compiler.
3740
3741 @item
3742 @cindex Inlining
3743 Inlining requires the appropriate source files for the package or
3744 subprogram bodies to be available to the compiler. Inlining is always
3745 effective, independent of the order in which units are complied.
3746
3747 @item
3748 Compiling a unit never affects any other compilations. The editing of
3749 sources may cause previous compilations to be out of date if they
3750 depended on the source file being modified.
3751 @end itemize
3752
3753 @noindent
3754 The most important result of these differences is that order of compilation
3755 is never significant in GNAT. There is no situation in which one is
3756 required to do one compilation before another. What shows up as order of
3757 compilation requirements in the traditional Ada library becomes, in
3758 GNAT, simple source dependencies; in other words, there is only a set
3759 of rules saying what source files must be present when a file is
3760 compiled.
3761
3762 @ifset vms
3763 @node Placement of temporary files
3764 @section Placement of temporary files
3765 @cindex Temporary files (user control over placement)
3766
3767 @noindent
3768 GNAT creates temporary files in the directory designated by the environment
3769 variable @env{TMPDIR}.
3770 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3771 for detailed information on how environment variables are resolved.
3772 For most users the easiest way to make use of this feature is to simply
3773 define @env{TMPDIR} as a job level logical name).
3774 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3775 for compiler temporary files, then you can include something like the
3776 following command in your @file{LOGIN.COM} file:
3777
3778 @smallexample
3779 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3780 @end smallexample
3781
3782 @noindent
3783 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3784 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3785 designated by @env{TEMP}.
3786 If none of these environment variables are defined then GNAT uses the
3787 directory designated by the logical name @code{SYS$SCRATCH:}
3788 (by default the user's home directory). If all else fails
3789 GNAT uses the current directory for temporary files.
3790 @end ifset
3791
3792 @c *************************
3793 @node Compiling Using gcc
3794 @chapter Compiling Using @command{gcc}
3795
3796 @noindent
3797 This chapter discusses how to compile Ada programs using the @command{gcc}
3798 command. It also describes the set of switches
3799 that can be used to control the behavior of the compiler.
3800 @menu
3801 * Compiling Programs::
3802 * Switches for gcc::
3803 * Search Paths and the Run-Time Library (RTL)::
3804 * Order of Compilation Issues::
3805 * Examples::
3806 @end menu
3807
3808 @node Compiling Programs
3809 @section Compiling Programs
3810
3811 @noindent
3812 The first step in creating an executable program is to compile the units
3813 of the program using the @command{gcc} command. You must compile the
3814 following files:
3815
3816 @itemize @bullet
3817 @item
3818 the body file (@file{.adb}) for a library level subprogram or generic
3819 subprogram
3820
3821 @item
3822 the spec file (@file{.ads}) for a library level package or generic
3823 package that has no body
3824
3825 @item
3826 the body file (@file{.adb}) for a library level package
3827 or generic package that has a body
3828
3829 @end itemize
3830
3831 @noindent
3832 You need @emph{not} compile the following files
3833
3834 @itemize @bullet
3835
3836 @item
3837 the spec of a library unit which has a body
3838
3839 @item
3840 subunits
3841 @end itemize
3842
3843 @noindent
3844 because they are compiled as part of compiling related units. GNAT
3845 package specs
3846 when the corresponding body is compiled, and subunits when the parent is
3847 compiled.
3848
3849 @cindex cannot generate code
3850 If you attempt to compile any of these files, you will get one of the
3851 following error messages (where @var{fff} is the name of the file you compiled):
3852
3853 @smallexample
3854 cannot generate code for file @var{fff} (package spec)
3855 to check package spec, use -gnatc
3856
3857 cannot generate code for file @var{fff} (missing subunits)
3858 to check parent unit, use -gnatc
3859
3860 cannot generate code for file @var{fff} (subprogram spec)
3861 to check subprogram spec, use -gnatc
3862
3863 cannot generate code for file @var{fff} (subunit)
3864 to check subunit, use -gnatc
3865 @end smallexample
3866
3867 @noindent
3868 As indicated by the above error messages, if you want to submit
3869 one of these files to the compiler to check for correct semantics
3870 without generating code, then use the @option{-gnatc} switch.
3871
3872 The basic command for compiling a file containing an Ada unit is
3873
3874 @smallexample
3875 $ gcc -c @ovar{switches} @file{file name}
3876 @end smallexample
3877
3878 @noindent
3879 where @var{file name} is the name of the Ada file (usually
3880 having an extension
3881 @file{.ads} for a spec or @file{.adb} for a body).
3882 @ifclear vms
3883 You specify the
3884 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3885 @end ifclear
3886 The result of a successful compilation is an object file, which has the
3887 same name as the source file but an extension of @file{.o} and an Ada
3888 Library Information (ALI) file, which also has the same name as the
3889 source file, but with @file{.ali} as the extension. GNAT creates these
3890 two output files in the current directory, but you may specify a source
3891 file in any directory using an absolute or relative path specification
3892 containing the directory information.
3893
3894 @findex gnat1
3895 @command{gcc} is actually a driver program that looks at the extensions of
3896 the file arguments and loads the appropriate compiler. For example, the
3897 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3898 These programs are in directories known to the driver program (in some
3899 configurations via environment variables you set), but need not be in
3900 your path. The @command{gcc} driver also calls the assembler and any other
3901 utilities needed to complete the generation of the required object
3902 files.
3903
3904 It is possible to supply several file names on the same @command{gcc}
3905 command. This causes @command{gcc} to call the appropriate compiler for
3906 each file. For example, the following command lists three separate
3907 files to be compiled:
3908
3909 @smallexample
3910 $ gcc -c x.adb y.adb z.c
3911 @end smallexample
3912
3913 @noindent
3914 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3915 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3916 The compiler generates three object files @file{x.o}, @file{y.o} and
3917 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3918 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3919 @ifclear vms
3920 except for
3921 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3922 @end ifclear
3923
3924 @node Switches for gcc
3925 @section Switches for @command{gcc}
3926
3927 @noindent
3928 The @command{gcc} command accepts switches that control the
3929 compilation process. These switches are fully described in this section.
3930 First we briefly list all the switches, in alphabetical order, then we
3931 describe the switches in more detail in functionally grouped sections.
3932
3933 More switches exist for GCC than those documented here, especially
3934 for specific targets. However, their use is not recommended as
3935 they may change code generation in ways that are incompatible with
3936 the Ada run-time library, or can cause inconsistencies between
3937 compilation units.
3938
3939 @menu
3940 * Output and Error Message Control::
3941 * Warning Message Control::
3942 * Debugging and Assertion Control::
3943 * Validity Checking::
3944 * Style Checking::
3945 * Run-Time Checks::
3946 * Using gcc for Syntax Checking::
3947 * Using gcc for Semantic Checking::
3948 * Compiling Different Versions of Ada::
3949 * Character Set Control::
3950 * File Naming Control::
3951 * Subprogram Inlining Control::
3952 * Auxiliary Output Control::
3953 * Debugging Control::
3954 * Exception Handling Control::
3955 * Units to Sources Mapping Files::
3956 * Integrated Preprocessing::
3957 * Code Generation Control::
3958 @ifset vms
3959 * Return Codes::
3960 @end ifset
3961 @end menu
3962
3963 @table @option
3964 @c !sort!
3965 @ifclear vms
3966 @cindex @option{-b} (@command{gcc})
3967 @item -b @var{target}
3968 Compile your program to run on @var{target}, which is the name of a
3969 system configuration. You must have a GNAT cross-compiler built if
3970 @var{target} is not the same as your host system.
3971
3972 @item -B@var{dir}
3973 @cindex @option{-B} (@command{gcc})
3974 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3975 from @var{dir} instead of the default location. Only use this switch
3976 when multiple versions of the GNAT compiler are available.
3977 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3978 GNU Compiler Collection (GCC)}, for further details. You would normally
3979 use the @option{-b} or @option{-V} switch instead.
3980
3981 @item -c
3982 @cindex @option{-c} (@command{gcc})
3983 Compile. Always use this switch when compiling Ada programs.
3984
3985 Note: for some other languages when using @command{gcc}, notably in
3986 the case of C and C++, it is possible to use
3987 use @command{gcc} without a @option{-c} switch to
3988 compile and link in one step. In the case of GNAT, you
3989 cannot use this approach, because the binder must be run
3990 and @command{gcc} cannot be used to run the GNAT binder.
3991 @end ifclear
3992
3993 @item -fno-inline
3994 @cindex @option{-fno-inline} (@command{gcc})
3995 Suppresses all back-end inlining, even if other optimization or inlining
3996 switches are set.
3997 This includes suppression of inlining that results
3998 from the use of the pragma @code{Inline_Always}.
3999 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
4000 are ignored, and @option{-gnatn} and @option{-gnatN} have no
4001 effect if this switch is present.
4002
4003 @item -fno-inline-functions
4004 @cindex @option{-fno-inline-functions} (@command{gcc})
4005 Suppresses automatic inlining of simple subprograms, which is enabled
4006 if @option{-O3} is used.
4007
4008 @item -fno-inline-small-functions
4009 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4010 Suppresses automatic inlining of small subprograms, which is enabled
4011 if @option{-O2} is used.
4012
4013 @item -fno-inline-functions-called-once
4014 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4015 Suppresses inlining of subprograms local to the unit and called once
4016 from within it, which is enabled if @option{-O1} is used.
4017
4018 @item -fno-ivopts
4019 @cindex @option{-fno-ivopts} (@command{gcc})
4020 Suppresses high-level loop induction variable optimizations, which are
4021 enabled if @option{-O1} is used. These optimizations are generally
4022 profitable but, for some specific cases of loops with numerous uses
4023 of the iteration variable that follow a common pattern, they may end
4024 up destroying the regularity that could be exploited at a lower level
4025 and thus producing inferior code.
4026
4027 @item -fno-strict-aliasing
4028 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4029 Causes the compiler to avoid assumptions regarding non-aliasing
4030 of objects of different types. See
4031 @ref{Optimization and Strict Aliasing} for details.
4032
4033 @item -fstack-check
4034 @cindex @option{-fstack-check} (@command{gcc})
4035 Activates stack checking.
4036 See @ref{Stack Overflow Checking} for details.
4037
4038 @item -fstack-usage
4039 @cindex @option{-fstack-usage} (@command{gcc})
4040 Makes the compiler output stack usage information for the program, on a
4041 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4042
4043 @item -fcallgraph-info@r{[}=su@r{]}
4044 @cindex @option{-fcallgraph-info} (@command{gcc})
4045 Makes the compiler output callgraph information for the program, on a
4046 per-file basis.  The information is generated in the VCG format.  It can
4047 be decorated with stack-usage per-node information.
4048
4049 @item ^-g^/DEBUG^
4050 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4051 Generate debugging information. This information is stored in the object
4052 file and copied from there to the final executable file by the linker,
4053 where it can be read by the debugger. You must use the
4054 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4055
4056 @item -gnat83
4057 @cindex @option{-gnat83} (@command{gcc})
4058 Enforce Ada 83 restrictions.
4059
4060 @item -gnat95
4061 @cindex @option{-gnat95} (@command{gcc})
4062 Enforce Ada 95 restrictions.
4063
4064 @item -gnat05
4065 @cindex @option{-gnat05} (@command{gcc})
4066 Allow full Ada 2005 features.
4067
4068 @item -gnata
4069 @cindex @option{-gnata} (@command{gcc})
4070 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4071 activated. Note that these pragmas can also be controlled using the
4072 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4073 It also activates pragmas @code{Check}, @code{Precondition}, and
4074 @code{Postcondition}. Note that these pragmas can also be controlled
4075 using the configuration pragma @code{Check_Policy}.
4076
4077 @item -gnatA
4078 @cindex @option{-gnatA} (@command{gcc})
4079 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4080 it will be ignored.
4081
4082 @item -gnatb
4083 @cindex @option{-gnatb} (@command{gcc})
4084 Generate brief messages to @file{stderr} even if verbose mode set.
4085
4086 @item -gnatB
4087 @cindex @option{-gnatB} (@command{gcc})
4088 Assume no invalid (bad) values except for 'Valid attribute use
4089 (@pxref{Validity Checking}).
4090
4091 @item -gnatc
4092 @cindex @option{-gnatc} (@command{gcc})
4093 Check syntax and semantics only (no code generation attempted).
4094
4095 @item -gnatC
4096 @cindex @option{-gnatC} (@command{gcc})
4097 Generate CodePeer information (no code generation attempted).
4098 This switch will generate an intermediate representation suitable for
4099 use by CodePeer (@file{.scil} files). This switch is not compatible with
4100 code generation (it will, among other things, disable some switches such
4101 as -gnatn, and enable others such as -gnata).
4102
4103 @item -gnatd
4104 @cindex @option{-gnatd} (@command{gcc})
4105 Specify debug options for the compiler. The string of characters after
4106 the @option{-gnatd} specify the specific debug options. The possible
4107 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4108 compiler source file @file{debug.adb} for details of the implemented
4109 debug options. Certain debug options are relevant to applications
4110 programmers, and these are documented at appropriate points in this
4111 users guide.
4112
4113 @ifclear vms
4114 @item -gnatD
4115 @cindex @option{-gnatD[nn]} (@command{gcc})
4116 @end ifclear
4117 @ifset vms
4118 @item /XDEBUG /LXDEBUG=nnn
4119 @end ifset
4120 Create expanded source files for source level debugging. This switch
4121 also suppress generation of cross-reference information
4122 (see @option{-gnatx}).
4123
4124 @item -gnatec=@var{path}
4125 @cindex @option{-gnatec} (@command{gcc})
4126 Specify a configuration pragma file
4127 @ifclear vms
4128 (the equal sign is optional)
4129 @end ifclear
4130 (@pxref{The Configuration Pragmas Files}).
4131
4132 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4133 @cindex @option{-gnateD} (@command{gcc})
4134 Defines a symbol, associated with @var{value}, for preprocessing.
4135 (@pxref{Integrated Preprocessing}).
4136
4137 @item -gnatef
4138 @cindex @option{-gnatef} (@command{gcc})
4139 Display full source path name in brief error messages.
4140
4141 @item -gnateG
4142 @cindex @option{-gnateG} (@command{gcc})
4143 Save result of preprocessing in a text file.
4144
4145 @item -gnatem=@var{path}
4146 @cindex @option{-gnatem} (@command{gcc})
4147 Specify a mapping file
4148 @ifclear vms
4149 (the equal sign is optional)
4150 @end ifclear
4151 (@pxref{Units to Sources Mapping Files}).
4152
4153 @item -gnatep=@var{file}
4154 @cindex @option{-gnatep} (@command{gcc})
4155 Specify a preprocessing data file
4156 @ifclear vms
4157 (the equal sign is optional)
4158 @end ifclear
4159 (@pxref{Integrated Preprocessing}).
4160
4161 @item -gnateS
4162 @cindex @option{-gnateS} (@command{gcc})
4163 Generate SCO (Source Coverage Obligation) information in the ALI
4164 file. This information is used by advanced coverage tools. See
4165 unit @file{SCOs} in the compiler sources for details in files
4166 @file{scos.ads} and @file{scos.adb}.
4167
4168 @item -gnatE
4169 @cindex @option{-gnatE} (@command{gcc})
4170 Full dynamic elaboration checks.
4171
4172 @item -gnatf
4173 @cindex @option{-gnatf} (@command{gcc})
4174 Full errors. Multiple errors per line, all undefined references, do not
4175 attempt to suppress cascaded errors.
4176
4177 @item -gnatF
4178 @cindex @option{-gnatF} (@command{gcc})
4179 Externals names are folded to all uppercase.
4180
4181 @item ^-gnatg^/GNAT_INTERNAL^
4182 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4183 Internal GNAT implementation mode. This should not be used for
4184 applications programs, it is intended only for use by the compiler
4185 and its run-time library. For documentation, see the GNAT sources.
4186 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4187 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4188 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4189 so that all standard warnings and all standard style options are turned on.
4190 All warnings and style error messages are treated as errors.
4191
4192 @ifclear vms
4193 @item -gnatG=nn
4194 @cindex @option{-gnatG[nn]} (@command{gcc})
4195 @end ifclear
4196 @ifset vms
4197 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4198 @end ifset
4199 List generated expanded code in source form.
4200
4201 @item ^-gnath^/HELP^
4202 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4203 Output usage information. The output is written to @file{stdout}.
4204
4205 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4206 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4207 Identifier character set
4208 @ifclear vms
4209 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4210 @end ifclear
4211 For details of the possible selections for @var{c},
4212 see @ref{Character Set Control}.
4213
4214 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4215 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4216 Ignore representation clauses. When this switch is used,
4217 representation clauses are treated as comments. This is useful
4218 when initially porting code where you want to ignore rep clause
4219 problems, and also for compiling foreign code (particularly
4220 for use with ASIS). The representation clauses that are ignored
4221 are: enumeration_representation_clause, record_representation_clause,
4222 and attribute_definition_clause for the following attributes:
4223 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4224 Object_Size, Size, Small, Stream_Size, and Value_Size.
4225 Note that this option should be used only for compiling -- the
4226 code is likely to malfunction at run time.
4227
4228 @item -gnatjnn
4229 @cindex @option{-gnatjnn} (@command{gcc})
4230 Reformat error messages to fit on nn character lines
4231
4232 @item -gnatk=@var{n}
4233 @cindex @option{-gnatk} (@command{gcc})
4234 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4235
4236 @item -gnatl
4237 @cindex @option{-gnatl} (@command{gcc})
4238 Output full source listing with embedded error messages.
4239
4240 @item -gnatL
4241 @cindex @option{-gnatL} (@command{gcc})
4242 Used in conjunction with -gnatG or -gnatD to intersperse original
4243 source lines (as comment lines with line numbers) in the expanded
4244 source output.
4245
4246 @item -gnatm=@var{n}
4247 @cindex @option{-gnatm} (@command{gcc})
4248 Limit number of detected error or warning messages to @var{n}
4249 where @var{n} is in the range 1..999999. The default setting if
4250 no switch is given is 9999. If the number of warnings reaches this
4251 limit, then a message is output and further warnings are suppressed,
4252 but the compilation is continued. If the number of error messages
4253 reaches this limit, then a message is output and the compilation
4254 is abandoned. The equal sign here is optional. A value of zero
4255 means that no limit applies.
4256
4257 @item -gnatn
4258 @cindex @option{-gnatn} (@command{gcc})
4259 Activate inlining for subprograms for which
4260 pragma @code{inline} is specified. This inlining is performed
4261 by the GCC back-end.
4262
4263 @item -gnatN
4264 @cindex @option{-gnatN} (@command{gcc})
4265 Activate front end inlining for subprograms for which
4266 pragma @code{Inline} is specified. This inlining is performed
4267 by the front end and will be visible in the
4268 @option{-gnatG} output.
4269
4270 When using a gcc-based back end (in practice this means using any version
4271 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4272 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4273 Historically front end inlining was more extensive than the gcc back end
4274 inlining, but that is no longer the case.
4275
4276 @item -gnato
4277 @cindex @option{-gnato} (@command{gcc})
4278 Enable numeric overflow checking (which is not normally enabled by
4279 default). Note that division by zero is a separate check that is not
4280 controlled by this switch (division by zero checking is on by default).
4281
4282 @item -gnatp
4283 @cindex @option{-gnatp} (@command{gcc})
4284 Suppress all checks. See @ref{Run-Time Checks} for details.
4285
4286 @item -gnatP
4287 @cindex @option{-gnatP} (@command{gcc})
4288 Enable polling. This is required on some systems (notably Windows NT) to
4289 obtain asynchronous abort and asynchronous transfer of control capability.
4290 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4291 details.
4292
4293 @item -gnatq
4294 @cindex @option{-gnatq} (@command{gcc})
4295 Don't quit. Try semantics, even if parse errors.
4296
4297 @item -gnatQ
4298 @cindex @option{-gnatQ} (@command{gcc})
4299 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4300
4301 @item -gnatr
4302 @cindex @option{-gnatr} (@command{gcc})
4303 Treat pragma Restrictions as Restriction_Warnings.
4304
4305 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4306 @cindex @option{-gnatR} (@command{gcc})
4307 Output representation information for declared types and objects.
4308
4309 @item -gnats
4310 @cindex @option{-gnats} (@command{gcc})
4311 Syntax check only.
4312
4313 @item -gnatS
4314 @cindex @option{-gnatS} (@command{gcc})
4315 Print package Standard.
4316
4317 @item -gnatt
4318 @cindex @option{-gnatt} (@command{gcc})
4319 Generate tree output file.
4320
4321 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4322 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4323 All compiler tables start at @var{nnn} times usual starting size.
4324
4325 @item -gnatu
4326 @cindex @option{-gnatu} (@command{gcc})
4327 List units for this compilation.
4328
4329 @item -gnatU
4330 @cindex @option{-gnatU} (@command{gcc})
4331 Tag all error messages with the unique string ``error:''
4332
4333 @item -gnatv
4334 @cindex @option{-gnatv} (@command{gcc})
4335 Verbose mode. Full error output with source lines to @file{stdout}.
4336
4337 @item -gnatV
4338 @cindex @option{-gnatV} (@command{gcc})
4339 Control level of validity checking (@pxref{Validity Checking}).
4340
4341 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4342 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4343 Warning mode where
4344 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4345 the exact warnings that
4346 are enabled or disabled (@pxref{Warning Message Control}).
4347
4348 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4349 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4350 Wide character encoding method
4351 @ifclear vms
4352 (@var{e}=n/h/u/s/e/8).
4353 @end ifclear
4354 @ifset vms
4355 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4356 @end ifset
4357
4358 @item -gnatx
4359 @cindex @option{-gnatx} (@command{gcc})
4360 Suppress generation of cross-reference information.
4361
4362 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4363 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4364 Enable built-in style checks (@pxref{Style Checking}).
4365
4366 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4367 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4368 Distribution stub generation and compilation
4369 @ifclear vms
4370 (@var{m}=r/c for receiver/caller stubs).
4371 @end ifclear
4372 @ifset vms
4373 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4374 to be generated and compiled).
4375 @end ifset
4376
4377 @item ^-I^/SEARCH=^@var{dir}
4378 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4379 @cindex RTL
4380 Direct GNAT to search the @var{dir} directory for source files needed by
4381 the current compilation
4382 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4383
4384 @item ^-I-^/NOCURRENT_DIRECTORY^
4385 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4386 @cindex RTL
4387 Except for the source file named in the command line, do not look for source
4388 files in the directory containing the source file named in the command line
4389 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4390
4391 @ifclear vms
4392 @item -mbig-switch
4393 @cindex @option{-mbig-switch} (@command{gcc})
4394 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4395 This standard gcc switch causes the compiler to use larger offsets in its
4396 jump table representation for @code{case} statements.
4397 This may result in less efficient code, but is sometimes necessary
4398 (for example on HP-UX targets)
4399 @cindex HP-UX and @option{-mbig-switch} option
4400 in order to compile large and/or nested @code{case} statements.
4401
4402 @item -o @var{file}
4403 @cindex @option{-o} (@command{gcc})
4404 This switch is used in @command{gcc} to redirect the generated object file
4405 and its associated ALI file. Beware of this switch with GNAT, because it may
4406 cause the object file and ALI file to have different names which in turn
4407 may confuse the binder and the linker.
4408 @end ifclear
4409
4410 @item -nostdinc
4411 @cindex @option{-nostdinc} (@command{gcc})
4412 Inhibit the search of the default location for the GNAT Run Time
4413 Library (RTL) source files.
4414
4415 @item -nostdlib
4416 @cindex @option{-nostdlib} (@command{gcc})
4417 Inhibit the search of the default location for the GNAT Run Time
4418 Library (RTL) ALI files.
4419
4420 @ifclear vms
4421 @item -O@ovar{n}
4422 @cindex @option{-O} (@command{gcc})
4423 @var{n} controls the optimization level.
4424
4425 @table @asis
4426 @item n = 0
4427 No optimization, the default setting if no @option{-O} appears
4428
4429 @item n = 1
4430 Normal optimization, the default if you specify @option{-O} without
4431 an operand. A good compromise between code quality and compilation
4432 time.
4433
4434 @item n = 2
4435 Extensive optimization, may improve execution time, possibly at the cost of
4436 substantially increased compilation time.
4437
4438 @item n = 3
4439 Same as @option{-O2}, and also includes inline expansion for small subprograms
4440 in the same unit.
4441
4442 @item n = s
4443 Optimize space usage
4444 @end table
4445
4446 @noindent
4447 See also @ref{Optimization Levels}.
4448 @end ifclear
4449
4450 @ifset vms
4451 @item  /NOOPTIMIZE
4452 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4453 Equivalent to @option{/OPTIMIZE=NONE}.
4454 This is the default behavior in the absence of an @option{/OPTIMIZE}
4455 qualifier.
4456
4457 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4458 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4459 Selects the level of optimization for your program. The supported
4460 keywords are as follows:
4461 @table @code
4462 @item   ALL
4463 Perform most optimizations, including those that
4464 are expensive.
4465 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4466 without keyword options.
4467
4468 @item   NONE
4469 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4470
4471 @item SOME
4472 Perform some optimizations, but omit ones that are costly.
4473
4474 @item   DEVELOPMENT
4475 Same as @code{SOME}.
4476
4477 @item INLINING
4478 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4479 automatic inlining of small subprograms within a unit
4480
4481 @item   UNROLL_LOOPS
4482 Try to unroll loops. This keyword may be specified together with
4483 any keyword above other than @code{NONE}. Loop unrolling
4484 usually, but not always, improves the performance of programs.
4485
4486 @item SPACE
4487 Optimize space usage
4488 @end table
4489
4490 @noindent
4491 See also @ref{Optimization Levels}.
4492 @end ifset
4493
4494 @ifclear vms
4495 @item -pass-exit-codes
4496 @cindex @option{-pass-exit-codes} (@command{gcc})
4497 Catch exit codes from the compiler and use the most meaningful as
4498 exit status.
4499 @end ifclear
4500
4501 @item --RTS=@var{rts-path}
4502 @cindex @option{--RTS} (@command{gcc})
4503 Specifies the default location of the runtime library. Same meaning as the
4504 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4505
4506 @item ^-S^/ASM^
4507 @cindex @option{^-S^/ASM^} (@command{gcc})
4508 ^Used in place of @option{-c} to^Used to^
4509 cause the assembler source file to be
4510 generated, using @file{^.s^.S^} as the extension,
4511 instead of the object file.
4512 This may be useful if you need to examine the generated assembly code.
4513
4514 @item ^-fverbose-asm^/VERBOSE_ASM^
4515 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4516 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4517 to cause the generated assembly code file to be annotated with variable
4518 names, making it significantly easier to follow.
4519
4520 @item ^-v^/VERBOSE^
4521 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4522 Show commands generated by the @command{gcc} driver. Normally used only for
4523 debugging purposes or if you need to be sure what version of the
4524 compiler you are executing.
4525
4526 @ifclear vms
4527 @item -V @var{ver}
4528 @cindex @option{-V} (@command{gcc})
4529 Execute @var{ver} version of the compiler. This is the @command{gcc}
4530 version, not the GNAT version.
4531 @end ifclear
4532
4533 @item ^-w^/NO_BACK_END_WARNINGS^
4534 @cindex @option{-w} (@command{gcc})
4535 Turn off warnings generated by the back end of the compiler. Use of
4536 this switch also causes the default for front end warnings to be set
4537 to suppress (as though @option{-gnatws} had appeared at the start of
4538 the options).
4539
4540 @end table
4541
4542 @ifclear vms
4543 @c Combining qualifiers does not work on VMS
4544 You may combine a sequence of GNAT switches into a single switch. For
4545 example, the combined switch
4546
4547 @cindex Combining GNAT switches
4548 @smallexample
4549 -gnatofi3
4550 @end smallexample
4551
4552 @noindent
4553 is equivalent to specifying the following sequence of switches:
4554
4555 @smallexample
4556 -gnato -gnatf -gnati3
4557 @end smallexample
4558 @end ifclear
4559
4560 @noindent
4561 The following restrictions apply to the combination of switches
4562 in this manner:
4563
4564 @itemize @bullet
4565 @item
4566 The switch @option{-gnatc} if combined with other switches must come
4567 first in the string.
4568
4569 @item
4570 The switch @option{-gnats} if combined with other switches must come
4571 first in the string.
4572
4573 @item
4574 The switches
4575 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4576 may not be combined with any other switches.
4577
4578 @ifclear vms
4579 @item
4580 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4581 switch), then all further characters in the switch are interpreted
4582 as style modifiers (see description of @option{-gnaty}).
4583
4584 @item
4585 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4586 switch), then all further characters in the switch are interpreted
4587 as debug flags (see description of @option{-gnatd}).
4588
4589 @item
4590 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4591 switch), then all further characters in the switch are interpreted
4592 as warning mode modifiers (see description of @option{-gnatw}).
4593
4594 @item
4595 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4596 switch), then all further characters in the switch are interpreted
4597 as validity checking options (@pxref{Validity Checking}).
4598 @end ifclear
4599 @end itemize
4600
4601 @node Output and Error Message Control
4602 @subsection Output and Error Message Control
4603 @findex stderr
4604
4605 @noindent
4606 The standard default format for error messages is called ``brief format''.
4607 Brief format messages are written to @file{stderr} (the standard error
4608 file) and have the following form:
4609
4610 @smallexample
4611 e.adb:3:04: Incorrect spelling of keyword "function"
4612 e.adb:4:20: ";" should be "is"
4613 @end smallexample
4614
4615 @noindent
4616 The first integer after the file name is the line number in the file,
4617 and the second integer is the column number within the line.
4618 @ifclear vms
4619 @code{GPS} can parse the error messages
4620 and point to the referenced character.
4621 @end ifclear
4622 The following switches provide control over the error message
4623 format:
4624
4625 @table @option
4626 @c !sort!
4627 @item -gnatv
4628 @cindex @option{-gnatv} (@command{gcc})
4629 @findex stdout
4630 @ifclear vms
4631 The v stands for verbose.
4632 @end ifclear
4633 The effect of this setting is to write long-format error
4634 messages to @file{stdout} (the standard output file.
4635 The same program compiled with the
4636 @option{-gnatv} switch would generate:
4637
4638 @smallexample
4639 @cartouche
4640 3. funcion X (Q : Integer)
4641    |
4642 >>> Incorrect spelling of keyword "function"
4643 4. return Integer;
4644                  |
4645 >>> ";" should be "is"
4646 @end cartouche
4647 @end smallexample
4648
4649 @noindent
4650 The vertical bar indicates the location of the error, and the @samp{>>>}
4651 prefix can be used to search for error messages. When this switch is
4652 used the only source lines output are those with errors.
4653
4654 @item -gnatl
4655 @cindex @option{-gnatl} (@command{gcc})
4656 @ifclear vms
4657 The @code{l} stands for list.
4658 @end ifclear
4659 This switch causes a full listing of
4660 the file to be generated. In the case where a body is
4661 compiled, the corresponding spec is also listed, along
4662 with any subunits. Typical output from compiling a package
4663 body @file{p.adb} might look like:
4664
4665 @smallexample @c ada
4666 @cartouche
4667  Compiling: p.adb
4668
4669      1. package body p is
4670      2.    procedure a;
4671      3.    procedure a is separate;
4672      4. begin
4673      5.    null
4674                |
4675         >>> missing ";"
4676
4677      6. end;
4678
4679 Compiling: p.ads
4680
4681      1. package p is
4682      2.    pragma Elaborate_Body
4683                                 |
4684         >>> missing ";"
4685
4686      3. end p;
4687
4688 Compiling: p-a.adb
4689
4690      1. separate p
4691                 |
4692         >>> missing "("
4693
4694      2. procedure a is
4695      3. begin
4696      4.    null
4697                |
4698         >>> missing ";"
4699
4700      5. end;
4701 @end cartouche
4702 @end smallexample
4703
4704 @noindent
4705 @findex stderr
4706 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4707 standard output is redirected, a brief summary is written to
4708 @file{stderr} (standard error) giving the number of error messages and
4709 warning messages generated.
4710
4711 @item -^gnatl^OUTPUT_FILE^=file
4712 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4713 This has the same effect as @option{-gnatl} except that the output is
4714 written to a file instead of to standard output. If the given name
4715 @file{fname} does not start with a period, then it is the full name
4716 of the file to be written. If @file{fname} is an extension, it is
4717 appended to the name of the file being compiled. For example, if
4718 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4719 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4720
4721 @item -gnatU
4722 @cindex @option{-gnatU} (@command{gcc})
4723 This switch forces all error messages to be preceded by the unique
4724 string ``error:''. This means that error messages take a few more
4725 characters in space, but allows easy searching for and identification
4726 of error messages.
4727
4728 @item -gnatb
4729 @cindex @option{-gnatb} (@command{gcc})
4730 @ifclear vms
4731 The @code{b} stands for brief.
4732 @end ifclear
4733 This switch causes GNAT to generate the
4734 brief format error messages to @file{stderr} (the standard error
4735 file) as well as the verbose
4736 format message or full listing (which as usual is written to
4737 @file{stdout} (the standard output file).
4738
4739 @item -gnatm=@var{n}
4740 @cindex @option{-gnatm} (@command{gcc})
4741 @ifclear vms
4742 The @code{m} stands for maximum.
4743 @end ifclear
4744 @var{n} is a decimal integer in the
4745 range of 1 to 999999 and limits the number of error or warning
4746 messages to be generated. For example, using
4747 @option{-gnatm2} might yield
4748
4749 @smallexample
4750 e.adb:3:04: Incorrect spelling of keyword "function"
4751 e.adb:5:35: missing ".."
4752 fatal error: maximum number of errors detected
4753 compilation abandoned
4754 @end smallexample
4755
4756 @noindent
4757 The default setting if
4758 no switch is given is 9999. If the number of warnings reaches this
4759 limit, then a message is output and further warnings are suppressed,
4760 but the compilation is continued. If the number of error messages
4761 reaches this limit, then a message is output and the compilation
4762 is abandoned. A value of zero means that no limit applies.
4763
4764 @noindent
4765 Note that the equal sign is optional, so the switches
4766 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4767
4768 @item -gnatf
4769 @cindex @option{-gnatf} (@command{gcc})
4770 @cindex Error messages, suppressing
4771 @ifclear vms
4772 The @code{f} stands for full.
4773 @end ifclear
4774 Normally, the compiler suppresses error messages that are likely to be
4775 redundant. This switch causes all error
4776 messages to be generated. In particular, in the case of
4777 references to undefined variables. If a given variable is referenced
4778 several times, the normal format of messages is
4779 @smallexample
4780 e.adb:7:07: "V" is undefined (more references follow)
4781 @end smallexample
4782
4783 @noindent
4784 where the parenthetical comment warns that there are additional
4785 references to the variable @code{V}. Compiling the same program with the
4786 @option{-gnatf} switch yields
4787
4788 @smallexample
4789 e.adb:7:07: "V" is undefined
4790 e.adb:8:07: "V" is undefined
4791 e.adb:8:12: "V" is undefined
4792 e.adb:8:16: "V" is undefined
4793 e.adb:9:07: "V" is undefined
4794 e.adb:9:12: "V" is undefined
4795 @end smallexample
4796
4797 @noindent
4798 The @option{-gnatf} switch also generates additional information for
4799 some error messages.  Some examples are:
4800
4801 @itemize @bullet
4802 @item
4803 Details on possibly non-portable unchecked conversion
4804 @item
4805 List possible interpretations for ambiguous calls
4806 @item
4807 Additional details on incorrect parameters
4808 @end itemize
4809
4810 @item -gnatjnn
4811 @cindex @option{-gnatjnn} (@command{gcc})
4812 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4813 with continuation lines are treated as though the continuation lines were
4814 separate messages (and so a warning with two continuation lines counts as
4815 three warnings, and is listed as three separate messages).
4816
4817 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4818 messages are output in a different manner. A message and all its continuation
4819 lines are treated as a unit, and count as only one warning or message in the
4820 statistics totals. Furthermore, the message is reformatted so that no line
4821 is longer than nn characters.
4822
4823 @item -gnatq
4824 @cindex @option{-gnatq} (@command{gcc})
4825 @ifclear vms
4826 The @code{q} stands for quit (really ``don't quit'').
4827 @end ifclear
4828 In normal operation mode, the compiler first parses the program and
4829 determines if there are any syntax errors. If there are, appropriate
4830 error messages are generated and compilation is immediately terminated.
4831 This switch tells
4832 GNAT to continue with semantic analysis even if syntax errors have been
4833 found. This may enable the detection of more errors in a single run. On
4834 the other hand, the semantic analyzer is more likely to encounter some
4835 internal fatal error when given a syntactically invalid tree.
4836
4837 @item -gnatQ
4838 @cindex @option{-gnatQ} (@command{gcc})
4839 In normal operation mode, the @file{ALI} file is not generated if any
4840 illegalities are detected in the program. The use of @option{-gnatQ} forces
4841 generation of the @file{ALI} file. This file is marked as being in
4842 error, so it cannot be used for binding purposes, but it does contain
4843 reasonably complete cross-reference information, and thus may be useful
4844 for use by tools (e.g., semantic browsing tools or integrated development
4845 environments) that are driven from the @file{ALI} file. This switch
4846 implies @option{-gnatq}, since the semantic phase must be run to get a
4847 meaningful ALI file.
4848
4849 In addition, if @option{-gnatt} is also specified, then the tree file is
4850 generated even if there are illegalities. It may be useful in this case
4851 to also specify @option{-gnatq} to ensure that full semantic processing
4852 occurs. The resulting tree file can be processed by ASIS, for the purpose
4853 of providing partial information about illegal units, but if the error
4854 causes the tree to be badly malformed, then ASIS may crash during the
4855 analysis.
4856
4857 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4858 being in error, @command{gnatmake} will attempt to recompile the source when it
4859 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4860
4861 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4862 since ALI files are never generated if @option{-gnats} is set.
4863
4864 @end table
4865
4866 @node Warning Message Control
4867 @subsection Warning Message Control
4868 @cindex Warning messages
4869 @noindent
4870 In addition to error messages, which correspond to illegalities as defined
4871 in the Ada Reference Manual, the compiler detects two kinds of warning
4872 situations.
4873
4874 First, the compiler considers some constructs suspicious and generates a
4875 warning message to alert you to a possible error. Second, if the
4876 compiler detects a situation that is sure to raise an exception at
4877 run time, it generates a warning message. The following shows an example
4878 of warning messages:
4879 @smallexample
4880 e.adb:4:24: warning: creation of object may raise Storage_Error
4881 e.adb:10:17: warning: static value out of range
4882 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4883 @end smallexample
4884
4885 @noindent
4886 GNAT considers a large number of situations as appropriate
4887 for the generation of warning messages. As always, warnings are not
4888 definite indications of errors. For example, if you do an out-of-range
4889 assignment with the deliberate intention of raising a
4890 @code{Constraint_Error} exception, then the warning that may be
4891 issued does not indicate an error. Some of the situations for which GNAT
4892 issues warnings (at least some of the time) are given in the following
4893 list. This list is not complete, and new warnings are often added to
4894 subsequent versions of GNAT. The list is intended to give a general idea
4895 of the kinds of warnings that are generated.
4896
4897 @itemize @bullet
4898 @item
4899 Possible infinitely recursive calls
4900
4901 @item
4902 Out-of-range values being assigned
4903
4904 @item
4905 Possible order of elaboration problems
4906
4907 @item
4908 Assertions (pragma Assert) that are sure to fail
4909
4910 @item
4911 Unreachable code
4912
4913 @item
4914 Address clauses with possibly unaligned values, or where an attempt is
4915 made to overlay a smaller variable with a larger one.
4916
4917 @item
4918 Fixed-point type declarations with a null range
4919
4920 @item
4921 Direct_IO or Sequential_IO instantiated with a type that has access values
4922
4923 @item
4924 Variables that are never assigned a value
4925
4926 @item
4927 Variables that are referenced before being initialized
4928
4929 @item
4930 Task entries with no corresponding @code{accept} statement
4931
4932 @item
4933 Duplicate accepts for the same task entry in a @code{select}
4934
4935 @item
4936 Objects that take too much storage
4937
4938 @item
4939 Unchecked conversion between types of differing sizes
4940
4941 @item
4942 Missing @code{return} statement along some execution path in a function
4943
4944 @item
4945 Incorrect (unrecognized) pragmas
4946
4947 @item
4948 Incorrect external names
4949
4950 @item
4951 Allocation from empty storage pool
4952
4953 @item
4954 Potentially blocking operation in protected type
4955
4956 @item
4957 Suspicious parenthesization of expressions
4958
4959 @item
4960 Mismatching bounds in an aggregate
4961
4962 @item
4963 Attempt to return local value by reference
4964
4965 @item
4966 Premature instantiation of a generic body
4967
4968 @item
4969 Attempt to pack aliased components
4970
4971 @item
4972 Out of bounds array subscripts
4973
4974 @item
4975 Wrong length on string assignment
4976
4977 @item
4978 Violations of style rules if style checking is enabled
4979
4980 @item
4981 Unused @code{with} clauses
4982
4983 @item
4984 @code{Bit_Order} usage that does not have any effect
4985
4986 @item
4987 @code{Standard.Duration} used to resolve universal fixed expression
4988
4989 @item
4990 Dereference of possibly null value
4991
4992 @item
4993 Declaration that is likely to cause storage error
4994
4995 @item
4996 Internal GNAT unit @code{with}'ed by application unit
4997
4998 @item
4999 Values known to be out of range at compile time
5000
5001 @item
5002 Unreferenced labels and variables
5003
5004 @item
5005 Address overlays that could clobber memory
5006
5007 @item
5008 Unexpected initialization when address clause present
5009
5010 @item
5011 Bad alignment for address clause
5012
5013 @item
5014 Useless type conversions
5015
5016 @item
5017 Redundant assignment statements and other redundant constructs
5018
5019 @item
5020 Useless exception handlers
5021
5022 @item
5023 Accidental hiding of name by child unit
5024
5025 @item
5026 Access before elaboration detected at compile time
5027
5028 @item
5029 A range in a @code{for} loop that is known to be null or might be null
5030
5031 @end itemize
5032
5033 @noindent
5034 The following section lists compiler switches that are available
5035 to control the handling of warning messages. It is also possible
5036 to exercise much finer control over what warnings are issued and
5037 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5038 gnat_rm, GNAT Reference manual}.
5039
5040 @table @option
5041 @c !sort!
5042 @item -gnatwa
5043 @emph{Activate all optional errors.}
5044 @cindex @option{-gnatwa} (@command{gcc})
5045 This switch activates most optional warning messages, see remaining list
5046 in this section for details on optional warning messages that can be
5047 individually controlled.  The warnings that are not turned on by this
5048 switch are
5049 @option{-gnatwd} (implicit dereferencing),
5050 @option{-gnatwh} (hiding),
5051 @option{-gnatwl} (elaboration warnings),
5052 @option{-gnatw.o} (warn on values set by out parameters ignored)
5053 and @option{-gnatwt} (tracking of deleted conditional code).
5054 All other optional warnings are turned on.
5055
5056 @item -gnatwA
5057 @emph{Suppress all optional errors.}
5058 @cindex @option{-gnatwA} (@command{gcc})
5059 This switch suppresses all optional warning messages, see remaining list
5060 in this section for details on optional warning messages that can be
5061 individually controlled.
5062
5063 @item -gnatw.a
5064 @emph{Activate warnings on failing assertions.}
5065 @cindex @option{-gnatw.a} (@command{gcc})
5066 @cindex Assert failures
5067 This switch activates warnings for assertions where the compiler can tell at
5068 compile time that the assertion will fail. Note that this warning is given
5069 even if assertions are disabled. The default is that such warnings are
5070 generated.
5071
5072 @item -gnatw.A
5073 @emph{Suppress warnings on failing assertions.}
5074 @cindex @option{-gnatw.A} (@command{gcc})
5075 @cindex Assert failures
5076 This switch suppresses warnings for assertions where the compiler can tell at
5077 compile time that the assertion will fail.
5078
5079 @item -gnatwb
5080 @emph{Activate warnings on bad fixed values.}
5081 @cindex @option{-gnatwb} (@command{gcc})
5082 @cindex Bad fixed values
5083 @cindex Fixed-point Small value
5084 @cindex Small value
5085 This switch activates warnings for static fixed-point expressions whose
5086 value is not an exact multiple of Small. Such values are implementation
5087 dependent, since an implementation is free to choose either of the multiples
5088 that surround the value. GNAT always chooses the closer one, but this is not
5089 required behavior, and it is better to specify a value that is an exact
5090 multiple, ensuring predictable execution. The default is that such warnings
5091 are not generated.
5092
5093 @item -gnatwB
5094 @emph{Suppress warnings on bad fixed values.}
5095 @cindex @option{-gnatwB} (@command{gcc})
5096 This switch suppresses warnings for static fixed-point expressions whose
5097 value is not an exact multiple of Small.
5098
5099 @item -gnatw.b
5100 @emph{Activate warnings on biased representation.}
5101 @cindex @option{-gnatw.b} (@command{gcc})
5102 @cindex Biased representation
5103 This switch activates warnings when a size clause, value size clause, component
5104 clause, or component size clause forces the use of biased representation for an
5105 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5106 to represent 10/11). The default is that such warnings are generated.
5107
5108 @item -gnatw.B
5109 @emph{Suppress warnings on biased representation.}
5110 @cindex @option{-gnatwB} (@command{gcc})
5111 This switch suppresses warnings for representation clauses that force the use
5112 of biased representation.
5113
5114 @item -gnatwc
5115 @emph{Activate warnings on conditionals.}
5116 @cindex @option{-gnatwc} (@command{gcc})
5117 @cindex Conditionals, constant
5118 This switch activates warnings for conditional expressions used in
5119 tests that are known to be True or False at compile time. The default
5120 is that such warnings are not generated.
5121 Note that this warning does
5122 not get issued for the use of boolean variables or constants whose
5123 values are known at compile time, since this is a standard technique
5124 for conditional compilation in Ada, and this would generate too many
5125 false positive warnings.
5126
5127 This warning option also activates a special test for comparisons using
5128 the operators ``>='' and`` <=''.
5129 If the compiler can tell that only the equality condition is possible,
5130 then it will warn that the ``>'' or ``<'' part of the test
5131 is useless and that the operator could be replaced by ``=''.
5132 An example would be comparing a @code{Natural} variable <= 0.
5133
5134 This warning option also generates warnings if
5135 one or both tests is optimized away in a membership test for integer
5136 values if the result can be determined at compile time. Range tests on
5137 enumeration types are not included, since it is common for such tests
5138 to include an end point.
5139
5140 This warning can also be turned on using @option{-gnatwa}.
5141
5142 @item -gnatwC
5143 @emph{Suppress warnings on conditionals.}
5144 @cindex @option{-gnatwC} (@command{gcc})
5145 This switch suppresses warnings for conditional expressions used in
5146 tests that are known to be True or False at compile time.
5147
5148 @item -gnatw.c
5149 @emph{Activate warnings on missing component clauses.}
5150 @cindex @option{-gnatw.c} (@command{gcc})
5151 @cindex Component clause, missing
5152 This switch activates warnings for record components where a record
5153 representation clause is present and has component clauses for the
5154 majority, but not all, of the components. A warning is given for each
5155 component for which no component clause is present.
5156
5157 This warning can also be turned on using @option{-gnatwa}.
5158
5159 @item -gnatw.C
5160 @emph{Suppress warnings on missing component clauses.}
5161 @cindex @option{-gnatwC} (@command{gcc})
5162 This switch suppresses warnings for record components that are
5163 missing a component clause in the situation described above.
5164
5165 @item -gnatwd
5166 @emph{Activate warnings on implicit dereferencing.}
5167 @cindex @option{-gnatwd} (@command{gcc})
5168 If this switch is set, then the use of a prefix of an access type
5169 in an indexed component, slice, or selected component without an
5170 explicit @code{.all} will generate a warning. With this warning
5171 enabled, access checks occur only at points where an explicit
5172 @code{.all} appears in the source code (assuming no warnings are
5173 generated as a result of this switch). The default is that such
5174 warnings are not generated.
5175 Note that @option{-gnatwa} does not affect the setting of
5176 this warning option.
5177
5178 @item -gnatwD
5179 @emph{Suppress warnings on implicit dereferencing.}
5180 @cindex @option{-gnatwD} (@command{gcc})
5181 @cindex Implicit dereferencing
5182 @cindex Dereferencing, implicit
5183 This switch suppresses warnings for implicit dereferences in
5184 indexed components, slices, and selected components.
5185
5186 @item -gnatwe
5187 @emph{Treat warnings as errors.}
5188 @cindex @option{-gnatwe} (@command{gcc})
5189 @cindex Warnings, treat as error
5190 This switch causes warning messages to be treated as errors.
5191 The warning string still appears, but the warning messages are counted
5192 as errors, and prevent the generation of an object file.
5193
5194 @item -gnatw.e
5195 @emph{Activate every optional warning}
5196 @cindex @option{-gnatw.e} (@command{gcc})
5197 @cindex Warnings, activate every optional warning
5198 This switch activates all optional warnings, including those which
5199 are not activated by @code{-gnatwa}.
5200
5201 @item -gnatwf
5202 @emph{Activate warnings on unreferenced formals.}
5203 @cindex @option{-gnatwf} (@command{gcc})
5204 @cindex Formals, unreferenced
5205 This switch causes a warning to be generated if a formal parameter
5206 is not referenced in the body of the subprogram. This warning can
5207 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5208 default is that these warnings are not generated.
5209
5210 @item -gnatwF
5211 @emph{Suppress warnings on unreferenced formals.}
5212 @cindex @option{-gnatwF} (@command{gcc})
5213 This switch suppresses warnings for unreferenced formal
5214 parameters. Note that the
5215 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5216 effect of warning on unreferenced entities other than subprogram
5217 formals.
5218
5219 @item -gnatwg
5220 @emph{Activate warnings on unrecognized pragmas.}
5221 @cindex @option{-gnatwg} (@command{gcc})
5222 @cindex Pragmas, unrecognized
5223 This switch causes a warning to be generated if an unrecognized
5224 pragma is encountered. Apart from issuing this warning, the
5225 pragma is ignored and has no effect. This warning can
5226 also be turned on using @option{-gnatwa}. The default
5227 is that such warnings are issued (satisfying the Ada Reference
5228 Manual requirement that such warnings appear).
5229
5230 @item -gnatwG
5231 @emph{Suppress warnings on unrecognized pragmas.}
5232 @cindex @option{-gnatwG} (@command{gcc})
5233 This switch suppresses warnings for unrecognized pragmas.
5234
5235 @item -gnatwh
5236 @emph{Activate warnings on hiding.}
5237 @cindex @option{-gnatwh} (@command{gcc})
5238 @cindex Hiding of Declarations
5239 This switch activates warnings on hiding declarations.
5240 A declaration is considered hiding
5241 if it is for a non-overloadable entity, and it declares an entity with the
5242 same name as some other entity that is directly or use-visible. The default
5243 is that such warnings are not generated.
5244 Note that @option{-gnatwa} does not affect the setting of this warning option.
5245
5246 @item -gnatwH
5247 @emph{Suppress warnings on hiding.}
5248 @cindex @option{-gnatwH} (@command{gcc})
5249 This switch suppresses warnings on hiding declarations.
5250
5251 @item -gnatwi
5252 @emph{Activate warnings on implementation units.}
5253 @cindex @option{-gnatwi} (@command{gcc})
5254 This switch activates warnings for a @code{with} of an internal GNAT
5255 implementation unit, defined as any unit from the @code{Ada},
5256 @code{Interfaces}, @code{GNAT},
5257 ^^@code{DEC},^ or @code{System}
5258 hierarchies that is not
5259 documented in either the Ada Reference Manual or the GNAT
5260 Programmer's Reference Manual. Such units are intended only
5261 for internal implementation purposes and should not be @code{with}'ed
5262 by user programs. The default is that such warnings are generated
5263 This warning can also be turned on using @option{-gnatwa}.
5264
5265 @item -gnatwI
5266 @emph{Disable warnings on implementation units.}
5267 @cindex @option{-gnatwI} (@command{gcc})
5268 This switch disables warnings for a @code{with} of an internal GNAT
5269 implementation unit.
5270
5271 @item -gnatwj
5272 @emph{Activate warnings on obsolescent features (Annex J).}
5273 @cindex @option{-gnatwj} (@command{gcc})
5274 @cindex Features, obsolescent
5275 @cindex Obsolescent features
5276 If this warning option is activated, then warnings are generated for
5277 calls to subprograms marked with @code{pragma Obsolescent} and
5278 for use of features in Annex J of the Ada Reference Manual. In the
5279 case of Annex J, not all features are flagged. In particular use
5280 of the renamed packages (like @code{Text_IO}) and use of package
5281 @code{ASCII} are not flagged, since these are very common and
5282 would generate many annoying positive warnings. The default is that
5283 such warnings are not generated. This warning is also turned on by
5284 the use of @option{-gnatwa}.
5285
5286 In addition to the above cases, warnings are also generated for
5287 GNAT features that have been provided in past versions but which
5288 have been superseded (typically by features in the new Ada standard).
5289 For example, @code{pragma Ravenscar} will be flagged since its
5290 function is replaced by @code{pragma Profile(Ravenscar)}.
5291
5292 Note that this warning option functions differently from the
5293 restriction @code{No_Obsolescent_Features} in two respects.
5294 First, the restriction applies only to annex J features.
5295 Second, the restriction does flag uses of package @code{ASCII}.
5296
5297 @item -gnatwJ
5298 @emph{Suppress warnings on obsolescent features (Annex J).}
5299 @cindex @option{-gnatwJ} (@command{gcc})
5300 This switch disables warnings on use of obsolescent features.
5301
5302 @item -gnatwk
5303 @emph{Activate warnings on variables that could be constants.}
5304 @cindex @option{-gnatwk} (@command{gcc})
5305 This switch activates warnings for variables that are initialized but
5306 never modified, and then could be declared constants. The default is that
5307 such warnings are not given.
5308 This warning can also be turned on using @option{-gnatwa}.
5309
5310 @item -gnatwK
5311 @emph{Suppress warnings on variables that could be constants.}
5312 @cindex @option{-gnatwK} (@command{gcc})
5313 This switch disables warnings on variables that could be declared constants.
5314
5315 @item -gnatwl
5316 @emph{Activate warnings for elaboration pragmas.}
5317 @cindex @option{-gnatwl} (@command{gcc})
5318 @cindex Elaboration, warnings
5319 This switch activates warnings on missing
5320 @code{Elaborate_All} and @code{Elaborate} pragmas.
5321 See the section in this guide on elaboration checking for details on
5322 when such pragmas should be used. In dynamic elaboration mode, this switch
5323 generations warnings about the need to add elaboration pragmas. Note however,
5324 that if you blindly follow these warnings, and add @code{Elaborate_All}
5325 warnings wherever they are recommended, you basically end up with the
5326 equivalent of the static elaboration model, which may not be what you want for
5327 legacy code for which the static model does not work.
5328
5329 For the static model, the messages generated are labeled "info:" (for
5330 information messages). They are not warnings to add elaboration pragmas,
5331 merely informational messages showing what implicit elaboration pragmas
5332 have been added, for use in analyzing elaboration circularity problems.
5333
5334 Warnings are also generated if you
5335 are using the static mode of elaboration, and a @code{pragma Elaborate}
5336 is encountered. The default is that such warnings
5337 are not generated.
5338 This warning is not automatically turned on by the use of @option{-gnatwa}.
5339
5340 @item -gnatwL
5341 @emph{Suppress warnings for elaboration pragmas.}
5342 @cindex @option{-gnatwL} (@command{gcc})
5343 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5344 See the section in this guide on elaboration checking for details on
5345 when such pragmas should be used.
5346
5347 @item -gnatwm
5348 @emph{Activate warnings on modified but unreferenced variables.}
5349 @cindex @option{-gnatwm} (@command{gcc})
5350 This switch activates warnings for variables that are assigned (using
5351 an initialization value or with one or more assignment statements) but
5352 whose value is never read. The warning is suppressed for volatile
5353 variables and also for variables that are renamings of other variables
5354 or for which an address clause is given.
5355 This warning can also be turned on using @option{-gnatwa}.
5356 The default is that these warnings are not given.
5357
5358 @item -gnatwM
5359 @emph{Disable warnings on modified but unreferenced variables.}
5360 @cindex @option{-gnatwM} (@command{gcc})
5361 This switch disables warnings for variables that are assigned or
5362 initialized, but never read.
5363
5364 @item -gnatw.m
5365 @emph{Activate warnings on suspicious modulus values.}
5366 @cindex @option{-gnatw.m} (@command{gcc})
5367 This switch activates warnings for modulus values that seem suspicious.
5368 The cases caught are where the size is the same as the modulus (e.g.
5369 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5370 with no size clause. The guess in both cases is that 2**x was intended
5371 rather than x. The default is that these warnings are given.
5372
5373 @item -gnatw.M
5374 @emph{Disable warnings on suspicious modulus values.}
5375 @cindex @option{-gnatw.M} (@command{gcc})
5376 This switch disables warnings for suspicious modulus values.
5377
5378 @item -gnatwn
5379 @emph{Set normal warnings mode.}
5380 @cindex @option{-gnatwn} (@command{gcc})
5381 This switch sets normal warning mode, in which enabled warnings are
5382 issued and treated as warnings rather than errors. This is the default
5383 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5384 an explicit @option{-gnatws} or
5385 @option{-gnatwe}. It also cancels the effect of the
5386 implicit @option{-gnatwe} that is activated by the
5387 use of @option{-gnatg}.
5388
5389 @item -gnatwo
5390 @emph{Activate warnings on address clause overlays.}
5391 @cindex @option{-gnatwo} (@command{gcc})
5392 @cindex Address Clauses, warnings
5393 This switch activates warnings for possibly unintended initialization
5394 effects of defining address clauses that cause one variable to overlap
5395 another. The default is that such warnings are generated.
5396 This warning can also be turned on using @option{-gnatwa}.
5397
5398 @item -gnatwO
5399 @emph{Suppress warnings on address clause overlays.}
5400 @cindex @option{-gnatwO} (@command{gcc})
5401 This switch suppresses warnings on possibly unintended initialization
5402 effects of defining address clauses that cause one variable to overlap
5403 another.
5404
5405 @item -gnatw.o
5406 @emph{Activate warnings on modified but unreferenced out parameters.}
5407 @cindex @option{-gnatw.o} (@command{gcc})
5408 This switch activates warnings for variables that are modified by using
5409 them as actuals for a call to a procedure with an out mode formal, where
5410 the resulting assigned value is never read. It is applicable in the case
5411 where there is more than one out mode formal. If there is only one out
5412 mode formal, the warning is issued by default (controlled by -gnatwu).
5413 The warning is suppressed for volatile
5414 variables and also for variables that are renamings of other variables
5415 or for which an address clause is given.
5416 The default is that these warnings are not given. Note that this warning
5417 is not included in -gnatwa, it must be activated explicitly.
5418
5419 @item -gnatw.O
5420 @emph{Disable warnings on modified but unreferenced out parameters.}
5421 @cindex @option{-gnatw.O} (@command{gcc})
5422 This switch suppresses warnings for variables that are modified by using
5423 them as actuals for a call to a procedure with an out mode formal, where
5424 the resulting assigned value is never read.
5425
5426 @item -gnatwp
5427 @emph{Activate warnings on ineffective pragma Inlines.}
5428 @cindex @option{-gnatwp} (@command{gcc})
5429 @cindex Inlining, warnings
5430 This switch activates warnings for failure of front end inlining
5431 (activated by @option{-gnatN}) to inline a particular call. There are
5432 many reasons for not being able to inline a call, including most
5433 commonly that the call is too complex to inline. The default is
5434 that such warnings are not given.
5435 This warning can also be turned on using @option{-gnatwa}.
5436 Warnings on ineffective inlining by the gcc back-end can be activated
5437 separately, using the gcc switch -Winline.
5438
5439 @item -gnatwP
5440 @emph{Suppress warnings on ineffective pragma Inlines.}
5441 @cindex @option{-gnatwP} (@command{gcc})
5442 This switch suppresses warnings on ineffective pragma Inlines. If the
5443 inlining mechanism cannot inline a call, it will simply ignore the
5444 request silently.
5445
5446 @item -gnatw.p
5447 @emph{Activate warnings on parameter ordering.}
5448 @cindex @option{-gnatw.p} (@command{gcc})
5449 @cindex Parameter order, warnings
5450 This switch activates warnings for cases of suspicious parameter
5451 ordering when the list of arguments are all simple identifiers that
5452 match the names of the formals, but are in a different order. The
5453 warning is suppressed if any use of named parameter notation is used,
5454 so this is the appropriate way to suppress a false positive (and
5455 serves to emphasize that the "misordering" is deliberate). The
5456 default is
5457 that such warnings are not given.
5458 This warning can also be turned on using @option{-gnatwa}.
5459
5460 @item -gnatw.P
5461 @emph{Suppress warnings on parameter ordering.}
5462 @cindex @option{-gnatw.P} (@command{gcc})
5463 This switch suppresses warnings on cases of suspicious parameter
5464 ordering.
5465
5466 @item -gnatwq
5467 @emph{Activate warnings on questionable missing parentheses.}
5468 @cindex @option{-gnatwq} (@command{gcc})
5469 @cindex Parentheses, warnings
5470 This switch activates warnings for cases where parentheses are not used and
5471 the result is potential ambiguity from a readers point of view. For example
5472 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5473 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5474 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5475 follow the rule of always parenthesizing to make the association clear, and
5476 this warning switch warns if such parentheses are not present. The default
5477 is that these warnings are given.
5478 This warning can also be turned on using @option{-gnatwa}.
5479
5480 @item -gnatwQ
5481 @emph{Suppress warnings on questionable missing parentheses.}
5482 @cindex @option{-gnatwQ} (@command{gcc})
5483 This switch suppresses warnings for cases where the association is not
5484 clear and the use of parentheses is preferred.
5485
5486 @item -gnatwr
5487 @emph{Activate warnings on redundant constructs.}
5488 @cindex @option{-gnatwr} (@command{gcc})
5489 This switch activates warnings for redundant constructs. The following
5490 is the current list of constructs regarded as redundant:
5491
5492 @itemize @bullet
5493 @item
5494 Assignment of an item to itself.
5495 @item
5496 Type conversion that converts an expression to its own type.
5497 @item
5498 Use of the attribute @code{Base} where @code{typ'Base} is the same
5499 as @code{typ}.
5500 @item
5501 Use of pragma @code{Pack} when all components are placed by a record
5502 representation clause.
5503 @item
5504 Exception handler containing only a reraise statement (raise with no
5505 operand) which has no effect.
5506 @item
5507 Use of the operator abs on an operand that is known at compile time
5508 to be non-negative
5509 @item
5510 Comparison of boolean expressions to an explicit True value.
5511 @end itemize
5512
5513 This warning can also be turned on using @option{-gnatwa}.
5514 The default is that warnings for redundant constructs are not given.
5515
5516 @item -gnatwR
5517 @emph{Suppress warnings on redundant constructs.}
5518 @cindex @option{-gnatwR} (@command{gcc})
5519 This switch suppresses warnings for redundant constructs.
5520
5521 @item -gnatw.r
5522 @emph{Activate warnings for object renaming function.}
5523 @cindex @option{-gnatw.r} (@command{gcc})
5524 This switch activates warnings for an object renaming that renames a
5525 function call, which is equivalent to a constant declaration (as
5526 opposed to renaming the function itself).  The default is that these
5527 warnings are given.  This warning can also be turned on using
5528 @option{-gnatwa}.
5529
5530 @item -gnatw.R
5531 @emph{Suppress warnings for object renaming function.}
5532 @cindex @option{-gnatwT} (@command{gcc})
5533 This switch suppresses warnings for object renaming function.
5534
5535 @item -gnatws
5536 @emph{Suppress all warnings.}
5537 @cindex @option{-gnatws} (@command{gcc})
5538 This switch completely suppresses the
5539 output of all warning messages from the GNAT front end.
5540 Note that it does not suppress warnings from the @command{gcc} back end.
5541 To suppress these back end warnings as well, use the switch @option{-w}
5542 in addition to @option{-gnatws}.
5543
5544 @item -gnatwt
5545 @emph{Activate warnings for tracking of deleted conditional code.}
5546 @cindex @option{-gnatwt} (@command{gcc})
5547 @cindex Deactivated code, warnings
5548 @cindex Deleted code, warnings
5549 This switch activates warnings for tracking of code in conditionals (IF and
5550 CASE statements) that is detected to be dead code which cannot be executed, and
5551 which is removed by the front end. This warning is off by default, and is not
5552 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5553 useful for detecting deactivated code in certified applications.
5554
5555 @item -gnatwT
5556 @emph{Suppress warnings for tracking of deleted conditional code.}
5557 @cindex @option{-gnatwT} (@command{gcc})
5558 This switch suppresses warnings for tracking of deleted conditional code.
5559
5560 @item -gnatwu
5561 @emph{Activate warnings on unused entities.}
5562 @cindex @option{-gnatwu} (@command{gcc})
5563 This switch activates warnings to be generated for entities that
5564 are declared but not referenced, and for units that are @code{with}'ed
5565 and not
5566 referenced. In the case of packages, a warning is also generated if
5567 no entities in the package are referenced. This means that if the package
5568 is referenced but the only references are in @code{use}
5569 clauses or @code{renames}
5570 declarations, a warning is still generated. A warning is also generated
5571 for a generic package that is @code{with}'ed but never instantiated.
5572 In the case where a package or subprogram body is compiled, and there
5573 is a @code{with} on the corresponding spec
5574 that is only referenced in the body,
5575 a warning is also generated, noting that the
5576 @code{with} can be moved to the body. The default is that
5577 such warnings are not generated.
5578 This switch also activates warnings on unreferenced formals
5579 (it includes the effect of @option{-gnatwf}).
5580 This warning can also be turned on using @option{-gnatwa}.
5581
5582 @item -gnatwU
5583 @emph{Suppress warnings on unused entities.}
5584 @cindex @option{-gnatwU} (@command{gcc})
5585 This switch suppresses warnings for unused entities and packages.
5586 It also turns off warnings on unreferenced formals (and thus includes
5587 the effect of @option{-gnatwF}).
5588
5589 @item -gnatwv
5590 @emph{Activate warnings on unassigned variables.}
5591 @cindex @option{-gnatwv} (@command{gcc})
5592 @cindex Unassigned variable warnings
5593 This switch activates warnings for access to variables which
5594 may not be properly initialized. The default is that
5595 such warnings are generated.
5596 This warning can also be turned on using @option{-gnatwa}.
5597
5598 @item -gnatwV
5599 @emph{Suppress warnings on unassigned variables.}
5600 @cindex @option{-gnatwV} (@command{gcc})
5601 This switch suppresses warnings for access to variables which
5602 may not be properly initialized.
5603 For variables of a composite type, the warning can also be suppressed in
5604 Ada 2005 by using a default initialization with a box. For example, if
5605 Table is an array of records whose components are only partially uninitialized,
5606 then the following code:
5607
5608 @smallexample @c ada
5609    Tab : Table := (others => <>);
5610 @end smallexample
5611
5612 will suppress warnings on subsequent statements that access components
5613 of variable Tab.
5614
5615 @item -gnatww
5616 @emph{Activate warnings on wrong low bound assumption.}
5617 @cindex @option{-gnatww} (@command{gcc})
5618 @cindex String indexing warnings
5619 This switch activates warnings for indexing an unconstrained string parameter
5620 with a literal or S'Length. This is a case where the code is assuming that the
5621 low bound is one, which is in general not true (for example when a slice is
5622 passed). The default is that such warnings are generated.
5623 This warning can also be turned on using @option{-gnatwa}.
5624
5625 @item -gnatwW
5626 @emph{Suppress warnings on wrong low bound assumption.}
5627 @cindex @option{-gnatwW} (@command{gcc})
5628 This switch suppresses warnings for indexing an unconstrained string parameter
5629 with a literal or S'Length. Note that this warning can also be suppressed
5630 in a particular case by adding an
5631 assertion that the lower bound is 1,
5632 as shown in the following example.
5633
5634 @smallexample @c ada
5635    procedure K (S : String) is
5636       pragma Assert (S'First = 1);
5637       @dots{}
5638 @end smallexample
5639
5640 @item -gnatw.w
5641 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5642 @cindex @option{-gnatw.w} (@command{gcc})
5643 @cindex Warnings Off control
5644 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5645 where either the pragma is entirely useless (because it suppresses no
5646 warnings), or it could be replaced by @code{pragma Unreferenced} or
5647 @code{pragma Unmodified}.The default is that these warnings are not given.
5648 Note that this warning is not included in -gnatwa, it must be
5649 activated explicitly.
5650
5651 @item -gnatw.W
5652 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5653 @cindex @option{-gnatw.W} (@command{gcc})
5654 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5655
5656 @item -gnatwx
5657 @emph{Activate warnings on Export/Import pragmas.}
5658 @cindex @option{-gnatwx} (@command{gcc})
5659 @cindex Export/Import pragma warnings
5660 This switch activates warnings on Export/Import pragmas when
5661 the compiler detects a possible conflict between the Ada and
5662 foreign language calling sequences. For example, the use of
5663 default parameters in a convention C procedure is dubious
5664 because the C compiler cannot supply the proper default, so
5665 a warning is issued. The default is that such warnings are
5666 generated.
5667 This warning can also be turned on using @option{-gnatwa}.
5668
5669 @item -gnatwX
5670 @emph{Suppress warnings on Export/Import pragmas.}
5671 @cindex @option{-gnatwX} (@command{gcc})
5672 This switch suppresses warnings on Export/Import pragmas.
5673 The sense of this is that you are telling the compiler that
5674 you know what you are doing in writing the pragma, and it
5675 should not complain at you.
5676
5677 @item -gnatw.x
5678 @emph{Activate warnings for No_Exception_Propagation mode.}
5679 @cindex @option{-gnatwm} (@command{gcc})
5680 This switch activates warnings for exception usage when pragma Restrictions
5681 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5682 explicit exception raises which are not covered by a local handler, and for
5683 exception handlers which do not cover a local raise. The default is that these
5684 warnings are not given.
5685
5686 @item -gnatw.X
5687 @emph{Disable warnings for No_Exception_Propagation mode.}
5688 This switch disables warnings for exception usage when pragma Restrictions
5689 (No_Exception_Propagation) is in effect.
5690
5691 @item -gnatwy
5692 @emph{Activate warnings for Ada 2005 compatibility issues.}
5693 @cindex @option{-gnatwy} (@command{gcc})
5694 @cindex Ada 2005 compatibility issues warnings
5695 For the most part Ada 2005 is upwards compatible with Ada 95,
5696 but there are some exceptions (for example the fact that
5697 @code{interface} is now a reserved word in Ada 2005). This
5698 switch activates several warnings to help in identifying
5699 and correcting such incompatibilities. The default is that
5700 these warnings are generated. Note that at one point Ada 2005
5701 was called Ada 0Y, hence the choice of character.
5702 This warning can also be turned on using @option{-gnatwa}.
5703
5704 @item -gnatwY
5705 @emph{Disable warnings for Ada 2005 compatibility issues.}
5706 @cindex @option{-gnatwY} (@command{gcc})
5707 @cindex Ada 2005 compatibility issues warnings
5708 This switch suppresses several warnings intended to help in identifying
5709 incompatibilities between Ada 95 and Ada 2005.
5710
5711 @item -gnatwz
5712 @emph{Activate warnings on unchecked conversions.}
5713 @cindex @option{-gnatwz} (@command{gcc})
5714 @cindex Unchecked_Conversion warnings
5715 This switch activates warnings for unchecked conversions
5716 where the types are known at compile time to have different
5717 sizes. The default
5718 is that such warnings are generated. Warnings are also
5719 generated for subprogram pointers with different conventions,
5720 and, on VMS only, for data pointers with different conventions.
5721 This warning can also be turned on using @option{-gnatwa}.
5722
5723 @item -gnatwZ
5724 @emph{Suppress warnings on unchecked conversions.}
5725 @cindex @option{-gnatwZ} (@command{gcc})
5726 This switch suppresses warnings for unchecked conversions
5727 where the types are known at compile time to have different
5728 sizes or conventions.
5729
5730 @item ^-Wunused^WARNINGS=UNUSED^
5731 @cindex @option{-Wunused}
5732 The warnings controlled by the @option{-gnatw} switch are generated by
5733 the front end of the compiler. The @option{GCC} back end can provide
5734 additional warnings and they are controlled by the @option{-W} switch.
5735 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5736 warnings for entities that are declared but not referenced.
5737
5738 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5739 @cindex @option{-Wuninitialized}
5740 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5741 the back end warning for uninitialized variables. This switch must be
5742 used in conjunction with an optimization level greater than zero.
5743
5744 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5745 @cindex @option{-Wall}
5746 This switch enables all the above warnings from the @option{GCC} back end.
5747 The code generator detects a number of warning situations that are missed
5748 by the @option{GNAT} front end, and this switch can be used to activate them.
5749 The use of this switch also sets the default front end warning mode to
5750 @option{-gnatwa}, that is, most front end warnings activated as well.
5751
5752 @item ^-w^/NO_BACK_END_WARNINGS^
5753 @cindex @option{-w}
5754 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5755 The use of this switch also sets the default front end warning mode to
5756 @option{-gnatws}, that is, front end warnings suppressed as well.
5757
5758 @end table
5759
5760 @noindent
5761 @ifclear vms
5762 A string of warning parameters can be used in the same parameter. For example:
5763
5764 @smallexample
5765 -gnatwaLe
5766 @end smallexample
5767
5768 @noindent
5769 will turn on all optional warnings except for elaboration pragma warnings,
5770 and also specify that warnings should be treated as errors.
5771 @end ifclear
5772 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5773
5774 @table @option
5775 @c !sort!
5776 @item -gnatwC
5777 @item -gnatwD
5778 @item -gnatwF
5779 @item -gnatwg
5780 @item -gnatwH
5781 @item -gnatwi
5782 @item -gnatwJ
5783 @item -gnatwK
5784 @item -gnatwL
5785 @item -gnatwM
5786 @item -gnatwn
5787 @item -gnatwo
5788 @item -gnatwP
5789 @item -gnatwR
5790 @item -gnatwU
5791 @item -gnatwv
5792 @item -gnatwz
5793 @item -gnatwx
5794
5795 @end table
5796
5797 @node Debugging and Assertion Control
5798 @subsection Debugging and Assertion Control
5799
5800 @table @option
5801 @item -gnata
5802 @cindex @option{-gnata} (@command{gcc})
5803 @findex Assert
5804 @findex Debug
5805 @cindex Assertions
5806
5807 @noindent
5808 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5809 are ignored. This switch, where @samp{a} stands for assert, causes
5810 @code{Assert} and @code{Debug} pragmas to be activated.
5811
5812 The pragmas have the form:
5813
5814 @smallexample
5815 @cartouche
5816    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5817                       @var{static-string-expression}@r{]})
5818    @b{pragma} Debug (@var{procedure call})
5819 @end cartouche
5820 @end smallexample
5821
5822 @noindent
5823 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5824 If the result is @code{True}, the pragma has no effect (other than
5825 possible side effects from evaluating the expression). If the result is
5826 @code{False}, the exception @code{Assert_Failure} declared in the package
5827 @code{System.Assertions} is
5828 raised (passing @var{static-string-expression}, if present, as the
5829 message associated with the exception). If no string expression is
5830 given the default is a string giving the file name and line number
5831 of the pragma.
5832
5833 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5834 @code{pragma Debug} may appear within a declaration sequence, allowing
5835 debugging procedures to be called between declarations.
5836
5837 @ifset vms
5838 @item /DEBUG@r{[}=debug-level@r{]}
5839 @itemx  /NODEBUG
5840 Specifies how much debugging information is to be included in
5841 the resulting object file where 'debug-level' is one of the following:
5842 @table @code
5843 @item   TRACEBACK
5844 Include both debugger symbol records and traceback
5845 the object file.
5846 This is the default setting.
5847 @item   ALL
5848 Include both debugger symbol records and traceback in
5849 object file.
5850 @item   NONE
5851 Excludes both debugger symbol records and traceback
5852 the object file. Same as /NODEBUG.
5853 @item   SYMBOLS
5854 Includes only debugger symbol records in the object
5855 file. Note that this doesn't include traceback information.
5856 @end table
5857 @end ifset
5858 @end table
5859
5860 @node Validity Checking
5861 @subsection Validity Checking
5862 @findex Validity Checking
5863
5864 @noindent
5865 The Ada Reference Manual defines the concept of invalid values (see
5866 RM 13.9.1). The primary source of invalid values is uninitialized
5867 variables. A scalar variable that is left uninitialized may contain
5868 an invalid value; the concept of invalid does not apply to access or
5869 composite types.
5870
5871 It is an error to read an invalid value, but the RM does not require
5872 run-time checks to detect such errors, except for some minimal
5873 checking to prevent erroneous execution (i.e. unpredictable
5874 behavior). This corresponds to the @option{-gnatVd} switch below,
5875 which is the default. For example, by default, if the expression of a
5876 case statement is invalid, it will raise Constraint_Error rather than
5877 causing a wild jump, and if an array index on the left-hand side of an
5878 assignment is invalid, it will raise Constraint_Error rather than
5879 overwriting an arbitrary memory location.
5880
5881 The @option{-gnatVa} may be used to enable additional validity checks,
5882 which are not required by the RM. These checks are often very
5883 expensive (which is why the RM does not require them). These checks
5884 are useful in tracking down uninitialized variables, but they are
5885 not usually recommended for production builds.
5886
5887 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5888 control; you can enable whichever validity checks you desire. However,
5889 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5890 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5891 sufficient for non-debugging use.
5892
5893 The @option{-gnatB} switch tells the compiler to assume that all
5894 values are valid (that is, within their declared subtype range)
5895 except in the context of a use of the Valid attribute. This means
5896 the compiler can generate more efficient code, since the range
5897 of values is better known at compile time. However, an uninitialized
5898 variable can cause wild jumps and memory corruption in this mode.
5899
5900 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5901 checking mode as described below.
5902 @ifclear vms
5903 The @code{x} argument is a string of letters that
5904 indicate validity checks that are performed or not performed in addition
5905 to the default checks required by Ada as described above.
5906 @end ifclear
5907 @ifset vms
5908 The options allowed for this qualifier
5909 indicate validity checks that are performed or not performed in addition
5910 to the default checks required by Ada as described above.
5911 @end ifset
5912
5913 @table @option
5914 @c !sort!
5915 @item -gnatVa
5916 @emph{All validity checks.}
5917 @cindex @option{-gnatVa} (@command{gcc})
5918 All validity checks are turned on.
5919 @ifclear vms
5920 That is, @option{-gnatVa} is
5921 equivalent to @option{gnatVcdfimorst}.
5922 @end ifclear
5923
5924 @item -gnatVc
5925 @emph{Validity checks for copies.}
5926 @cindex @option{-gnatVc} (@command{gcc})
5927 The right hand side of assignments, and the initializing values of
5928 object declarations are validity checked.
5929
5930 @item -gnatVd
5931 @emph{Default (RM) validity checks.}
5932 @cindex @option{-gnatVd} (@command{gcc})
5933 Some validity checks are done by default following normal Ada semantics
5934 (RM 13.9.1 (9-11)).
5935 A check is done in case statements that the expression is within the range
5936 of the subtype. If it is not, Constraint_Error is raised.
5937 For assignments to array components, a check is done that the expression used
5938 as index is within the range. If it is not, Constraint_Error is raised.
5939 Both these validity checks may be turned off using switch @option{-gnatVD}.
5940 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5941 switch @option{-gnatVd} will leave the checks turned on.
5942 Switch @option{-gnatVD} should be used only if you are sure that all such
5943 expressions have valid values. If you use this switch and invalid values
5944 are present, then the program is erroneous, and wild jumps or memory
5945 overwriting may occur.
5946
5947 @item -gnatVe
5948 @emph{Validity checks for elementary components.}
5949 @cindex @option{-gnatVe} (@command{gcc})
5950 In the absence of this switch, assignments to record or array components are
5951 not validity checked, even if validity checks for assignments generally
5952 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5953 require valid data, but assignment of individual components does. So for
5954 example, there is a difference between copying the elements of an array with a
5955 slice assignment, compared to assigning element by element in a loop. This
5956 switch allows you to turn off validity checking for components, even when they
5957 are assigned component by component.
5958
5959 @item -gnatVf
5960 @emph{Validity checks for floating-point values.}
5961 @cindex @option{-gnatVf} (@command{gcc})
5962 In the absence of this switch, validity checking occurs only for discrete
5963 values. If @option{-gnatVf} is specified, then validity checking also applies
5964 for floating-point values, and NaNs and infinities are considered invalid,
5965 as well as out of range values for constrained types. Note that this means
5966 that standard IEEE infinity mode is not allowed. The exact contexts
5967 in which floating-point values are checked depends on the setting of other
5968 options. For example,
5969 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5970 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5971 (the order does not matter) specifies that floating-point parameters of mode
5972 @code{in} should be validity checked.
5973
5974 @item -gnatVi
5975 @emph{Validity checks for @code{in} mode parameters}
5976 @cindex @option{-gnatVi} (@command{gcc})
5977 Arguments for parameters of mode @code{in} are validity checked in function
5978 and procedure calls at the point of call.
5979
5980 @item -gnatVm
5981 @emph{Validity checks for @code{in out} mode parameters.}
5982 @cindex @option{-gnatVm} (@command{gcc})
5983 Arguments for parameters of mode @code{in out} are validity checked in
5984 procedure calls at the point of call. The @code{'m'} here stands for
5985 modify, since this concerns parameters that can be modified by the call.
5986 Note that there is no specific option to test @code{out} parameters,
5987 but any reference within the subprogram will be tested in the usual
5988 manner, and if an invalid value is copied back, any reference to it
5989 will be subject to validity checking.
5990
5991 @item -gnatVn
5992 @emph{No validity checks.}
5993 @cindex @option{-gnatVn} (@command{gcc})
5994 This switch turns off all validity checking, including the default checking
5995 for case statements and left hand side subscripts. Note that the use of
5996 the switch @option{-gnatp} suppresses all run-time checks, including
5997 validity checks, and thus implies @option{-gnatVn}. When this switch
5998 is used, it cancels any other @option{-gnatV} previously issued.
5999
6000 @item -gnatVo
6001 @emph{Validity checks for operator and attribute operands.}
6002 @cindex @option{-gnatVo} (@command{gcc})
6003 Arguments for predefined operators and attributes are validity checked.
6004 This includes all operators in package @code{Standard},
6005 the shift operators defined as intrinsic in package @code{Interfaces}
6006 and operands for attributes such as @code{Pos}. Checks are also made
6007 on individual component values for composite comparisons, and on the
6008 expressions in type conversions and qualified expressions. Checks are
6009 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6010
6011 @item -gnatVp
6012 @emph{Validity checks for parameters.}
6013 @cindex @option{-gnatVp} (@command{gcc})
6014 This controls the treatment of parameters within a subprogram (as opposed
6015 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6016 of parameters on a call. If either of these call options is used, then
6017 normally an assumption is made within a subprogram that the input arguments
6018 have been validity checking at the point of call, and do not need checking
6019 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6020 is not made, and parameters are not assumed to be valid, so their validity
6021 will be checked (or rechecked) within the subprogram.
6022
6023 @item -gnatVr
6024 @emph{Validity checks for function returns.}
6025 @cindex @option{-gnatVr} (@command{gcc})
6026 The expression in @code{return} statements in functions is validity
6027 checked.
6028
6029 @item -gnatVs
6030 @emph{Validity checks for subscripts.}
6031 @cindex @option{-gnatVs} (@command{gcc})
6032 All subscripts expressions are checked for validity, whether they appear
6033 on the right side or left side (in default mode only left side subscripts
6034 are validity checked).
6035
6036 @item -gnatVt
6037 @emph{Validity checks for tests.}
6038 @cindex @option{-gnatVt} (@command{gcc})
6039 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6040 statements are checked, as well as guard expressions in entry calls.
6041
6042 @end table
6043
6044 @noindent
6045 The @option{-gnatV} switch may be followed by
6046 ^a string of letters^a list of options^
6047 to turn on a series of validity checking options.
6048 For example,
6049 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6050 specifies that in addition to the default validity checking, copies and
6051 function return expressions are to be validity checked.
6052 In order to make it easier
6053 to specify the desired combination of effects,
6054 @ifclear vms
6055 the upper case letters @code{CDFIMORST} may
6056 be used to turn off the corresponding lower case option.
6057 @end ifclear
6058 @ifset vms
6059 the prefix @code{NO} on an option turns off the corresponding validity
6060 checking:
6061 @itemize @bullet
6062 @item @code{NOCOPIES}
6063 @item @code{NODEFAULT}
6064 @item @code{NOFLOATS}
6065 @item @code{NOIN_PARAMS}
6066 @item @code{NOMOD_PARAMS}
6067 @item @code{NOOPERANDS}
6068 @item @code{NORETURNS}
6069 @item @code{NOSUBSCRIPTS}
6070 @item @code{NOTESTS}
6071 @end itemize
6072 @end ifset
6073 Thus
6074 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6075 turns on all validity checking options except for
6076 checking of @code{@b{in out}} procedure arguments.
6077
6078 The specification of additional validity checking generates extra code (and
6079 in the case of @option{-gnatVa} the code expansion can be substantial).
6080 However, these additional checks can be very useful in detecting
6081 uninitialized variables, incorrect use of unchecked conversion, and other
6082 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6083 is useful in conjunction with the extra validity checking, since this
6084 ensures that wherever possible uninitialized variables have invalid values.
6085
6086 See also the pragma @code{Validity_Checks} which allows modification of
6087 the validity checking mode at the program source level, and also allows for
6088 temporary disabling of validity checks.
6089
6090 @node Style Checking
6091 @subsection Style Checking
6092 @findex Style checking
6093
6094 @noindent
6095 The @option{-gnaty^x^(option,option,@dots{})^} switch
6096 @cindex @option{-gnaty} (@command{gcc})
6097 causes the compiler to
6098 enforce specified style rules. A limited set of style rules has been used
6099 in writing the GNAT sources themselves. This switch allows user programs
6100 to activate all or some of these checks. If the source program fails a
6101 specified style check, an appropriate warning message is given, preceded by
6102 the character sequence ``(style)''.
6103 @ifset vms
6104 @code{(option,option,@dots{})} is a sequence of keywords
6105 @end ifset
6106 @ifclear vms
6107 The string @var{x} is a sequence of letters or digits
6108 @end ifclear
6109 indicating the particular style
6110 checks to be performed. The following checks are defined:
6111
6112 @table @option
6113 @c !sort!
6114 @item 0-9
6115 @emph{Specify indentation level.}
6116 If a digit from 1-9 appears
6117 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6118 then proper indentation is checked, with the digit indicating the
6119 indentation level required. A value of zero turns off this style check.
6120 The general style of required indentation is as specified by
6121 the examples in the Ada Reference Manual. Full line comments must be
6122 aligned with the @code{--} starting on a column that is a multiple of
6123 the alignment level, or they may be aligned the same way as the following
6124 non-blank line (this is useful when full line comments appear in the middle
6125 of a statement.
6126
6127 @item ^a^ATTRIBUTE^
6128 @emph{Check attribute casing.}
6129 Attribute names, including the case of keywords such as @code{digits}
6130 used as attributes names, must be written in mixed case, that is, the
6131 initial letter and any letter following an underscore must be uppercase.
6132 All other letters must be lowercase.
6133
6134 @item ^A^ARRAY_INDEXES^
6135 @emph{Use of array index numbers in array attributes.}
6136 When using the array attributes First, Last, Range,
6137 or Length, the index number must be omitted for one-dimensional arrays
6138 and is required for multi-dimensional arrays.
6139
6140 @item ^b^BLANKS^
6141 @emph{Blanks not allowed at statement end.}
6142 Trailing blanks are not allowed at the end of statements. The purpose of this
6143 rule, together with h (no horizontal tabs), is to enforce a canonical format
6144 for the use of blanks to separate source tokens.
6145
6146 @item ^B^BOOLEAN_OPERATORS^
6147 @emph{Check Boolean operators.}
6148 The use of AND/OR operators is not permitted except in the cases of modular
6149 operands, array operands, and simple stand-alone boolean variables or
6150 boolean constants. In all other cases AND THEN/OR ELSE are required.
6151
6152 @item ^c^COMMENTS^
6153 @emph{Check comments.}
6154 Comments must meet the following set of rules:
6155
6156 @itemize @bullet
6157
6158 @item
6159 The ``@code{--}'' that starts the column must either start in column one,
6160 or else at least one blank must precede this sequence.
6161
6162 @item
6163 Comments that follow other tokens on a line must have at least one blank
6164 following the ``@code{--}'' at the start of the comment.
6165
6166 @item
6167 Full line comments must have two blanks following the ``@code{--}'' that
6168 starts the comment, with the following exceptions.
6169
6170 @item
6171 A line consisting only of the ``@code{--}'' characters, possibly preceded
6172 by blanks is permitted.
6173
6174 @item
6175 A comment starting with ``@code{--x}'' where @code{x} is a special character
6176 is permitted.
6177 This allows proper processing of the output generated by specialized tools
6178 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6179 annotation
6180 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6181 special character is defined as being in one of the ASCII ranges
6182 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6183 Note that this usage is not permitted
6184 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6185
6186 @item
6187 A line consisting entirely of minus signs, possibly preceded by blanks, is
6188 permitted. This allows the construction of box comments where lines of minus
6189 signs are used to form the top and bottom of the box.
6190
6191 @item
6192 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6193 least one blank follows the initial ``@code{--}''. Together with the preceding
6194 rule, this allows the construction of box comments, as shown in the following
6195 example:
6196 @smallexample
6197 ---------------------------
6198 -- This is a box comment --
6199 -- with two text lines.  --
6200 ---------------------------
6201 @end smallexample
6202 @end itemize
6203
6204 @item ^d^DOS_LINE_ENDINGS^
6205 @emph{Check no DOS line terminators present.}
6206 All lines must be terminated by a single ASCII.LF
6207 character (in particular the DOS line terminator sequence CR/LF is not
6208 allowed).
6209
6210 @item ^e^END^
6211 @emph{Check end/exit labels.}
6212 Optional labels on @code{end} statements ending subprograms and on
6213 @code{exit} statements exiting named loops, are required to be present.
6214
6215 @item ^f^VTABS^
6216 @emph{No form feeds or vertical tabs.}
6217 Neither form feeds nor vertical tab characters are permitted
6218 in the source text.
6219
6220 @item ^g^GNAT^
6221 @emph{GNAT style mode}
6222 The set of style check switches is set to match that used by the GNAT sources.
6223 This may be useful when developing code that is eventually intended to be
6224 incorporated into GNAT. For further details, see GNAT sources.
6225
6226 @item ^h^HTABS^
6227 @emph{No horizontal tabs.}
6228 Horizontal tab characters are not permitted in the source text.
6229 Together with the b (no blanks at end of line) check, this
6230 enforces a canonical form for the use of blanks to separate
6231 source tokens.
6232
6233 @item ^i^IF_THEN^
6234 @emph{Check if-then layout.}
6235 The keyword @code{then} must appear either on the same
6236 line as corresponding @code{if}, or on a line on its own, lined
6237 up under the @code{if} with at least one non-blank line in between
6238 containing all or part of the condition to be tested.
6239
6240 @item ^I^IN_MODE^
6241 @emph{check mode IN keywords}
6242 Mode @code{in} (the default mode) is not
6243 allowed to be given explicitly. @code{in out} is fine,
6244 but not @code{in} on its own.
6245
6246 @item ^k^KEYWORD^
6247 @emph{Check keyword casing.}
6248 All keywords must be in lower case (with the exception of keywords
6249 such as @code{digits} used as attribute names to which this check
6250 does not apply).
6251
6252 @item ^l^LAYOUT^
6253 @emph{Check layout.}
6254 Layout of statement and declaration constructs must follow the
6255 recommendations in the Ada Reference Manual, as indicated by the
6256 form of the syntax rules. For example an @code{else} keyword must
6257 be lined up with the corresponding @code{if} keyword.
6258
6259 There are two respects in which the style rule enforced by this check
6260 option are more liberal than those in the Ada Reference Manual. First
6261 in the case of record declarations, it is permissible to put the
6262 @code{record} keyword on the same line as the @code{type} keyword, and
6263 then the @code{end} in @code{end record} must line up under @code{type}.
6264 This is also permitted when the type declaration is split on two lines.
6265 For example, any of the following three layouts is acceptable:
6266
6267 @smallexample @c ada
6268 @cartouche
6269 type q is record
6270    a : integer;
6271    b : integer;
6272 end record;
6273
6274 type q is
6275    record
6276       a : integer;
6277       b : integer;
6278    end record;
6279
6280 type q is
6281    record
6282       a : integer;
6283       b : integer;
6284 end record;
6285
6286 @end cartouche
6287 @end smallexample
6288
6289 @noindent
6290 Second, in the case of a block statement, a permitted alternative
6291 is to put the block label on the same line as the @code{declare} or
6292 @code{begin} keyword, and then line the @code{end} keyword up under
6293 the block label. For example both the following are permitted:
6294
6295 @smallexample @c ada
6296 @cartouche
6297 Block : declare
6298    A : Integer := 3;
6299 begin
6300    Proc (A, A);
6301 end Block;
6302
6303 Block :
6304    declare
6305       A : Integer := 3;
6306    begin
6307       Proc (A, A);
6308    end Block;
6309 @end cartouche
6310 @end smallexample
6311
6312 @noindent
6313 The same alternative format is allowed for loops. For example, both of
6314 the following are permitted:
6315
6316 @smallexample @c ada
6317 @cartouche
6318 Clear : while J < 10 loop
6319    A (J) := 0;
6320 end loop Clear;
6321
6322 Clear :
6323    while J < 10 loop
6324       A (J) := 0;
6325    end loop Clear;
6326 @end cartouche
6327 @end smallexample
6328
6329 @item ^Lnnn^MAX_NESTING=nnn^
6330 @emph{Set maximum nesting level}
6331 The maximum level of nesting of constructs (including subprograms, loops,
6332 blocks, packages, and conditionals) may not exceed the given value
6333 @option{nnn}. A value of zero disconnects this style check.
6334
6335 @item ^m^LINE_LENGTH^
6336 @emph{Check maximum line length.}
6337 The length of source lines must not exceed 79 characters, including
6338 any trailing blanks. The value of 79 allows convenient display on an
6339 80 character wide device or window, allowing for possible special
6340 treatment of 80 character lines. Note that this count is of
6341 characters in the source text. This means that a tab character counts
6342 as one character in this count but a wide character sequence counts as
6343 a single character (however many bytes are needed in the encoding).
6344
6345 @item ^Mnnn^MAX_LENGTH=nnn^
6346 @emph{Set maximum line length.}
6347 The length of lines must not exceed the
6348 given value @option{nnn}. The maximum value that can be specified is 32767.
6349
6350 @item ^n^STANDARD_CASING^
6351 @emph{Check casing of entities in Standard.}
6352 Any identifier from Standard must be cased
6353 to match the presentation in the Ada Reference Manual (for example,
6354 @code{Integer} and @code{ASCII.NUL}).
6355
6356 @item ^N^NONE^
6357 @emph{Turn off all style checks}
6358 All style check options are turned off.
6359
6360 @item ^o^ORDERED_SUBPROGRAMS^
6361 @emph{Check order of subprogram bodies.}
6362 All subprogram bodies in a given scope
6363 (e.g.@: a package body) must be in alphabetical order. The ordering
6364 rule uses normal Ada rules for comparing strings, ignoring casing
6365 of letters, except that if there is a trailing numeric suffix, then
6366 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6367 before Junk10).
6368
6369 @item ^O^OVERRIDING_INDICATORS^
6370 @emph{Check that overriding subprograms are explicitly marked as such.}
6371 The declaration of a primitive operation of a type extension that overrides
6372 an inherited operation must carry an overriding indicator.
6373
6374 @item ^p^PRAGMA^
6375 @emph{Check pragma casing.}
6376 Pragma names must be written in mixed case, that is, the
6377 initial letter and any letter following an underscore must be uppercase.
6378 All other letters must be lowercase.
6379
6380 @item ^r^REFERENCES^
6381 @emph{Check references.}
6382 All identifier references must be cased in the same way as the
6383 corresponding declaration. No specific casing style is imposed on
6384 identifiers. The only requirement is for consistency of references
6385 with declarations.
6386
6387 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6388 @emph{Check no statements after THEN/ELSE.}
6389 No statements are allowed
6390 on the same line as a THEN or ELSE keyword following the
6391 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6392 and a special exception allows a pragma to appear after ELSE.
6393
6394 @item ^s^SPECS^
6395 @emph{Check separate specs.}
6396 Separate declarations (``specs'') are required for subprograms (a
6397 body is not allowed to serve as its own declaration). The only
6398 exception is that parameterless library level procedures are
6399 not required to have a separate declaration. This exception covers
6400 the most frequent form of main program procedures.
6401
6402 @item ^t^TOKEN^
6403 @emph{Check token spacing.}
6404 The following token spacing rules are enforced:
6405
6406 @itemize @bullet
6407
6408 @item
6409 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6410
6411 @item
6412 The token @code{=>} must be surrounded by spaces.
6413
6414 @item
6415 The token @code{<>} must be preceded by a space or a left parenthesis.
6416
6417 @item
6418 Binary operators other than @code{**} must be surrounded by spaces.
6419 There is no restriction on the layout of the @code{**} binary operator.
6420
6421 @item
6422 Colon must be surrounded by spaces.
6423
6424 @item
6425 Colon-equal (assignment, initialization) must be surrounded by spaces.
6426
6427 @item
6428 Comma must be the first non-blank character on the line, or be
6429 immediately preceded by a non-blank character, and must be followed
6430 by a space.
6431
6432 @item
6433 If the token preceding a left parenthesis ends with a letter or digit, then
6434 a space must separate the two tokens.
6435
6436 @item
6437 A right parenthesis must either be the first non-blank character on
6438 a line, or it must be preceded by a non-blank character.
6439
6440 @item
6441 A semicolon must not be preceded by a space, and must not be followed by
6442 a non-blank character.
6443
6444 @item
6445 A unary plus or minus may not be followed by a space.
6446
6447 @item
6448 A vertical bar must be surrounded by spaces.
6449 @end itemize
6450
6451 @item ^u^UNNECESSARY_BLANK_LINES^
6452 @emph{Check unnecessary blank lines.}
6453 Unnecessary blank lines are not allowed. A blank line is considered
6454 unnecessary if it appears at the end of the file, or if more than
6455 one blank line occurs in sequence.
6456
6457 @item ^x^XTRA_PARENS^
6458 @emph{Check extra parentheses.}
6459 Unnecessary extra level of parentheses (C-style) are not allowed
6460 around conditions in @code{if} statements, @code{while} statements and
6461 @code{exit} statements.
6462
6463 @item ^y^ALL_BUILTIN^
6464 @emph{Set all standard style check options}
6465 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6466 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6467 @option{-gnatyS}, @option{-gnatyLnnn},
6468 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6469
6470 @ifclear vms
6471 @item -
6472 @emph{Remove style check options}
6473 This causes any subsequent options in the string to act as canceling the
6474 corresponding style check option. To cancel maximum nesting level control,
6475 use @option{L} parameter witout any integer value after that, because any
6476 digit following @option{-} in the parameter string of the @option{-gnaty}
6477 option will be threated as canceling indentation check. The same is true
6478 for @option{M} parameter. @option{y} and @option{N} parameters are not
6479 allowed after @option{-}.
6480
6481 @item +
6482 This causes any subsequent options in the string to enable the corresponding
6483 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6484 if any.
6485 @end ifclear
6486
6487 @ifset vms
6488 @item NOxxx
6489 @emph{Removing style check options}
6490 If the name of a style check is preceded by @option{NO} then the corresponding
6491 style check is turned off. For example @option{NOCOMMENTS} turns off style
6492 checking for comments.
6493 @end ifset
6494 @end table
6495
6496 @noindent
6497 In the above rules, appearing in column one is always permitted, that is,
6498 counts as meeting either a requirement for a required preceding space,
6499 or as meeting a requirement for no preceding space.
6500
6501 Appearing at the end of a line is also always permitted, that is, counts
6502 as meeting either a requirement for a following space, or as meeting
6503 a requirement for no following space.
6504
6505 @noindent
6506 If any of these style rules is violated, a message is generated giving
6507 details on the violation. The initial characters of such messages are
6508 always ``@code{(style)}''. Note that these messages are treated as warning
6509 messages, so they normally do not prevent the generation of an object
6510 file. The @option{-gnatwe} switch can be used to treat warning messages,
6511 including style messages, as fatal errors.
6512
6513 The switch
6514 @ifclear vms
6515 @option{-gnaty} on its own (that is not
6516 followed by any letters or digits), then the effect is equivalent
6517 to the use of @option{-gnatyy}, as described above, that is all
6518 built-in standard style check options are enabled.
6519
6520 @end ifclear
6521 @ifset vms
6522 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6523 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6524 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6525 @end ifset
6526
6527
6528
6529 The switch
6530 @ifclear vms
6531 @option{-gnatyN}
6532 @end ifclear
6533 @ifset vms
6534 /STYLE_CHECKS=NONE
6535 @end ifset
6536 clears any previously set style checks.
6537
6538 @node Run-Time Checks
6539 @subsection Run-Time Checks
6540 @cindex Division by zero
6541 @cindex Access before elaboration
6542 @cindex Checks, division by zero
6543 @cindex Checks, access before elaboration
6544 @cindex Checks, stack overflow checking
6545
6546 @noindent
6547 By default, the following checks are suppressed: integer overflow
6548 checks, stack overflow checks, and checks for access before
6549 elaboration on subprogram calls. All other checks, including range
6550 checks and array bounds checks, are turned on by default. The
6551 following @command{gcc} switches refine this default behavior.
6552
6553 @table @option
6554 @c !sort!
6555 @item -gnatp
6556 @cindex @option{-gnatp} (@command{gcc})
6557 @cindex Suppressing checks
6558 @cindex Checks, suppressing
6559 @findex Suppress
6560 This switch causes the unit to be compiled
6561 as though @code{pragma Suppress (All_checks)}
6562 had been present in the source. Validity checks are also eliminated (in
6563 other words @option{-gnatp} also implies @option{-gnatVn}.
6564 Use this switch to improve the performance
6565 of the code at the expense of safety in the presence of invalid data or
6566 program bugs.
6567
6568 Note that when checks are suppressed, the compiler is allowed, but not
6569 required, to omit the checking code. If the run-time cost of the
6570 checking code is zero or near-zero, the compiler will generate it even
6571 if checks are suppressed. In particular, if the compiler can prove
6572 that a certain check will necessarily fail, it will generate code to
6573 do an unconditional ``raise'', even if checks are suppressed. The
6574 compiler warns in this case. Another case in which checks may not be
6575 eliminated is when they are embedded in certain run time routines such
6576 as math library routines.
6577
6578 Of course, run-time checks are omitted whenever the compiler can prove
6579 that they will not fail, whether or not checks are suppressed.
6580
6581 Note that if you suppress a check that would have failed, program
6582 execution is erroneous, which means the behavior is totally
6583 unpredictable. The program might crash, or print wrong answers, or
6584 do anything else. It might even do exactly what you wanted it to do
6585 (and then it might start failing mysteriously next week or next
6586 year). The compiler will generate code based on the assumption that
6587 the condition being checked is true, which can result in disaster if
6588 that assumption is wrong.
6589
6590 @item -gnato
6591 @cindex @option{-gnato} (@command{gcc})
6592 @cindex Overflow checks
6593 @cindex Check, overflow
6594 Enables overflow checking for integer operations.
6595 This causes GNAT to generate slower and larger executable
6596 programs by adding code to check for overflow (resulting in raising
6597 @code{Constraint_Error} as required by standard Ada
6598 semantics). These overflow checks correspond to situations in which
6599 the true value of the result of an operation may be outside the base
6600 range of the result type. The following example shows the distinction:
6601
6602 @smallexample @c ada
6603 X1 : Integer := "Integer'Last";
6604 X2 : Integer range 1 .. 5 := "5";
6605 X3 : Integer := "Integer'Last";
6606 X4 : Integer range 1 .. 5 := "5";
6607 F  : Float := "2.0E+20";
6608 @dots{}
6609 X1 := X1 + 1;
6610 X2 := X2 + 1;
6611 X3 := Integer (F);
6612 X4 := Integer (F);
6613 @end smallexample
6614
6615 @noindent
6616 Note that if explicit values are assigned at compile time, the
6617 compiler may be able to detect overflow at compile time, in which case
6618 no actual run-time checking code is required, and Constraint_Error
6619 will be raised unconditionally, with or without
6620 @option{-gnato}. That's why the assigned values in the above fragment
6621 are in quotes, the meaning is "assign a value not known to the
6622 compiler that happens to be equal to ...". The remaining discussion
6623 assumes that the compiler cannot detect the values at compile time.
6624
6625 Here the first addition results in a value that is outside the base range
6626 of Integer, and hence requires an overflow check for detection of the
6627 constraint error. Thus the first assignment to @code{X1} raises a
6628 @code{Constraint_Error} exception only if @option{-gnato} is set.
6629
6630 The second increment operation results in a violation of the explicit
6631 range constraint; such range checks are performed by default, and are
6632 unaffected by @option{-gnato}.
6633
6634 The two conversions of @code{F} both result in values that are outside
6635 the base range of type @code{Integer} and thus will raise
6636 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6637 The fact that the result of the second conversion is assigned to
6638 variable @code{X4} with a restricted range is irrelevant, since the problem
6639 is in the conversion, not the assignment.
6640
6641 Basically the rule is that in the default mode (@option{-gnato} not
6642 used), the generated code assures that all integer variables stay
6643 within their declared ranges, or within the base range if there is
6644 no declared range. This prevents any serious problems like indexes
6645 out of range for array operations.
6646
6647 What is not checked in default mode is an overflow that results in
6648 an in-range, but incorrect value. In the above example, the assignments
6649 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6650 range of the target variable, but the result is wrong in the sense that
6651 it is too large to be represented correctly. Typically the assignment
6652 to @code{X1} will result in wrap around to the largest negative number.
6653 The conversions of @code{F} will result in some @code{Integer} value
6654 and if that integer value is out of the @code{X4} range then the
6655 subsequent assignment would generate an exception.
6656
6657 @findex Machine_Overflows
6658 Note that the @option{-gnato} switch does not affect the code generated
6659 for any floating-point operations; it applies only to integer
6660 semantics).
6661 For floating-point, GNAT has the @code{Machine_Overflows}
6662 attribute set to @code{False} and the normal mode of operation is to
6663 generate IEEE NaN and infinite values on overflow or invalid operations
6664 (such as dividing 0.0 by 0.0).
6665
6666 The reason that we distinguish overflow checking from other kinds of
6667 range constraint checking is that a failure of an overflow check, unlike
6668 for example the failure of a range check, can result in an incorrect
6669 value, but cannot cause random memory destruction (like an out of range
6670 subscript), or a wild jump (from an out of range case value). Overflow
6671 checking is also quite expensive in time and space, since in general it
6672 requires the use of double length arithmetic.
6673
6674 Note again that @option{-gnato} is off by default, so overflow checking is
6675 not performed in default mode. This means that out of the box, with the
6676 default settings, GNAT does not do all the checks expected from the
6677 language description in the Ada Reference Manual. If you want all constraint
6678 checks to be performed, as described in this Manual, then you must
6679 explicitly use the -gnato switch either on the @command{gnatmake} or
6680 @command{gcc} command.
6681
6682 @item -gnatE
6683 @cindex @option{-gnatE} (@command{gcc})
6684 @cindex Elaboration checks
6685 @cindex Check, elaboration
6686 Enables dynamic checks for access-before-elaboration
6687 on subprogram calls and generic instantiations.
6688 Note that @option{-gnatE} is not necessary for safety, because in the
6689 default mode, GNAT ensures statically that the checks would not fail.
6690 For full details of the effect and use of this switch,
6691 @xref{Compiling Using gcc}.
6692
6693 @item -fstack-check
6694 @cindex @option{-fstack-check} (@command{gcc})
6695 @cindex Stack Overflow Checking
6696 @cindex Checks, stack overflow checking
6697 Activates stack overflow checking. For full details of the effect and use of
6698 this switch see @ref{Stack Overflow Checking}.
6699 @end table
6700
6701 @findex Unsuppress
6702 @noindent
6703 The setting of these switches only controls the default setting of the
6704 checks. You may modify them using either @code{Suppress} (to remove
6705 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6706 the program source.
6707
6708 @node Using gcc for Syntax Checking
6709 @subsection Using @command{gcc} for Syntax Checking
6710 @table @option
6711 @item -gnats
6712 @cindex @option{-gnats} (@command{gcc})
6713 @ifclear vms
6714
6715 @noindent
6716 The @code{s} stands for ``syntax''.
6717 @end ifclear
6718
6719 Run GNAT in syntax checking only mode. For
6720 example, the command
6721
6722 @smallexample
6723 $ gcc -c -gnats x.adb
6724 @end smallexample
6725
6726 @noindent
6727 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6728 series of files in a single command
6729 @ifclear vms
6730 , and can use wild cards to specify such a group of files.
6731 Note that you must specify the @option{-c} (compile
6732 only) flag in addition to the @option{-gnats} flag.
6733 @end ifclear
6734 .
6735 You may use other switches in conjunction with @option{-gnats}. In
6736 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6737 format of any generated error messages.
6738
6739 When the source file is empty or contains only empty lines and/or comments,
6740 the output is a warning:
6741
6742 @smallexample
6743 $ gcc -c -gnats -x ada toto.txt
6744 toto.txt:1:01: warning: empty file, contains no compilation units
6745 $
6746 @end smallexample
6747
6748 Otherwise, the output is simply the error messages, if any. No object file or
6749 ALI file is generated by a syntax-only compilation. Also, no units other
6750 than the one specified are accessed. For example, if a unit @code{X}
6751 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6752 check only mode does not access the source file containing unit
6753 @code{Y}.
6754
6755 @cindex Multiple units, syntax checking
6756 Normally, GNAT allows only a single unit in a source file. However, this
6757 restriction does not apply in syntax-check-only mode, and it is possible
6758 to check a file containing multiple compilation units concatenated
6759 together. This is primarily used by the @code{gnatchop} utility
6760 (@pxref{Renaming Files Using gnatchop}).
6761 @end table
6762
6763 @node Using gcc for Semantic Checking
6764 @subsection Using @command{gcc} for Semantic Checking
6765 @table @option
6766 @item -gnatc
6767 @cindex @option{-gnatc} (@command{gcc})
6768
6769 @ifclear vms
6770 @noindent
6771 The @code{c} stands for ``check''.
6772 @end ifclear
6773 Causes the compiler to operate in semantic check mode,
6774 with full checking for all illegalities specified in the
6775 Ada Reference Manual, but without generation of any object code
6776 (no object file is generated).
6777
6778 Because dependent files must be accessed, you must follow the GNAT
6779 semantic restrictions on file structuring to operate in this mode:
6780
6781 @itemize @bullet
6782 @item
6783 The needed source files must be accessible
6784 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6785
6786 @item
6787 Each file must contain only one compilation unit.
6788
6789 @item
6790 The file name and unit name must match (@pxref{File Naming Rules}).
6791 @end itemize
6792
6793 The output consists of error messages as appropriate. No object file is
6794 generated. An @file{ALI} file is generated for use in the context of
6795 cross-reference tools, but this file is marked as not being suitable
6796 for binding (since no object file is generated).
6797 The checking corresponds exactly to the notion of
6798 legality in the Ada Reference Manual.
6799
6800 Any unit can be compiled in semantics-checking-only mode, including
6801 units that would not normally be compiled (subunits,
6802 and specifications where a separate body is present).
6803 @end table
6804
6805 @node Compiling Different Versions of Ada
6806 @subsection Compiling Different Versions of Ada
6807
6808 @noindent
6809 The switches described in this section allow you to explicitly specify
6810 the version of the Ada language that your programs are written in.
6811 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6812 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6813 indicate Ada 83 compatibility mode.
6814
6815 @table @option
6816 @cindex Compatibility with Ada 83
6817
6818 @item -gnat83 (Ada 83 Compatibility Mode)
6819 @cindex @option{-gnat83} (@command{gcc})
6820 @cindex ACVC, Ada 83 tests
6821 @cindex Ada 83 mode
6822
6823 @noindent
6824 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6825 specifies that the program is to be compiled in Ada 83 mode. With
6826 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6827 semantics where this can be done easily.
6828 It is not possible to guarantee this switch does a perfect
6829 job; some subtle tests, such as are
6830 found in earlier ACVC tests (and that have been removed from the ACATS suite
6831 for Ada 95), might not compile correctly.
6832 Nevertheless, this switch may be useful in some circumstances, for example
6833 where, due to contractual reasons, existing code needs to be maintained
6834 using only Ada 83 features.
6835
6836 With few exceptions (most notably the need to use @code{<>} on
6837 @cindex Generic formal parameters
6838 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6839 reserved words, and the use of packages
6840 with optional bodies), it is not necessary to specify the
6841 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6842 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6843 a correct Ada 83 program is usually also a correct program
6844 in these later versions of the language standard.
6845 For further information, please refer to @ref{Compatibility and Porting Guide}.
6846
6847 @item -gnat95 (Ada 95 mode)
6848 @cindex @option{-gnat95} (@command{gcc})
6849 @cindex Ada 95 mode
6850
6851 @noindent
6852 This switch directs the compiler to implement the Ada 95 version of the
6853 language.
6854 Since Ada 95 is almost completely upwards
6855 compatible with Ada 83, Ada 83 programs may generally be compiled using
6856 this switch (see the description of the @option{-gnat83} switch for further
6857 information about Ada 83 mode).
6858 If an Ada 2005 program is compiled in Ada 95 mode,
6859 uses of the new Ada 2005 features will cause error
6860 messages or warnings.
6861
6862 This switch also can be used to cancel the effect of a previous
6863 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6864
6865 @item -gnat05 (Ada 2005 mode)
6866 @cindex @option{-gnat05} (@command{gcc})
6867 @cindex Ada 2005 mode
6868
6869 @noindent
6870 This switch directs the compiler to implement the Ada 2005 version of the
6871 language.
6872 Since Ada 2005 is almost completely upwards
6873 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6874 may generally be compiled using this switch (see the description of the
6875 @option{-gnat83} and @option{-gnat95} switches for further
6876 information).
6877
6878 For information about the approved ``Ada Issues'' that have been incorporated
6879 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6880 Included with GNAT releases is a file @file{features-ada0y} that describes
6881 the set of implemented Ada 2005 features.
6882 @end table
6883
6884
6885 @node Character Set Control
6886 @subsection Character Set Control
6887 @table @option
6888 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6889 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6890
6891 @noindent
6892 Normally GNAT recognizes the Latin-1 character set in source program
6893 identifiers, as described in the Ada Reference Manual.
6894 This switch causes
6895 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6896 single character ^^or word^ indicating the character set, as follows:
6897
6898 @table @code
6899 @item 1
6900 ISO 8859-1 (Latin-1) identifiers
6901
6902 @item 2
6903 ISO 8859-2 (Latin-2) letters allowed in identifiers
6904
6905 @item 3
6906 ISO 8859-3 (Latin-3) letters allowed in identifiers
6907
6908 @item 4
6909 ISO 8859-4 (Latin-4) letters allowed in identifiers
6910
6911 @item 5
6912 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6913
6914 @item 9
6915 ISO 8859-15 (Latin-9) letters allowed in identifiers
6916
6917 @item ^p^PC^
6918 IBM PC letters (code page 437) allowed in identifiers
6919
6920 @item ^8^PC850^
6921 IBM PC letters (code page 850) allowed in identifiers
6922
6923 @item ^f^FULL_UPPER^
6924 Full upper-half codes allowed in identifiers
6925
6926 @item ^n^NO_UPPER^
6927 No upper-half codes allowed in identifiers
6928
6929 @item ^w^WIDE^
6930 Wide-character codes (that is, codes greater than 255)
6931 allowed in identifiers
6932 @end table
6933
6934 @xref{Foreign Language Representation}, for full details on the
6935 implementation of these character sets.
6936
6937 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6938 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6939 Specify the method of encoding for wide characters.
6940 @var{e} is one of the following:
6941
6942 @table @code
6943
6944 @item ^h^HEX^
6945 Hex encoding (brackets coding also recognized)
6946
6947 @item ^u^UPPER^
6948 Upper half encoding (brackets encoding also recognized)
6949
6950 @item ^s^SHIFT_JIS^
6951 Shift/JIS encoding (brackets encoding also recognized)
6952
6953 @item ^e^EUC^
6954 EUC encoding (brackets encoding also recognized)
6955
6956 @item ^8^UTF8^
6957 UTF-8 encoding (brackets encoding also recognized)
6958
6959 @item ^b^BRACKETS^
6960 Brackets encoding only (default value)
6961 @end table
6962 For full details on these encoding
6963 methods see @ref{Wide Character Encodings}.
6964 Note that brackets coding is always accepted, even if one of the other
6965 options is specified, so for example @option{-gnatW8} specifies that both
6966 brackets and UTF-8 encodings will be recognized. The units that are
6967 with'ed directly or indirectly will be scanned using the specified
6968 representation scheme, and so if one of the non-brackets scheme is
6969 used, it must be used consistently throughout the program. However,
6970 since brackets encoding is always recognized, it may be conveniently
6971 used in standard libraries, allowing these libraries to be used with
6972 any of the available coding schemes.
6973 scheme.
6974
6975 If no @option{-gnatW?} parameter is present, then the default
6976 representation is normally Brackets encoding only. However, if the
6977 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6978 byte order mark or BOM for UTF-8), then these three characters are
6979 skipped and the default representation for the file is set to UTF-8.
6980
6981 Note that the wide character representation that is specified (explicitly
6982 or by default) for the main program also acts as the default encoding used
6983 for Wide_Text_IO files if not specifically overridden by a WCEM form
6984 parameter.
6985
6986 @end table
6987 @node File Naming Control
6988 @subsection File Naming Control
6989
6990 @table @option
6991 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6992 @cindex @option{-gnatk} (@command{gcc})
6993 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6994 1-999, indicates the maximum allowable length of a file name (not
6995 including the @file{.ads} or @file{.adb} extension). The default is not
6996 to enable file name krunching.
6997
6998 For the source file naming rules, @xref{File Naming Rules}.
6999 @end table
7000
7001 @node Subprogram Inlining Control
7002 @subsection Subprogram Inlining Control
7003
7004 @table @option
7005 @c !sort!
7006 @item -gnatn
7007 @cindex @option{-gnatn} (@command{gcc})
7008 @ifclear vms
7009 The @code{n} here is intended to suggest the first syllable of the
7010 word ``inline''.
7011 @end ifclear
7012 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7013 inlining to actually occur, optimization must be enabled. To enable
7014 inlining of subprograms specified by pragma @code{Inline},
7015 you must also specify this switch.
7016 In the absence of this switch, GNAT does not attempt
7017 inlining and does not need to access the bodies of
7018 subprograms for which @code{pragma Inline} is specified if they are not
7019 in the current unit.
7020
7021 If you specify this switch the compiler will access these bodies,
7022 creating an extra source dependency for the resulting object file, and
7023 where possible, the call will be inlined.
7024 For further details on when inlining is possible
7025 see @ref{Inlining of Subprograms}.
7026
7027 @item -gnatN
7028 @cindex @option{-gnatN} (@command{gcc})
7029 This switch activates front-end inlining which also
7030 generates additional dependencies.
7031
7032 When using a gcc-based back end (in practice this means using any version
7033 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7034 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7035 Historically front end inlining was more extensive than the gcc back end
7036 inlining, but that is no longer the case.
7037 @end table
7038
7039 @node Auxiliary Output Control
7040 @subsection Auxiliary Output Control
7041
7042 @table @option
7043 @item -gnatt
7044 @cindex @option{-gnatt} (@command{gcc})
7045 @cindex Writing internal trees
7046 @cindex Internal trees, writing to file
7047 Causes GNAT to write the internal tree for a unit to a file (with the
7048 extension @file{.adt}.
7049 This not normally required, but is used by separate analysis tools.
7050 Typically
7051 these tools do the necessary compilations automatically, so you should
7052 not have to specify this switch in normal operation.
7053 Note that the combination of switches @option{-gnatct}
7054 generates a tree in the form required by ASIS applications.
7055
7056 @item -gnatu
7057 @cindex @option{-gnatu} (@command{gcc})
7058 Print a list of units required by this compilation on @file{stdout}.
7059 The listing includes all units on which the unit being compiled depends
7060 either directly or indirectly.
7061
7062 @ifclear vms
7063 @item -pass-exit-codes
7064 @cindex @option{-pass-exit-codes} (@command{gcc})
7065 If this switch is not used, the exit code returned by @command{gcc} when
7066 compiling multiple files indicates whether all source files have
7067 been successfully used to generate object files or not.
7068
7069 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7070 exit status and allows an integrated development environment to better
7071 react to a compilation failure. Those exit status are:
7072
7073 @table @asis
7074 @item 5
7075 There was an error in at least one source file.
7076 @item 3
7077 At least one source file did not generate an object file.
7078 @item 2
7079 The compiler died unexpectedly (internal error for example).
7080 @item 0
7081 An object file has been generated for every source file.
7082 @end table
7083 @end ifclear
7084 @end table
7085
7086 @node Debugging Control
7087 @subsection Debugging Control
7088
7089 @table @option
7090 @c !sort!
7091 @cindex Debugging options
7092 @ifclear vms
7093 @item -gnatd@var{x}
7094 @cindex @option{-gnatd} (@command{gcc})
7095 Activate internal debugging switches. @var{x} is a letter or digit, or
7096 string of letters or digits, which specifies the type of debugging
7097 outputs desired. Normally these are used only for internal development
7098 or system debugging purposes. You can find full documentation for these
7099 switches in the body of the @code{Debug} unit in the compiler source
7100 file @file{debug.adb}.
7101 @end ifclear
7102
7103 @item -gnatG[=nn]
7104 @cindex @option{-gnatG} (@command{gcc})
7105 This switch causes the compiler to generate auxiliary output containing
7106 a pseudo-source listing of the generated expanded code. Like most Ada
7107 compilers, GNAT works by first transforming the high level Ada code into
7108 lower level constructs. For example, tasking operations are transformed
7109 into calls to the tasking run-time routines. A unique capability of GNAT
7110 is to list this expanded code in a form very close to normal Ada source.
7111 This is very useful in understanding the implications of various Ada
7112 usage on the efficiency of the generated code. There are many cases in
7113 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7114 generate a lot of run-time code. By using @option{-gnatG} you can identify
7115 these cases, and consider whether it may be desirable to modify the coding
7116 approach to improve efficiency.
7117
7118 The optional parameter @code{nn} if present after -gnatG specifies an
7119 alternative maximum line length that overrides the normal default of 72.
7120 This value is in the range 40-999999, values less than 40 being silently
7121 reset to 40. The equal sign is optional.
7122
7123 The format of the output is very similar to standard Ada source, and is
7124 easily understood by an Ada programmer. The following special syntactic
7125 additions correspond to low level features used in the generated code that
7126 do not have any exact analogies in pure Ada source form. The following
7127 is a partial list of these special constructions. See the spec
7128 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7129
7130 If the switch @option{-gnatL} is used in conjunction with
7131 @cindex @option{-gnatL} (@command{gcc})
7132 @option{-gnatG}, then the original source lines are interspersed
7133 in the expanded source (as comment lines with the original line number).
7134
7135 @table @code
7136 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7137 Shows the storage pool being used for an allocator.
7138
7139 @item at end @var{procedure-name};
7140 Shows the finalization (cleanup) procedure for a scope.
7141
7142 @item (if @var{expr} then @var{expr} else @var{expr})
7143 Conditional expression equivalent to the @code{x?y:z} construction in C.
7144
7145 @item @var{target}^^^(@var{source})
7146 A conversion with floating-point truncation instead of rounding.
7147
7148 @item @var{target}?(@var{source})
7149 A conversion that bypasses normal Ada semantic checking. In particular
7150 enumeration types and fixed-point types are treated simply as integers.
7151
7152 @item @var{target}?^^^(@var{source})
7153 Combines the above two cases.
7154
7155 @item @var{x} #/ @var{y}
7156 @itemx @var{x} #mod @var{y}
7157 @itemx @var{x} #* @var{y}
7158 @itemx @var{x} #rem @var{y}
7159 A division or multiplication of fixed-point values which are treated as
7160 integers without any kind of scaling.
7161
7162 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7163 Shows the storage pool associated with a @code{free} statement.
7164
7165 @item [subtype or type declaration]
7166 Used to list an equivalent declaration for an internally generated
7167 type that is referenced elsewhere in the listing.
7168
7169 @item freeze @var{type-name} @ovar{actions}
7170 Shows the point at which @var{type-name} is frozen, with possible
7171 associated actions to be performed at the freeze point.
7172
7173 @item reference @var{itype}
7174 Reference (and hence definition) to internal type @var{itype}.
7175
7176 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7177 Intrinsic function call.
7178
7179 @item @var{label-name} : label
7180 Declaration of label @var{labelname}.
7181
7182 @item #$ @var{subprogram-name}
7183 An implicit call to a run-time support routine
7184 (to meet the requirement of H.3.1(9) in a
7185 convenient manner).
7186
7187 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7188 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7189 @var{expr}, but handled more efficiently).
7190
7191 @item [constraint_error]
7192 Raise the @code{Constraint_Error} exception.
7193
7194 @item @var{expression}'reference
7195 A pointer to the result of evaluating @var{expression}.
7196
7197 @item @var{target-type}!(@var{source-expression})
7198 An unchecked conversion of @var{source-expression} to @var{target-type}.
7199
7200 @item [@var{numerator}/@var{denominator}]
7201 Used to represent internal real literals (that) have no exact
7202 representation in base 2-16 (for example, the result of compile time
7203 evaluation of the expression 1.0/27.0).
7204 @end table
7205
7206 @item -gnatD[=nn]
7207 @cindex @option{-gnatD} (@command{gcc})
7208 When used in conjunction with @option{-gnatG}, this switch causes
7209 the expanded source, as described above for
7210 @option{-gnatG} to be written to files with names
7211 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7212 instead of to the standard output file. For
7213 example, if the source file name is @file{hello.adb}, then a file
7214 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7215 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7216 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7217 you to do source level debugging using the generated code which is
7218 sometimes useful for complex code, for example to find out exactly
7219 which part of a complex construction raised an exception. This switch
7220 also suppress generation of cross-reference information (see
7221 @option{-gnatx}) since otherwise the cross-reference information
7222 would refer to the @file{^.dg^.DG^} file, which would cause
7223 confusion since this is not the original source file.
7224
7225 Note that @option{-gnatD} actually implies @option{-gnatG}
7226 automatically, so it is not necessary to give both options.
7227 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7228
7229 If the switch @option{-gnatL} is used in conjunction with
7230 @cindex @option{-gnatL} (@command{gcc})
7231 @option{-gnatDG}, then the original source lines are interspersed
7232 in the expanded source (as comment lines with the original line number).
7233
7234 The optional parameter @code{nn} if present after -gnatD specifies an
7235 alternative maximum line length that overrides the normal default of 72.
7236 This value is in the range 40-999999, values less than 40 being silently
7237 reset to 40. The equal sign is optional.
7238
7239 @item -gnatr
7240 @cindex @option{-gnatr} (@command{gcc})
7241 @cindex pragma Restrictions
7242 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7243 so that violation of restrictions causes warnings rather than illegalities.
7244 This is useful during the development process when new restrictions are added
7245 or investigated. The switch also causes pragma Profile to be treated as
7246 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7247 restriction warnings rather than restrictions.
7248
7249 @ifclear vms
7250 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7251 @cindex @option{-gnatR} (@command{gcc})
7252 This switch controls output from the compiler of a listing showing
7253 representation information for declared types and objects. For
7254 @option{-gnatR0}, no information is output (equivalent to omitting
7255 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7256 so @option{-gnatR} with no parameter has the same effect), size and alignment
7257 information is listed for declared array and record types. For
7258 @option{-gnatR2}, size and alignment information is listed for all
7259 declared types and objects. Finally @option{-gnatR3} includes symbolic
7260 expressions for values that are computed at run time for
7261 variant records. These symbolic expressions have a mostly obvious
7262 format with #n being used to represent the value of the n'th
7263 discriminant. See source files @file{repinfo.ads/adb} in the
7264 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7265 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7266 the output is to a file with the name @file{^file.rep^file_REP^} where
7267 file is the name of the corresponding source file.
7268 @end ifclear
7269 @ifset vms
7270 @item /REPRESENTATION_INFO
7271 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7272 This qualifier controls output from the compiler of a listing showing
7273 representation information for declared types and objects. For
7274 @option{/REPRESENTATION_INFO=NONE}, no information is output
7275 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7276 @option{/REPRESENTATION_INFO} without option is equivalent to
7277 @option{/REPRESENTATION_INFO=ARRAYS}.
7278 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7279 information is listed for declared array and record types. For
7280 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7281 is listed for all expression information for values that are computed
7282 at run time for variant records. These symbolic expressions have a mostly
7283 obvious format with #n being used to represent the value of the n'th
7284 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7285 @code{GNAT} sources for full details on the format of
7286 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7287 If _FILE is added at the end of an option
7288 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7289 then the output is to a file with the name @file{file_REP} where
7290 file is the name of the corresponding source file.
7291 @end ifset
7292 Note that it is possible for record components to have zero size. In
7293 this case, the component clause uses an obvious extension of permitted
7294 Ada syntax, for example @code{at 0 range 0 .. -1}.
7295
7296 Representation information requires that code be generated (since it is the
7297 code generator that lays out complex data structures). If an attempt is made
7298 to output representation information when no code is generated, for example
7299 when a subunit is compiled on its own, then no information can be generated
7300 and the compiler outputs a message to this effect.
7301
7302 @item -gnatS
7303 @cindex @option{-gnatS} (@command{gcc})
7304 The use of the switch @option{-gnatS} for an
7305 Ada compilation will cause the compiler to output a
7306 representation of package Standard in a form very
7307 close to standard Ada. It is not quite possible to
7308 do this entirely in standard Ada (since new
7309 numeric base types cannot be created in standard
7310 Ada), but the output is easily
7311 readable to any Ada programmer, and is useful to
7312 determine the characteristics of target dependent
7313 types in package Standard.
7314
7315 @item -gnatx
7316 @cindex @option{-gnatx} (@command{gcc})
7317 Normally the compiler generates full cross-referencing information in
7318 the @file{ALI} file. This information is used by a number of tools,
7319 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7320 suppresses this information. This saves some space and may slightly
7321 speed up compilation, but means that these tools cannot be used.
7322 @end table
7323
7324 @node Exception Handling Control
7325 @subsection Exception Handling Control
7326
7327 @noindent
7328 GNAT uses two methods for handling exceptions at run-time. The
7329 @code{setjmp/longjmp} method saves the context when entering
7330 a frame with an exception handler. Then when an exception is
7331 raised, the context can be restored immediately, without the
7332 need for tracing stack frames. This method provides very fast
7333 exception propagation, but introduces significant overhead for
7334 the use of exception handlers, even if no exception is raised.
7335
7336 The other approach is called ``zero cost'' exception handling.
7337 With this method, the compiler builds static tables to describe
7338 the exception ranges. No dynamic code is required when entering
7339 a frame containing an exception handler. When an exception is
7340 raised, the tables are used to control a back trace of the
7341 subprogram invocation stack to locate the required exception
7342 handler. This method has considerably poorer performance for
7343 the propagation of exceptions, but there is no overhead for
7344 exception handlers if no exception is raised. Note that in this
7345 mode and in the context of mixed Ada and C/C++ programming,
7346 to propagate an exception through a C/C++ code, the C/C++ code
7347 must be compiled with the @option{-funwind-tables} GCC's
7348 option.
7349
7350 The following switches may be used to control which of the
7351 two exception handling methods is used.
7352
7353 @table @option
7354 @c !sort!
7355
7356 @item --RTS=sjlj
7357 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7358 This switch causes the setjmp/longjmp run-time (when available) to be used
7359 for exception handling. If the default
7360 mechanism for the target is zero cost exceptions, then
7361 this switch can be used to modify this default, and must be
7362 used for all units in the partition.
7363 This option is rarely used. One case in which it may be
7364 advantageous is if you have an application where exception
7365 raising is common and the overall performance of the
7366 application is improved by favoring exception propagation.
7367
7368 @item --RTS=zcx
7369 @cindex @option{--RTS=zcx} (@command{gnatmake})
7370 @cindex Zero Cost Exceptions
7371 This switch causes the zero cost approach to be used
7372 for exception handling. If this is the default mechanism for the
7373 target (see below), then this switch is unneeded. If the default
7374 mechanism for the target is setjmp/longjmp exceptions, then
7375 this switch can be used to modify this default, and must be
7376 used for all units in the partition.
7377 This option can only be used if the zero cost approach
7378 is available for the target in use, otherwise it will generate an error.
7379 @end table
7380
7381 @noindent
7382 The same option @option{--RTS} must be used both for @command{gcc}
7383 and @command{gnatbind}. Passing this option to @command{gnatmake}
7384 (@pxref{Switches for gnatmake}) will ensure the required consistency
7385 through the compilation and binding steps.
7386
7387 @node Units to Sources Mapping Files
7388 @subsection Units to Sources Mapping Files
7389
7390 @table @option
7391
7392 @item -gnatem^^=^@var{path}
7393 @cindex @option{-gnatem} (@command{gcc})
7394 A mapping file is a way to communicate to the compiler two mappings:
7395 from unit names to file names (without any directory information) and from
7396 file names to path names (with full directory information). These mappings
7397 are used by the compiler to short-circuit the path search.
7398
7399 The use of mapping files is not required for correct operation of the
7400 compiler, but mapping files can improve efficiency, particularly when
7401 sources are read over a slow network connection. In normal operation,
7402 you need not be concerned with the format or use of mapping files,
7403 and the @option{-gnatem} switch is not a switch that you would use
7404 explicitly. it is intended only for use by automatic tools such as
7405 @command{gnatmake} running under the project file facility. The
7406 description here of the format of mapping files is provided
7407 for completeness and for possible use by other tools.
7408
7409 A mapping file is a sequence of sets of three lines. In each set,
7410 the first line is the unit name, in lower case, with ``@code{%s}''
7411 appended for
7412 specs and ``@code{%b}'' appended for bodies; the second line is the
7413 file name; and the third line is the path name.
7414
7415 Example:
7416 @smallexample
7417    main%b
7418    main.2.ada
7419    /gnat/project1/sources/main.2.ada
7420 @end smallexample
7421
7422 When the switch @option{-gnatem} is specified, the compiler will create
7423 in memory the two mappings from the specified file. If there is any problem
7424 (nonexistent file, truncated file or duplicate entries), no mapping will
7425 be created.
7426
7427 Several @option{-gnatem} switches may be specified; however, only the last
7428 one on the command line will be taken into account.
7429
7430 When using a project file, @command{gnatmake} create a temporary mapping file
7431 and communicates it to the compiler using this switch.
7432
7433 @end table
7434
7435 @node Integrated Preprocessing
7436 @subsection Integrated Preprocessing
7437
7438 @noindent
7439 GNAT sources may be preprocessed immediately before compilation.
7440 In this case, the actual
7441 text of the source is not the text of the source file, but is derived from it
7442 through a process called preprocessing. Integrated preprocessing is specified
7443 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7444 indicates, through a text file, the preprocessing data to be used.
7445 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7446
7447 @noindent
7448 Note that when integrated preprocessing is used, the output from the
7449 preprocessor is not written to any external file. Instead it is passed
7450 internally to the compiler. If you need to preserve the result of
7451 preprocessing in a file, then you should use @command{gnatprep}
7452 to perform the desired preprocessing in stand-alone mode.
7453
7454 @noindent
7455 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7456 used when Integrated Preprocessing is used. The reason is that preprocessing
7457 with another Preprocessing Data file without changing the sources will
7458 not trigger recompilation without this switch.
7459
7460 @noindent
7461 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7462 always trigger recompilation for sources that are preprocessed,
7463 because @command{gnatmake} cannot compute the checksum of the source after
7464 preprocessing.
7465
7466 @noindent
7467 The actual preprocessing function is described in details in section
7468 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7469 preprocessing is triggered and parameterized.
7470
7471 @table @code
7472
7473 @item -gnatep=@var{file}
7474 @cindex @option{-gnatep} (@command{gcc})
7475 This switch indicates to the compiler the file name (without directory
7476 information) of the preprocessor data file to use. The preprocessor data file
7477 should be found in the source directories.
7478
7479 @noindent
7480 A preprocessing data file is a text file with significant lines indicating
7481 how should be preprocessed either a specific source or all sources not
7482 mentioned in other lines. A significant line is a nonempty, non-comment line.
7483 Comments are similar to Ada comments.
7484
7485 @noindent
7486 Each significant line starts with either a literal string or the character '*'.
7487 A literal string is the file name (without directory information) of the source
7488 to preprocess. A character '*' indicates the preprocessing for all the sources
7489 that are not specified explicitly on other lines (order of the lines is not
7490 significant). It is an error to have two lines with the same file name or two
7491 lines starting with the character '*'.
7492
7493 @noindent
7494 After the file name or the character '*', another optional literal string
7495 indicating the file name of the definition file to be used for preprocessing
7496 (@pxref{Form of Definitions File}). The definition files are found by the
7497 compiler in one of the source directories. In some cases, when compiling
7498 a source in a directory other than the current directory, if the definition
7499 file is in the current directory, it may be necessary to add the current
7500 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7501 the compiler would not find the definition file.
7502
7503 @noindent
7504 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7505 be found. Those ^switches^switches^ are:
7506
7507 @table @code
7508
7509 @item -b
7510 Causes both preprocessor lines and the lines deleted by
7511 preprocessing to be replaced by blank lines, preserving the line number.
7512 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7513 it cancels the effect of @option{-c}.
7514
7515 @item -c
7516 Causes both preprocessor lines and the lines deleted
7517 by preprocessing to be retained as comments marked
7518 with the special string ``@code{--! }''.
7519
7520 @item -Dsymbol=value
7521 Define or redefine a symbol, associated with value. A symbol is an Ada
7522 identifier, or an Ada reserved word, with the exception of @code{if},
7523 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7524 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7525 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7526 same name defined in a definition file.
7527
7528 @item -s
7529 Causes a sorted list of symbol names and values to be
7530 listed on the standard output file.
7531
7532 @item -u
7533 Causes undefined symbols to be treated as having the value @code{FALSE}
7534 in the context
7535 of a preprocessor test. In the absence of this option, an undefined symbol in
7536 a @code{#if} or @code{#elsif} test will be treated as an error.
7537
7538 @end table
7539
7540 @noindent
7541 Examples of valid lines in a preprocessor data file:
7542
7543 @smallexample
7544   "toto.adb"  "prep.def" -u
7545   --  preprocess "toto.adb", using definition file "prep.def",
7546   --  undefined symbol are False.
7547
7548   * -c -DVERSION=V101
7549   --  preprocess all other sources without a definition file;
7550   --  suppressed lined are commented; symbol VERSION has the value V101.
7551
7552   "titi.adb" "prep2.def" -s
7553   --  preprocess "titi.adb", using definition file "prep2.def";
7554   --  list all symbols with their values.
7555 @end smallexample
7556
7557 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7558 @cindex @option{-gnateD} (@command{gcc})
7559 Define or redefine a preprocessing symbol, associated with value. If no value
7560 is given on the command line, then the value of the symbol is @code{True}.
7561 A symbol is an identifier, following normal Ada (case-insensitive)
7562 rules for its syntax, and value is any sequence (including an empty sequence)
7563 of characters from the set (letters, digits, period, underline).
7564 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7565 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7566
7567 @noindent
7568 A symbol declared with this ^switch^switch^ on the command line replaces a
7569 symbol with the same name either in a definition file or specified with a
7570 ^switch^switch^ -D in the preprocessor data file.
7571
7572 @noindent
7573 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7574
7575 @item -gnateG
7576 When integrated preprocessing is performed and the preprocessor modifies
7577 the source text, write the result of this preprocessing into a file
7578 <source>^.prep^_prep^.
7579
7580 @end table
7581
7582 @node Code Generation Control
7583 @subsection Code Generation Control
7584
7585 @noindent
7586
7587 The GCC technology provides a wide range of target dependent
7588 @option{-m} switches for controlling
7589 details of code generation with respect to different versions of
7590 architectures. This includes variations in instruction sets (e.g.@:
7591 different members of the power pc family), and different requirements
7592 for optimal arrangement of instructions (e.g.@: different members of
7593 the x86 family). The list of available @option{-m} switches may be
7594 found in the GCC documentation.
7595
7596 Use of these @option{-m} switches may in some cases result in improved
7597 code performance.
7598
7599 The GNAT Pro technology is tested and qualified without any
7600 @option{-m} switches,
7601 so generally the most reliable approach is to avoid the use of these
7602 switches. However, we generally expect most of these switches to work
7603 successfully with GNAT Pro, and many customers have reported successful
7604 use of these options.
7605
7606 Our general advice is to avoid the use of @option{-m} switches unless
7607 special needs lead to requirements in this area. In particular,
7608 there is no point in using @option{-m} switches to improve performance
7609 unless you actually see a performance improvement.
7610
7611 @ifset vms
7612 @node Return Codes
7613 @subsection Return Codes
7614 @cindex Return Codes
7615 @cindex @option{/RETURN_CODES=VMS}
7616
7617 @noindent
7618 On VMS, GNAT compiled programs return POSIX-style codes by default,
7619 e.g.@: @option{/RETURN_CODES=POSIX}.
7620
7621 To enable VMS style return codes, use GNAT BIND and LINK with the option
7622 @option{/RETURN_CODES=VMS}. For example:
7623
7624 @smallexample
7625 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7626 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7627 @end smallexample
7628
7629 @noindent
7630 Programs built with /RETURN_CODES=VMS are suitable to be called in
7631 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7632 are suitable for spawning with appropriate GNAT RTL routines.
7633
7634 @end ifset
7635
7636 @node Search Paths and the Run-Time Library (RTL)
7637 @section Search Paths and the Run-Time Library (RTL)
7638
7639 @noindent
7640 With the GNAT source-based library system, the compiler must be able to
7641 find source files for units that are needed by the unit being compiled.
7642 Search paths are used to guide this process.
7643
7644 The compiler compiles one source file whose name must be given
7645 explicitly on the command line. In other words, no searching is done
7646 for this file. To find all other source files that are needed (the most
7647 common being the specs of units), the compiler examines the following
7648 directories, in the following order:
7649
7650 @enumerate
7651 @item
7652 The directory containing the source file of the main unit being compiled
7653 (the file name on the command line).
7654
7655 @item
7656 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7657 @command{gcc} command line, in the order given.
7658
7659 @item
7660 @findex ADA_PRJ_INCLUDE_FILE
7661 Each of the directories listed in the text file whose name is given
7662 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7663
7664 @noindent
7665 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7666 driver when project files are used. It should not normally be set
7667 by other means.
7668
7669 @item
7670 @findex ADA_INCLUDE_PATH
7671 Each of the directories listed in the value of the
7672 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7673 @ifclear vms
7674 Construct this value
7675 exactly as the @env{PATH} environment variable: a list of directory
7676 names separated by colons (semicolons when working with the NT version).
7677 @end ifclear
7678 @ifset vms
7679 Normally, define this value as a logical name containing a comma separated
7680 list of directory names.
7681
7682 This variable can also be defined by means of an environment string
7683 (an argument to the HP C exec* set of functions).
7684
7685 Logical Name:
7686 @smallexample
7687 DEFINE ANOTHER_PATH FOO:[BAG]
7688 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7689 @end smallexample
7690
7691 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7692 first, followed by the standard Ada
7693 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7694 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7695 (Text_IO, Sequential_IO, etc)
7696 instead of the standard Ada packages. Thus, in order to get the standard Ada
7697 packages by default, ADA_INCLUDE_PATH must be redefined.
7698 @end ifset
7699
7700 @item
7701 The content of the @file{ada_source_path} file which is part of the GNAT
7702 installation tree and is used to store standard libraries such as the
7703 GNAT Run Time Library (RTL) source files.
7704 @ifclear vms
7705 @ref{Installing a library}
7706 @end ifclear
7707 @end enumerate
7708
7709 @noindent
7710 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7711 inhibits the use of the directory
7712 containing the source file named in the command line. You can still
7713 have this directory on your search path, but in this case it must be
7714 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7715
7716 Specifying the switch @option{-nostdinc}
7717 inhibits the search of the default location for the GNAT Run Time
7718 Library (RTL) source files.
7719
7720 The compiler outputs its object files and ALI files in the current
7721 working directory.
7722 @ifclear vms
7723 Caution: The object file can be redirected with the @option{-o} switch;
7724 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7725 so the @file{ALI} file will not go to the right place. Therefore, you should
7726 avoid using the @option{-o} switch.
7727 @end ifclear
7728
7729 @findex System.IO
7730 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7731 children make up the GNAT RTL, together with the simple @code{System.IO}
7732 package used in the @code{"Hello World"} example. The sources for these units
7733 are needed by the compiler and are kept together in one directory. Not
7734 all of the bodies are needed, but all of the sources are kept together
7735 anyway. In a normal installation, you need not specify these directory
7736 names when compiling or binding. Either the environment variables or
7737 the built-in defaults cause these files to be found.
7738
7739 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7740 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7741 consisting of child units of @code{GNAT}. This is a collection of generally
7742 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7743 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7744
7745 Besides simplifying access to the RTL, a major use of search paths is
7746 in compiling sources from multiple directories. This can make
7747 development environments much more flexible.
7748
7749 @node Order of Compilation Issues
7750 @section Order of Compilation Issues
7751
7752 @noindent
7753 If, in our earlier example, there was a spec for the @code{hello}
7754 procedure, it would be contained in the file @file{hello.ads}; yet this
7755 file would not have to be explicitly compiled. This is the result of the
7756 model we chose to implement library management. Some of the consequences
7757 of this model are as follows:
7758
7759 @itemize @bullet
7760 @item
7761 There is no point in compiling specs (except for package
7762 specs with no bodies) because these are compiled as needed by clients. If
7763 you attempt a useless compilation, you will receive an error message.
7764 It is also useless to compile subunits because they are compiled as needed
7765 by the parent.
7766
7767 @item
7768 There are no order of compilation requirements: performing a
7769 compilation never obsoletes anything. The only way you can obsolete
7770 something and require recompilations is to modify one of the
7771 source files on which it depends.
7772
7773 @item
7774 There is no library as such, apart from the ALI files
7775 (@pxref{The Ada Library Information Files}, for information on the format
7776 of these files). For now we find it convenient to create separate ALI files,
7777 but eventually the information therein may be incorporated into the object
7778 file directly.
7779
7780 @item
7781 When you compile a unit, the source files for the specs of all units
7782 that it @code{with}'s, all its subunits, and the bodies of any generics it
7783 instantiates must be available (reachable by the search-paths mechanism
7784 described above), or you will receive a fatal error message.
7785 @end itemize
7786
7787 @node Examples
7788 @section Examples
7789
7790 @noindent
7791 The following are some typical Ada compilation command line examples:
7792
7793 @table @code
7794 @item $ gcc -c xyz.adb
7795 Compile body in file @file{xyz.adb} with all default options.
7796
7797 @ifclear vms
7798 @item $ gcc -c -O2 -gnata xyz-def.adb
7799 @end ifclear
7800 @ifset vms
7801 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7802 @end ifset
7803
7804 Compile the child unit package in file @file{xyz-def.adb} with extensive
7805 optimizations, and pragma @code{Assert}/@code{Debug} statements
7806 enabled.
7807
7808 @item $ gcc -c -gnatc abc-def.adb
7809 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7810 mode.
7811 @end table
7812
7813 @node Binding Using gnatbind
7814 @chapter Binding Using @code{gnatbind}
7815 @findex gnatbind
7816
7817 @menu
7818 * Running gnatbind::
7819 * Switches for gnatbind::
7820 * Command-Line Access::
7821 * Search Paths for gnatbind::
7822 * Examples of gnatbind Usage::
7823 @end menu
7824
7825 @noindent
7826 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7827 to bind compiled GNAT objects.
7828
7829 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7830 driver (see @ref{The GNAT Driver and Project Files}).
7831
7832 The @code{gnatbind} program performs four separate functions:
7833
7834 @enumerate
7835 @item
7836 Checks that a program is consistent, in accordance with the rules in
7837 Chapter 10 of the Ada Reference Manual. In particular, error
7838 messages are generated if a program uses inconsistent versions of a
7839 given unit.
7840
7841 @item
7842 Checks that an acceptable order of elaboration exists for the program
7843 and issues an error message if it cannot find an order of elaboration
7844 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7845
7846 @item
7847 Generates a main program incorporating the given elaboration order.
7848 This program is a small Ada package (body and spec) that
7849 must be subsequently compiled
7850 using the GNAT compiler. The necessary compilation step is usually
7851 performed automatically by @command{gnatlink}. The two most important
7852 functions of this program
7853 are to call the elaboration routines of units in an appropriate order
7854 and to call the main program.
7855
7856 @item
7857 Determines the set of object files required by the given main program.
7858 This information is output in the forms of comments in the generated program,
7859 to be read by the @command{gnatlink} utility used to link the Ada application.
7860 @end enumerate
7861
7862 @node Running gnatbind
7863 @section Running @code{gnatbind}
7864
7865 @noindent
7866 The form of the @code{gnatbind} command is
7867
7868 @smallexample
7869 $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7870 @end smallexample
7871
7872 @noindent
7873 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7874 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7875 package in two files whose names are
7876 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7877 For example, if given the
7878 parameter @file{hello.ali}, for a main program contained in file
7879 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7880 and @file{b~hello.adb}.
7881
7882 When doing consistency checking, the binder takes into consideration
7883 any source files it can locate. For example, if the binder determines
7884 that the given main program requires the package @code{Pack}, whose
7885 @file{.ALI}
7886 file is @file{pack.ali} and whose corresponding source spec file is
7887 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7888 (using the same search path conventions as previously described for the
7889 @command{gcc} command). If it can locate this source file, it checks that
7890 the time stamps
7891 or source checksums of the source and its references to in @file{ALI} files
7892 match. In other words, any @file{ALI} files that mentions this spec must have
7893 resulted from compiling this version of the source file (or in the case
7894 where the source checksums match, a version close enough that the
7895 difference does not matter).
7896
7897 @cindex Source files, use by binder
7898 The effect of this consistency checking, which includes source files, is
7899 that the binder ensures that the program is consistent with the latest
7900 version of the source files that can be located at bind time. Editing a
7901 source file without compiling files that depend on the source file cause
7902 error messages to be generated by the binder.
7903
7904 For example, suppose you have a main program @file{hello.adb} and a
7905 package @code{P}, from file @file{p.ads} and you perform the following
7906 steps:
7907
7908 @enumerate
7909 @item
7910 Enter @code{gcc -c hello.adb} to compile the main program.
7911
7912 @item
7913 Enter @code{gcc -c p.ads} to compile package @code{P}.
7914
7915 @item
7916 Edit file @file{p.ads}.
7917
7918 @item
7919 Enter @code{gnatbind hello}.
7920 @end enumerate
7921
7922 @noindent
7923 At this point, the file @file{p.ali} contains an out-of-date time stamp
7924 because the file @file{p.ads} has been edited. The attempt at binding
7925 fails, and the binder generates the following error messages:
7926
7927 @smallexample
7928 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7929 error: "p.ads" has been modified and must be recompiled
7930 @end smallexample
7931
7932 @noindent
7933 Now both files must be recompiled as indicated, and then the bind can
7934 succeed, generating a main program. You need not normally be concerned
7935 with the contents of this file, but for reference purposes a sample
7936 binder output file is given in @ref{Example of Binder Output File}.
7937
7938 In most normal usage, the default mode of @command{gnatbind} which is to
7939 generate the main package in Ada, as described in the previous section.
7940 In particular, this means that any Ada programmer can read and understand
7941 the generated main program. It can also be debugged just like any other
7942 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7943 @command{gnatbind} and @command{gnatlink}.
7944
7945 However for some purposes it may be convenient to generate the main
7946 program in C rather than Ada. This may for example be helpful when you
7947 are generating a mixed language program with the main program in C. The
7948 GNAT compiler itself is an example.
7949 The use of the @option{^-C^/BIND_FILE=C^} switch
7950 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7951 be generated in C (and compiled using the gnu C compiler).
7952
7953 @node Switches for gnatbind
7954 @section Switches for @command{gnatbind}
7955
7956 @noindent
7957 The following switches are available with @code{gnatbind}; details will
7958 be presented in subsequent sections.
7959
7960 @menu
7961 * Consistency-Checking Modes::
7962 * Binder Error Message Control::
7963 * Elaboration Control::
7964 * Output Control::
7965 * Binding with Non-Ada Main Programs::
7966 * Binding Programs with No Main Subprogram::
7967 @end menu
7968
7969 @table @option
7970 @c !sort!
7971
7972 @item --version
7973 @cindex @option{--version} @command{gnatbind}
7974 Display Copyright and version, then exit disregarding all other options.
7975
7976 @item --help
7977 @cindex @option{--help} @command{gnatbind}
7978 If @option{--version} was not used, display usage, then exit disregarding
7979 all other options.
7980
7981 @item -a
7982 @cindex @option{-a} @command{gnatbind}
7983 Indicates that, if supported by the platform, the adainit procedure should
7984 be treated as an initialisation routine by the linker (a constructor). This
7985 is intended to be used by the Project Manager to automatically initialize
7986 shared Stand-Alone Libraries.
7987
7988 @item ^-aO^/OBJECT_SEARCH^
7989 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7990 Specify directory to be searched for ALI files.
7991
7992 @item ^-aI^/SOURCE_SEARCH^
7993 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7994 Specify directory to be searched for source file.
7995
7996 @item ^-A^/BIND_FILE=ADA^
7997 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7998 Generate binder program in Ada (default)
7999
8000 @item ^-b^/REPORT_ERRORS=BRIEF^
8001 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8002 Generate brief messages to @file{stderr} even if verbose mode set.
8003
8004 @item ^-c^/NOOUTPUT^
8005 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8006 Check only, no generation of binder output file.
8007
8008 @item ^-C^/BIND_FILE=C^
8009 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
8010 Generate binder program in C
8011
8012 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8013 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8014 This switch can be used to change the default task stack size value
8015 to a specified size @var{nn}, which is expressed in bytes by default, or
8016 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8017 with @var{m}.
8018 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8019 in effect, to completing all task specs with
8020 @smallexample @c ada
8021    pragma Storage_Size (nn);
8022 @end smallexample
8023 When they do not already have such a pragma.
8024
8025 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8026 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8027 This switch can be used to change the default secondary stack size value
8028 to a specified size @var{nn}, which is expressed in bytes by default, or
8029 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8030 with @var{m}.
8031
8032 The secondary stack is used to deal with functions that return a variable
8033 sized result, for example a function returning an unconstrained
8034 String. There are two ways in which this secondary stack is allocated.
8035
8036 For most targets, the secondary stack is growing on demand and is allocated
8037 as a chain of blocks in the heap. The -D option is not very
8038 relevant. It only give some control over the size of the allocated
8039 blocks (whose size is the minimum of the default secondary stack size value,
8040 and the actual size needed for the current allocation request).
8041
8042 For certain targets, notably VxWorks 653,
8043 the secondary stack is allocated by carving off a fixed ratio chunk of the
8044 primary task stack. The -D option is used to define the
8045 size of the environment task's secondary stack.
8046
8047 @item ^-e^/ELABORATION_DEPENDENCIES^
8048 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8049 Output complete list of elaboration-order dependencies.
8050
8051 @item ^-E^/STORE_TRACEBACKS^
8052 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8053 Store tracebacks in exception occurrences when the target supports it.
8054 This is the default with the zero cost exception mechanism.
8055 @ignore
8056 @c The following may get moved to an appendix
8057 This option is currently supported on the following targets:
8058 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8059 @end ignore
8060 See also the packages @code{GNAT.Traceback} and
8061 @code{GNAT.Traceback.Symbolic} for more information.
8062 @ifclear vms
8063 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8064 @command{gcc} option.
8065 @end ifclear
8066
8067 @item ^-F^/FORCE_ELABS_FLAGS^
8068 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8069 Force the checks of elaboration flags. @command{gnatbind} does not normally
8070 generate checks of elaboration flags for the main executable, except when
8071 a Stand-Alone Library is used. However, there are cases when this cannot be
8072 detected by gnatbind. An example is importing an interface of a Stand-Alone
8073 Library through a pragma Import and only specifying through a linker switch
8074 this Stand-Alone Library. This switch is used to guarantee that elaboration
8075 flag checks are generated.
8076
8077 @item ^-h^/HELP^
8078 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8079 Output usage (help) information
8080
8081 @item ^-I^/SEARCH^
8082 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8083 Specify directory to be searched for source and ALI files.
8084
8085 @item ^-I-^/NOCURRENT_DIRECTORY^
8086 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8087 Do not look for sources in the current directory where @code{gnatbind} was
8088 invoked, and do not look for ALI files in the directory containing the
8089 ALI file named in the @code{gnatbind} command line.
8090
8091 @item ^-l^/ORDER_OF_ELABORATION^
8092 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8093 Output chosen elaboration order.
8094
8095 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8096 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8097 Bind the units for library building. In this case the adainit and
8098 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8099 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8100 ^@var{xxx}final^@var{XXX}FINAL^.
8101 Implies ^-n^/NOCOMPILE^.
8102 @ifclear vms
8103 (@xref{GNAT and Libraries}, for more details.)
8104 @end ifclear
8105 @ifset vms
8106 On OpenVMS, these init and final procedures are exported in uppercase
8107 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8108 the init procedure will be "TOTOINIT" and the exported name of the final
8109 procedure will be "TOTOFINAL".
8110 @end ifset
8111
8112 @item ^-Mxyz^/RENAME_MAIN=xyz^
8113 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8114 Rename generated main program from main to xyz. This option is
8115 supported on cross environments only.
8116
8117 @item ^-m^/ERROR_LIMIT=^@var{n}
8118 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8119 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8120 in the range 1..999999. The default value if no switch is
8121 given is 9999. If the number of warnings reaches this limit, then a
8122 message is output and further warnings are suppressed, the bind
8123 continues in this case. If the number of errors reaches this
8124 limit, then a message is output and the bind is abandoned.
8125 A value of zero means that no limit is enforced. The equal
8126 sign is optional.
8127
8128 @ifset unw
8129 Furthermore, under Windows, the sources pointed to by the libraries path
8130 set in the registry are not searched for.
8131 @end ifset
8132
8133 @item ^-n^/NOMAIN^
8134 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8135 No main program.
8136
8137 @item -nostdinc
8138 @cindex @option{-nostdinc} (@command{gnatbind})
8139 Do not look for sources in the system default directory.
8140
8141 @item -nostdlib
8142 @cindex @option{-nostdlib} (@command{gnatbind})
8143 Do not look for library files in the system default directory.
8144
8145 @item --RTS=@var{rts-path}
8146 @cindex @option{--RTS} (@code{gnatbind})
8147 Specifies the default location of the runtime library. Same meaning as the
8148 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8149
8150 @item ^-o ^/OUTPUT=^@var{file}
8151 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8152 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8153 Note that if this option is used, then linking must be done manually,
8154 gnatlink cannot be used.
8155
8156 @item ^-O^/OBJECT_LIST^
8157 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8158 Output object list.
8159
8160 @item ^-p^/PESSIMISTIC_ELABORATION^
8161 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8162 Pessimistic (worst-case) elaboration order
8163
8164 @item ^-R^-R^
8165 @cindex @option{^-R^-R^} (@command{gnatbind})
8166 Output closure source list.
8167
8168 @item ^-s^/READ_SOURCES=ALL^
8169 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8170 Require all source files to be present.
8171
8172 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8173 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8174 Specifies the value to be used when detecting uninitialized scalar
8175 objects with pragma Initialize_Scalars.
8176 The @var{xxx} ^string specified with the switch^option^ may be either
8177 @itemize @bullet
8178 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8179 @item ``@option{^lo^LOW^}'' for the lowest possible value
8180 @item ``@option{^hi^HIGH^}'' for the highest possible value
8181 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8182 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8183 @end itemize
8184
8185 In addition, you can specify @option{-Sev} to indicate that the value is
8186 to be set at run time. In this case, the program will look for an environment
8187 @cindex GNAT_INIT_SCALARS
8188 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8189 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8190 If no environment variable is found, or if it does not have a valid value,
8191 then the default is @option{in} (invalid values).
8192
8193 @ifclear vms
8194 @item -static
8195 @cindex @option{-static} (@code{gnatbind})
8196 Link against a static GNAT run time.
8197
8198 @item -shared
8199 @cindex @option{-shared} (@code{gnatbind})
8200 Link against a shared GNAT run time when available.
8201 @end ifclear
8202
8203 @item ^-t^/NOTIME_STAMP_CHECK^
8204 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8205 Tolerate time stamp and other consistency errors
8206
8207 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8208 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8209 Set the time slice value to @var{n} milliseconds. If the system supports
8210 the specification of a specific time slice value, then the indicated value
8211 is used. If the system does not support specific time slice values, but
8212 does support some general notion of round-robin scheduling, then any
8213 nonzero value will activate round-robin scheduling.
8214
8215 A value of zero is treated specially. It turns off time
8216 slicing, and in addition, indicates to the tasking run time that the
8217 semantics should match as closely as possible the Annex D
8218 requirements of the Ada RM, and in particular sets the default
8219 scheduling policy to @code{FIFO_Within_Priorities}.
8220
8221 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8222 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8223 Enable dynamic stack usage, with @var{n} results stored and displayed
8224 at program termination. A result is generated when a task
8225 terminates. Results that can't be stored are displayed on the fly, at
8226 task termination. This option is currently not supported on Itanium
8227 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8228
8229 @item ^-v^/REPORT_ERRORS=VERBOSE^
8230 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8231 Verbose mode. Write error messages, header, summary output to
8232 @file{stdout}.
8233
8234 @ifclear vms
8235 @item -w@var{x}
8236 @cindex @option{-w} (@code{gnatbind})
8237 Warning mode (@var{x}=s/e for suppress/treat as error)
8238 @end ifclear
8239
8240 @ifset vms
8241 @item /WARNINGS=NORMAL
8242 @cindex @option{/WARNINGS} (@code{gnatbind})
8243 Normal warnings mode. Warnings are issued but ignored
8244
8245 @item /WARNINGS=SUPPRESS
8246 @cindex @option{/WARNINGS} (@code{gnatbind})
8247 All warning messages are suppressed
8248
8249 @item /WARNINGS=ERROR
8250 @cindex @option{/WARNINGS} (@code{gnatbind})
8251 Warning messages are treated as fatal errors
8252 @end ifset
8253
8254 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8255 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8256 Override default wide character encoding for standard Text_IO files.
8257
8258 @item ^-x^/READ_SOURCES=NONE^
8259 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8260 Exclude source files (check object consistency only).
8261
8262 @ifset vms
8263 @item /READ_SOURCES=AVAILABLE
8264 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8265 Default mode, in which sources are checked for consistency only if
8266 they are available.
8267 @end ifset
8268
8269 @item ^-y^/ENABLE_LEAP_SECONDS^
8270 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8271 Enable leap seconds support in @code{Ada.Calendar} and its children.
8272
8273 @item ^-z^/ZERO_MAIN^
8274 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8275 No main subprogram.
8276 @end table
8277
8278 @ifclear vms
8279 @noindent
8280 You may obtain this listing of switches by running @code{gnatbind} with
8281 no arguments.
8282 @end ifclear
8283
8284 @node Consistency-Checking Modes
8285 @subsection Consistency-Checking Modes
8286
8287 @noindent
8288 As described earlier, by default @code{gnatbind} checks
8289 that object files are consistent with one another and are consistent
8290 with any source files it can locate. The following switches control binder
8291 access to sources.
8292
8293 @table @option
8294 @c !sort!
8295 @item ^-s^/READ_SOURCES=ALL^
8296 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8297 Require source files to be present. In this mode, the binder must be
8298 able to locate all source files that are referenced, in order to check
8299 their consistency. In normal mode, if a source file cannot be located it
8300 is simply ignored. If you specify this switch, a missing source
8301 file is an error.
8302
8303 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8304 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8305 Override default wide character encoding for standard Text_IO files.
8306 Normally the default wide character encoding method used for standard
8307 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8308 the main source input (see description of switch
8309 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8310 use of this switch for the binder (which has the same set of
8311 possible arguments) overrides this default as specified.
8312
8313 @item ^-x^/READ_SOURCES=NONE^
8314 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8315 Exclude source files. In this mode, the binder only checks that ALI
8316 files are consistent with one another. Source files are not accessed.
8317 The binder runs faster in this mode, and there is still a guarantee that
8318 the resulting program is self-consistent.
8319 If a source file has been edited since it was last compiled, and you
8320 specify this switch, the binder will not detect that the object
8321 file is out of date with respect to the source file. Note that this is the
8322 mode that is automatically used by @command{gnatmake} because in this
8323 case the checking against sources has already been performed by
8324 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8325
8326 @ifset vms
8327 @item /READ_SOURCES=AVAILABLE
8328 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8329 This is the default mode in which source files are checked if they are
8330 available, and ignored if they are not available.
8331 @end ifset
8332 @end table
8333
8334 @node Binder Error Message Control
8335 @subsection Binder Error Message Control
8336
8337 @noindent
8338 The following switches provide control over the generation of error
8339 messages from the binder:
8340
8341 @table @option
8342 @c !sort!
8343 @item ^-v^/REPORT_ERRORS=VERBOSE^
8344 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8345 Verbose mode. In the normal mode, brief error messages are generated to
8346 @file{stderr}. If this switch is present, a header is written
8347 to @file{stdout} and any error messages are directed to @file{stdout}.
8348 All that is written to @file{stderr} is a brief summary message.
8349
8350 @item ^-b^/REPORT_ERRORS=BRIEF^
8351 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8352 Generate brief error messages to @file{stderr} even if verbose mode is
8353 specified. This is relevant only when used with the
8354 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8355
8356 @ifclear vms
8357 @item -m@var{n}
8358 @cindex @option{-m} (@code{gnatbind})
8359 Limits the number of error messages to @var{n}, a decimal integer in the
8360 range 1-999. The binder terminates immediately if this limit is reached.
8361
8362 @item -M@var{xxx}
8363 @cindex @option{-M} (@code{gnatbind})
8364 Renames the generated main program from @code{main} to @code{xxx}.
8365 This is useful in the case of some cross-building environments, where
8366 the actual main program is separate from the one generated
8367 by @code{gnatbind}.
8368 @end ifclear
8369
8370 @item ^-ws^/WARNINGS=SUPPRESS^
8371 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8372 @cindex Warnings
8373 Suppress all warning messages.
8374
8375 @item ^-we^/WARNINGS=ERROR^
8376 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8377 Treat any warning messages as fatal errors.
8378
8379 @ifset vms
8380 @item /WARNINGS=NORMAL
8381 Standard mode with warnings generated, but warnings do not get treated
8382 as errors.
8383 @end ifset
8384
8385 @item ^-t^/NOTIME_STAMP_CHECK^
8386 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8387 @cindex Time stamp checks, in binder
8388 @cindex Binder consistency checks
8389 @cindex Consistency checks, in binder
8390 The binder performs a number of consistency checks including:
8391
8392 @itemize @bullet
8393 @item
8394 Check that time stamps of a given source unit are consistent
8395 @item
8396 Check that checksums of a given source unit are consistent
8397 @item
8398 Check that consistent versions of @code{GNAT} were used for compilation
8399 @item
8400 Check consistency of configuration pragmas as required
8401 @end itemize
8402
8403 @noindent
8404 Normally failure of such checks, in accordance with the consistency
8405 requirements of the Ada Reference Manual, causes error messages to be
8406 generated which abort the binder and prevent the output of a binder
8407 file and subsequent link to obtain an executable.
8408
8409 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8410 into warnings, so that
8411 binding and linking can continue to completion even in the presence of such
8412 errors. The result may be a failed link (due to missing symbols), or a
8413 non-functional executable which has undefined semantics.
8414 @emph{This means that
8415 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8416 with extreme care.}
8417 @end table
8418
8419 @node Elaboration Control
8420 @subsection Elaboration Control
8421
8422 @noindent
8423 The following switches provide additional control over the elaboration
8424 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8425
8426 @table @option
8427 @item ^-p^/PESSIMISTIC_ELABORATION^
8428 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8429 Normally the binder attempts to choose an elaboration order that is
8430 likely to minimize the likelihood of an elaboration order error resulting
8431 in raising a @code{Program_Error} exception. This switch reverses the
8432 action of the binder, and requests that it deliberately choose an order
8433 that is likely to maximize the likelihood of an elaboration error.
8434 This is useful in ensuring portability and avoiding dependence on
8435 accidental fortuitous elaboration ordering.
8436
8437 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8438 switch if dynamic
8439 elaboration checking is used (@option{-gnatE} switch used for compilation).
8440 This is because in the default static elaboration mode, all necessary
8441 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8442 These implicit pragmas are still respected by the binder in
8443 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8444 safe elaboration order is assured.
8445 @end table
8446
8447 @node Output Control
8448 @subsection Output Control
8449
8450 @noindent
8451 The following switches allow additional control over the output
8452 generated by the binder.
8453
8454 @table @option
8455 @c !sort!
8456
8457 @item ^-A^/BIND_FILE=ADA^
8458 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
8459 Generate binder program in Ada (default). The binder program is named
8460 @file{b~@var{mainprog}.adb} by default. This can be changed with
8461 @option{^-o^/OUTPUT^} @code{gnatbind} option.
8462
8463 @item ^-c^/NOOUTPUT^
8464 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8465 Check only. Do not generate the binder output file. In this mode the
8466 binder performs all error checks but does not generate an output file.
8467
8468 @item ^-C^/BIND_FILE=C^
8469 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
8470 Generate binder program in C. The binder program is named
8471 @file{b_@var{mainprog}.c}.
8472 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
8473 option.
8474
8475 @item ^-e^/ELABORATION_DEPENDENCIES^
8476 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8477 Output complete list of elaboration-order dependencies, showing the
8478 reason for each dependency. This output can be rather extensive but may
8479 be useful in diagnosing problems with elaboration order. The output is
8480 written to @file{stdout}.
8481
8482 @item ^-h^/HELP^
8483 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8484 Output usage information. The output is written to @file{stdout}.
8485
8486 @item ^-K^/LINKER_OPTION_LIST^
8487 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8488 Output linker options to @file{stdout}. Includes library search paths,
8489 contents of pragmas Ident and Linker_Options, and libraries added
8490 by @code{gnatbind}.
8491
8492 @item ^-l^/ORDER_OF_ELABORATION^
8493 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8494 Output chosen elaboration order. The output is written to @file{stdout}.
8495
8496 @item ^-O^/OBJECT_LIST^
8497 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8498 Output full names of all the object files that must be linked to provide
8499 the Ada component of the program. The output is written to @file{stdout}.
8500 This list includes the files explicitly supplied and referenced by the user
8501 as well as implicitly referenced run-time unit files. The latter are
8502 omitted if the corresponding units reside in shared libraries. The
8503 directory names for the run-time units depend on the system configuration.
8504
8505 @item ^-o ^/OUTPUT=^@var{file}
8506 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8507 Set name of output file to @var{file} instead of the normal
8508 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8509 binder generated body filename. In C mode you would normally give
8510 @var{file} an extension of @file{.c} because it will be a C source program.
8511 Note that if this option is used, then linking must be done manually.
8512 It is not possible to use gnatlink in this case, since it cannot locate
8513 the binder file.
8514
8515 @item ^-r^/RESTRICTION_LIST^
8516 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8517 Generate list of @code{pragma Restrictions} that could be applied to
8518 the current unit. This is useful for code audit purposes, and also may
8519 be used to improve code generation in some cases.
8520
8521 @end table
8522
8523 @node Binding with Non-Ada Main Programs
8524 @subsection Binding with Non-Ada Main Programs
8525
8526 @noindent
8527 In our description so far we have assumed that the main
8528 program is in Ada, and that the task of the binder is to generate a
8529 corresponding function @code{main} that invokes this Ada main
8530 program. GNAT also supports the building of executable programs where
8531 the main program is not in Ada, but some of the called routines are
8532 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8533 The following switch is used in this situation:
8534
8535 @table @option
8536 @item ^-n^/NOMAIN^
8537 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8538 No main program. The main program is not in Ada.
8539 @end table
8540
8541 @noindent
8542 In this case, most of the functions of the binder are still required,
8543 but instead of generating a main program, the binder generates a file
8544 containing the following callable routines:
8545
8546 @table @code
8547 @item adainit
8548 @findex adainit
8549 You must call this routine to initialize the Ada part of the program by
8550 calling the necessary elaboration routines. A call to @code{adainit} is
8551 required before the first call to an Ada subprogram.
8552
8553 Note that it is assumed that the basic execution environment must be setup
8554 to be appropriate for Ada execution at the point where the first Ada
8555 subprogram is called. In particular, if the Ada code will do any
8556 floating-point operations, then the FPU must be setup in an appropriate
8557 manner. For the case of the x86, for example, full precision mode is
8558 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8559 that the FPU is in the right state.
8560
8561 @item adafinal
8562 @findex adafinal
8563 You must call this routine to perform any library-level finalization
8564 required by the Ada subprograms. A call to @code{adafinal} is required
8565 after the last call to an Ada subprogram, and before the program
8566 terminates.
8567 @end table
8568
8569 @noindent
8570 If the @option{^-n^/NOMAIN^} switch
8571 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8572 @cindex Binder, multiple input files
8573 is given, more than one ALI file may appear on
8574 the command line for @code{gnatbind}. The normal @dfn{closure}
8575 calculation is performed for each of the specified units. Calculating
8576 the closure means finding out the set of units involved by tracing
8577 @code{with} references. The reason it is necessary to be able to
8578 specify more than one ALI file is that a given program may invoke two or
8579 more quite separate groups of Ada units.
8580
8581 The binder takes the name of its output file from the last specified ALI
8582 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8583 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8584 The output is an Ada unit in source form that can
8585 be compiled with GNAT unless the -C switch is used in which case the
8586 output is a C source file, which must be compiled using the C compiler.
8587 This compilation occurs automatically as part of the @command{gnatlink}
8588 processing.
8589
8590 Currently the GNAT run time requires a FPU using 80 bits mode
8591 precision. Under targets where this is not the default it is required to
8592 call GNAT.Float_Control.Reset before using floating point numbers (this
8593 include float computation, float input and output) in the Ada code. A
8594 side effect is that this could be the wrong mode for the foreign code
8595 where floating point computation could be broken after this call.
8596
8597 @node Binding Programs with No Main Subprogram
8598 @subsection Binding Programs with No Main Subprogram
8599
8600 @noindent
8601 It is possible to have an Ada program which does not have a main
8602 subprogram. This program will call the elaboration routines of all the
8603 packages, then the finalization routines.
8604
8605 The following switch is used to bind programs organized in this manner:
8606
8607 @table @option
8608 @item ^-z^/ZERO_MAIN^
8609 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8610 Normally the binder checks that the unit name given on the command line
8611 corresponds to a suitable main subprogram. When this switch is used,
8612 a list of ALI files can be given, and the execution of the program
8613 consists of elaboration of these units in an appropriate order. Note
8614 that the default wide character encoding method for standard Text_IO
8615 files is always set to Brackets if this switch is set (you can use
8616 the binder switch
8617 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8618 @end table
8619
8620 @node Command-Line Access
8621 @section Command-Line Access
8622
8623 @noindent
8624 The package @code{Ada.Command_Line} provides access to the command-line
8625 arguments and program name. In order for this interface to operate
8626 correctly, the two variables
8627
8628 @smallexample
8629 @group
8630 int gnat_argc;
8631 char **gnat_argv;
8632 @end group
8633 @end smallexample
8634
8635 @noindent
8636 @findex gnat_argv
8637 @findex gnat_argc
8638 are declared in one of the GNAT library routines. These variables must
8639 be set from the actual @code{argc} and @code{argv} values passed to the
8640 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8641 generates the C main program to automatically set these variables.
8642 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8643 set these variables. If they are not set, the procedures in
8644 @code{Ada.Command_Line} will not be available, and any attempt to use
8645 them will raise @code{Constraint_Error}. If command line access is
8646 required, your main program must set @code{gnat_argc} and
8647 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8648 it.
8649
8650 @node Search Paths for gnatbind
8651 @section Search Paths for @code{gnatbind}
8652
8653 @noindent
8654 The binder takes the name of an ALI file as its argument and needs to
8655 locate source files as well as other ALI files to verify object consistency.
8656
8657 For source files, it follows exactly the same search rules as @command{gcc}
8658 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8659 directories searched are:
8660
8661 @enumerate
8662 @item
8663 The directory containing the ALI file named in the command line, unless
8664 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8665
8666 @item
8667 All directories specified by @option{^-I^/SEARCH^}
8668 switches on the @code{gnatbind}
8669 command line, in the order given.
8670
8671 @item
8672 @findex ADA_PRJ_OBJECTS_FILE
8673 Each of the directories listed in the text file whose name is given
8674 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8675
8676 @noindent
8677 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8678 driver when project files are used. It should not normally be set
8679 by other means.
8680
8681 @item
8682 @findex ADA_OBJECTS_PATH
8683 Each of the directories listed in the value of the
8684 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8685 @ifset unw
8686 Construct this value
8687 exactly as the @env{PATH} environment variable: a list of directory
8688 names separated by colons (semicolons when working with the NT version
8689 of GNAT).
8690 @end ifset
8691 @ifset vms
8692 Normally, define this value as a logical name containing a comma separated
8693 list of directory names.
8694
8695 This variable can also be defined by means of an environment string
8696 (an argument to the HP C exec* set of functions).
8697
8698 Logical Name:
8699 @smallexample
8700 DEFINE ANOTHER_PATH FOO:[BAG]
8701 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8702 @end smallexample
8703
8704 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8705 first, followed by the standard Ada
8706 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8707 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8708 (Text_IO, Sequential_IO, etc)
8709 instead of the standard Ada packages. Thus, in order to get the standard Ada
8710 packages by default, ADA_OBJECTS_PATH must be redefined.
8711 @end ifset
8712
8713 @item
8714 The content of the @file{ada_object_path} file which is part of the GNAT
8715 installation tree and is used to store standard libraries such as the
8716 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8717 specified.
8718 @ifclear vms
8719 @ref{Installing a library}
8720 @end ifclear
8721 @end enumerate
8722
8723 @noindent
8724 In the binder the switch @option{^-I^/SEARCH^}
8725 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8726 is used to specify both source and
8727 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8728 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8729 instead if you want to specify
8730 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8731 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8732 if you want to specify library paths
8733 only. This means that for the binder
8734 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8735 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8736 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8737 The binder generates the bind file (a C language source file) in the
8738 current working directory.
8739
8740 @findex Ada
8741 @findex System
8742 @findex Interfaces
8743 @findex GNAT
8744 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8745 children make up the GNAT Run-Time Library, together with the package
8746 GNAT and its children, which contain a set of useful additional
8747 library functions provided by GNAT. The sources for these units are
8748 needed by the compiler and are kept together in one directory. The ALI
8749 files and object files generated by compiling the RTL are needed by the
8750 binder and the linker and are kept together in one directory, typically
8751 different from the directory containing the sources. In a normal
8752 installation, you need not specify these directory names when compiling
8753 or binding. Either the environment variables or the built-in defaults
8754 cause these files to be found.
8755
8756 Besides simplifying access to the RTL, a major use of search paths is
8757 in compiling sources from multiple directories. This can make
8758 development environments much more flexible.
8759
8760 @node Examples of gnatbind Usage
8761 @section Examples of @code{gnatbind} Usage
8762
8763 @noindent
8764 This section contains a number of examples of using the GNAT binding
8765 utility @code{gnatbind}.
8766
8767 @table @code
8768 @item gnatbind hello
8769 The main program @code{Hello} (source program in @file{hello.adb}) is
8770 bound using the standard switch settings. The generated main program is
8771 @file{b~hello.adb}. This is the normal, default use of the binder.
8772
8773 @ifclear vms
8774 @item gnatbind hello -o mainprog.adb
8775 @end ifclear
8776 @ifset vms
8777 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8778 @end ifset
8779 The main program @code{Hello} (source program in @file{hello.adb}) is
8780 bound using the standard switch settings. The generated main program is
8781 @file{mainprog.adb} with the associated spec in
8782 @file{mainprog.ads}. Note that you must specify the body here not the
8783 spec, in the case where the output is in Ada. Note that if this option
8784 is used, then linking must be done manually, since gnatlink will not
8785 be able to find the generated file.
8786
8787 @ifclear vms
8788 @item gnatbind main -C -o mainprog.c -x
8789 @end ifclear
8790 @ifset vms
8791 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8792 @end ifset
8793 The main program @code{Main} (source program in
8794 @file{main.adb}) is bound, excluding source files from the
8795 consistency checking, generating
8796 the file @file{mainprog.c}.
8797
8798 @ifclear vms
8799 @item gnatbind -x main_program -C -o mainprog.c
8800 This command is exactly the same as the previous example. Switches may
8801 appear anywhere in the command line, and single letter switches may be
8802 combined into a single switch.
8803 @end ifclear
8804
8805 @ifclear vms
8806 @item gnatbind -n math dbase -C -o ada-control.c
8807 @end ifclear
8808 @ifset vms
8809 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8810 @end ifset
8811 The main program is in a language other than Ada, but calls to
8812 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8813 to @code{gnatbind} generates the file @file{ada-control.c} containing
8814 the @code{adainit} and @code{adafinal} routines to be called before and
8815 after accessing the Ada units.
8816 @end table
8817
8818 @c ------------------------------------
8819 @node Linking Using gnatlink
8820 @chapter Linking Using @command{gnatlink}
8821 @c ------------------------------------
8822 @findex gnatlink
8823
8824 @noindent
8825 This chapter discusses @command{gnatlink}, a tool that links
8826 an Ada program and builds an executable file. This utility
8827 invokes the system linker ^(via the @command{gcc} command)^^
8828 with a correct list of object files and library references.
8829 @command{gnatlink} automatically determines the list of files and
8830 references for the Ada part of a program. It uses the binder file
8831 generated by the @command{gnatbind} to determine this list.
8832
8833 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8834 driver (see @ref{The GNAT Driver and Project Files}).
8835
8836 @menu
8837 * Running gnatlink::
8838 * Switches for gnatlink::
8839 @end menu
8840
8841 @node Running gnatlink
8842 @section Running @command{gnatlink}
8843
8844 @noindent
8845 The form of the @command{gnatlink} command is
8846
8847 @smallexample
8848 $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8849            @ovar{non-Ada objects} @ovar{linker options}
8850 @end smallexample
8851
8852 @noindent
8853 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8854 non-Ada objects
8855 or linker options) may be in any order, provided that no non-Ada object may
8856 be mistaken for a main @file{ALI} file.
8857 Any file name @file{F} without the @file{.ali}
8858 extension will be taken as the main @file{ALI} file if a file exists
8859 whose name is the concatenation of @file{F} and @file{.ali}.
8860
8861 @noindent
8862 @file{@var{mainprog}.ali} references the ALI file of the main program.
8863 The @file{.ali} extension of this file can be omitted. From this
8864 reference, @command{gnatlink} locates the corresponding binder file
8865 @file{b~@var{mainprog}.adb} and, using the information in this file along
8866 with the list of non-Ada objects and linker options, constructs a
8867 linker command file to create the executable.
8868
8869 The arguments other than the @command{gnatlink} switches and the main
8870 @file{ALI} file are passed to the linker uninterpreted.
8871 They typically include the names of
8872 object files for units written in other languages than Ada and any library
8873 references required to resolve references in any of these foreign language
8874 units, or in @code{Import} pragmas in any Ada units.
8875
8876 @var{linker options} is an optional list of linker specific
8877 switches.
8878 The default linker called by gnatlink is @command{gcc} which in
8879 turn calls the appropriate system linker.
8880 Standard options for the linker such as @option{-lmy_lib} or
8881 @option{-Ldir} can be added as is.
8882 For options that are not recognized by
8883 @command{gcc} as linker options, use the @command{gcc} switches
8884 @option{-Xlinker} or @option{-Wl,}.
8885 Refer to the GCC documentation for
8886 details. Here is an example showing how to generate a linker map:
8887
8888 @smallexample
8889 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8890 @end smallexample
8891
8892 Using @var{linker options} it is possible to set the program stack and
8893 heap size.
8894 @ifset unw
8895 See @ref{Setting Stack Size from gnatlink} and
8896 @ref{Setting Heap Size from gnatlink}.
8897 @end ifset
8898
8899 @command{gnatlink} determines the list of objects required by the Ada
8900 program and prepends them to the list of objects passed to the linker.
8901 @command{gnatlink} also gathers any arguments set by the use of
8902 @code{pragma Linker_Options} and adds them to the list of arguments
8903 presented to the linker.
8904
8905 @ifset vms
8906 @command{gnatlink} accepts the following types of extra files on the command
8907 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8908 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8909 handled according to their extension.
8910 @end ifset
8911
8912 @node Switches for gnatlink
8913 @section Switches for @command{gnatlink}
8914
8915 @noindent
8916 The following switches are available with the @command{gnatlink} utility:
8917
8918 @table @option
8919 @c !sort!
8920
8921 @item --version
8922 @cindex @option{--version} @command{gnatlink}
8923 Display Copyright and version, then exit disregarding all other options.
8924
8925 @item --help
8926 @cindex @option{--help} @command{gnatlink}
8927 If @option{--version} was not used, display usage, then exit disregarding
8928 all other options.
8929
8930 @item ^-A^/BIND_FILE=ADA^
8931 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8932 The binder has generated code in Ada. This is the default.
8933
8934 @item ^-C^/BIND_FILE=C^
8935 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8936 If instead of generating a file in Ada, the binder has generated one in
8937 C, then the linker needs to know about it. Use this switch to signal
8938 to @command{gnatlink} that the binder has generated C code rather than
8939 Ada code.
8940
8941 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8942 @cindex Command line length
8943 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8944 On some targets, the command line length is limited, and @command{gnatlink}
8945 will generate a separate file for the linker if the list of object files
8946 is too long.
8947 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8948 to be generated even if
8949 the limit is not exceeded. This is useful in some cases to deal with
8950 special situations where the command line length is exceeded.
8951
8952 @item ^-g^/DEBUG^
8953 @cindex Debugging information, including
8954 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8955 The option to include debugging information causes the Ada bind file (in
8956 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8957 @option{^-g^/DEBUG^}.
8958 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8959 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8960 Without @option{^-g^/DEBUG^}, the binder removes these files by
8961 default. The same procedure apply if a C bind file was generated using
8962 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8963 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8964
8965 @item ^-n^/NOCOMPILE^
8966 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8967 Do not compile the file generated by the binder. This may be used when
8968 a link is rerun with different options, but there is no need to recompile
8969 the binder file.
8970
8971 @item ^-v^/VERBOSE^
8972 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8973 Causes additional information to be output, including a full list of the
8974 included object files. This switch option is most useful when you want
8975 to see what set of object files are being used in the link step.
8976
8977 @item ^-v -v^/VERBOSE/VERBOSE^
8978 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8979 Very verbose mode. Requests that the compiler operate in verbose mode when
8980 it compiles the binder file, and that the system linker run in verbose mode.
8981
8982 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8983 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8984 @var{exec-name} specifies an alternate name for the generated
8985 executable program. If this switch is omitted, the executable has the same
8986 name as the main unit. For example, @code{gnatlink try.ali} creates
8987 an executable called @file{^try^TRY.EXE^}.
8988
8989 @ifclear vms
8990 @item -b @var{target}
8991 @cindex @option{-b} (@command{gnatlink})
8992 Compile your program to run on @var{target}, which is the name of a
8993 system configuration. You must have a GNAT cross-compiler built if
8994 @var{target} is not the same as your host system.
8995
8996 @item -B@var{dir}
8997 @cindex @option{-B} (@command{gnatlink})
8998 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8999 from @var{dir} instead of the default location. Only use this switch
9000 when multiple versions of the GNAT compiler are available.
9001 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9002 for further details. You would normally use the @option{-b} or
9003 @option{-V} switch instead.
9004
9005 @item --GCC=@var{compiler_name}
9006 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9007 Program used for compiling the binder file. The default is
9008 @command{gcc}. You need to use quotes around @var{compiler_name} if
9009 @code{compiler_name} contains spaces or other separator characters.
9010 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9011 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9012 inserted after your command name. Thus in the above example the compiler
9013 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9014 A limitation of this syntax is that the name and path name of the executable
9015 itself must not include any embedded spaces. If the compiler executable is
9016 different from the default one (gcc or <prefix>-gcc), then the back-end
9017 switches in the ALI file are not used to compile the binder generated source.
9018 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9019 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9020 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9021 is taken into account. However, all the additional switches are also taken
9022 into account. Thus,
9023 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9024 @option{--GCC="bar -x -y -z -t"}.
9025
9026 @item --LINK=@var{name}
9027 @cindex @option{--LINK=} (@command{gnatlink})
9028 @var{name} is the name of the linker to be invoked. This is especially
9029 useful in mixed language programs since languages such as C++ require
9030 their own linker to be used. When this switch is omitted, the default
9031 name for the linker is @command{gcc}. When this switch is used, the
9032 specified linker is called instead of @command{gcc} with exactly the same
9033 parameters that would have been passed to @command{gcc} so if the desired
9034 linker requires different parameters it is necessary to use a wrapper
9035 script that massages the parameters before invoking the real linker. It
9036 may be useful to control the exact invocation by using the verbose
9037 switch.
9038
9039 @end ifclear
9040
9041 @ifset vms
9042 @item /DEBUG=TRACEBACK
9043 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9044 This qualifier causes sufficient information to be included in the
9045 executable file to allow a traceback, but does not include the full
9046 symbol information needed by the debugger.
9047
9048 @item /IDENTIFICATION="<string>"
9049 @code{"<string>"} specifies the string to be stored in the image file
9050 identification field in the image header.
9051 It overrides any pragma @code{Ident} specified string.
9052
9053 @item /NOINHIBIT-EXEC
9054 Generate the executable file even if there are linker warnings.
9055
9056 @item /NOSTART_FILES
9057 Don't link in the object file containing the ``main'' transfer address.
9058 Used when linking with a foreign language main program compiled with an
9059 HP compiler.
9060
9061 @item /STATIC
9062 Prefer linking with object libraries over sharable images, even without
9063 /DEBUG.
9064 @end ifset
9065
9066 @end table
9067
9068 @node The GNAT Make Program gnatmake
9069 @chapter The GNAT Make Program @command{gnatmake}
9070 @findex gnatmake
9071
9072 @menu
9073 * Running gnatmake::
9074 * Switches for gnatmake::
9075 * Mode Switches for gnatmake::
9076 * Notes on the Command Line::
9077 * How gnatmake Works::
9078 * Examples of gnatmake Usage::
9079 @end menu
9080 @noindent
9081 A typical development cycle when working on an Ada program consists of
9082 the following steps:
9083
9084 @enumerate
9085 @item
9086 Edit some sources to fix bugs.
9087
9088 @item
9089 Add enhancements.
9090
9091 @item
9092 Compile all sources affected.
9093
9094 @item
9095 Rebind and relink.
9096
9097 @item
9098 Test.
9099 @end enumerate
9100
9101 @noindent
9102 The third step can be tricky, because not only do the modified files
9103 @cindex Dependency rules
9104 have to be compiled, but any files depending on these files must also be
9105 recompiled. The dependency rules in Ada can be quite complex, especially
9106 in the presence of overloading, @code{use} clauses, generics and inlined
9107 subprograms.
9108
9109 @command{gnatmake} automatically takes care of the third and fourth steps
9110 of this process. It determines which sources need to be compiled,
9111 compiles them, and binds and links the resulting object files.
9112
9113 Unlike some other Ada make programs, the dependencies are always
9114 accurately recomputed from the new sources. The source based approach of
9115 the GNAT compilation model makes this possible. This means that if
9116 changes to the source program cause corresponding changes in
9117 dependencies, they will always be tracked exactly correctly by
9118 @command{gnatmake}.
9119
9120 @node Running gnatmake
9121 @section Running @command{gnatmake}
9122
9123 @noindent
9124 The usual form of the @command{gnatmake} command is
9125
9126 @smallexample
9127 $ gnatmake @ovar{switches} @var{file_name}
9128       @ovar{file_names} @ovar{mode_switches}
9129 @end smallexample
9130
9131 @noindent
9132 The only required argument is one @var{file_name}, which specifies
9133 a compilation unit that is a main program. Several @var{file_names} can be
9134 specified: this will result in several executables being built.
9135 If @code{switches} are present, they can be placed before the first
9136 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9137 If @var{mode_switches} are present, they must always be placed after
9138 the last @var{file_name} and all @code{switches}.
9139
9140 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9141 extension may be omitted from the @var{file_name} arguments. However, if
9142 you are using non-standard extensions, then it is required that the
9143 extension be given. A relative or absolute directory path can be
9144 specified in a @var{file_name}, in which case, the input source file will
9145 be searched for in the specified directory only. Otherwise, the input
9146 source file will first be searched in the directory where
9147 @command{gnatmake} was invoked and if it is not found, it will be search on
9148 the source path of the compiler as described in
9149 @ref{Search Paths and the Run-Time Library (RTL)}.
9150
9151 All @command{gnatmake} output (except when you specify
9152 @option{^-M^/DEPENDENCIES_LIST^}) is to
9153 @file{stderr}. The output produced by the
9154 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9155 @file{stdout}.
9156
9157 @node Switches for gnatmake
9158 @section Switches for @command{gnatmake}
9159
9160 @noindent
9161 You may specify any of the following switches to @command{gnatmake}:
9162
9163 @table @option
9164 @c !sort!
9165
9166 @item --version
9167 @cindex @option{--version} @command{gnatmake}
9168 Display Copyright and version, then exit disregarding all other options.
9169
9170 @item --help
9171 @cindex @option{--help} @command{gnatmake}
9172 If @option{--version} was not used, display usage, then exit disregarding
9173 all other options.
9174
9175 @ifclear vms
9176 @item --GCC=@var{compiler_name}
9177 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9178 Program used for compiling. The default is `@command{gcc}'. You need to use
9179 quotes around @var{compiler_name} if @code{compiler_name} contains
9180 spaces or other separator characters. As an example @option{--GCC="foo -x
9181 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9182 compiler. A limitation of this syntax is that the name and path name of
9183 the executable itself must not include any embedded spaces. Note that
9184 switch @option{-c} is always inserted after your command name. Thus in the
9185 above example the compiler command that will be used by @command{gnatmake}
9186 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9187 used, only the last @var{compiler_name} is taken into account. However,
9188 all the additional switches are also taken into account. Thus,
9189 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9190 @option{--GCC="bar -x -y -z -t"}.
9191
9192 @item --GNATBIND=@var{binder_name}
9193 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9194 Program used for binding. The default is `@code{gnatbind}'. You need to
9195 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9196 or other separator characters. As an example @option{--GNATBIND="bar -x
9197 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9198 binder. Binder switches that are normally appended by @command{gnatmake}
9199 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9200 A limitation of this syntax is that the name and path name of the executable
9201 itself must not include any embedded spaces.
9202
9203 @item --GNATLINK=@var{linker_name}
9204 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9205 Program used for linking. The default is `@command{gnatlink}'. You need to
9206 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9207 or other separator characters. As an example @option{--GNATLINK="lan -x
9208 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9209 linker. Linker switches that are normally appended by @command{gnatmake} to
9210 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9211 A limitation of this syntax is that the name and path name of the executable
9212 itself must not include any embedded spaces.
9213
9214 @end ifclear
9215
9216 @item ^-a^/ALL_FILES^
9217 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9218 Consider all files in the make process, even the GNAT internal system
9219 files (for example, the predefined Ada library files), as well as any
9220 locked files. Locked files are files whose ALI file is write-protected.
9221 By default,
9222 @command{gnatmake} does not check these files,
9223 because the assumption is that the GNAT internal files are properly up
9224 to date, and also that any write protected ALI files have been properly
9225 installed. Note that if there is an installation problem, such that one
9226 of these files is not up to date, it will be properly caught by the
9227 binder.
9228 You may have to specify this switch if you are working on GNAT
9229 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9230 in conjunction with @option{^-f^/FORCE_COMPILE^}
9231 if you need to recompile an entire application,
9232 including run-time files, using special configuration pragmas,
9233 such as a @code{Normalize_Scalars} pragma.
9234
9235 By default
9236 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9237 internal files with
9238 @ifclear vms
9239 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9240 @end ifclear
9241 @ifset vms
9242 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9243 @end ifset
9244
9245 @item ^-b^/ACTIONS=BIND^
9246 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9247 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9248 compilation and binding, but no link.
9249 Can be combined with @option{^-l^/ACTIONS=LINK^}
9250 to do binding and linking. When not combined with
9251 @option{^-c^/ACTIONS=COMPILE^}
9252 all the units in the closure of the main program must have been previously
9253 compiled and must be up to date. The root unit specified by @var{file_name}
9254 may be given without extension, with the source extension or, if no GNAT
9255 Project File is specified, with the ALI file extension.
9256
9257 @item ^-c^/ACTIONS=COMPILE^
9258 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9259 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9260 is also specified. Do not perform linking, except if both
9261 @option{^-b^/ACTIONS=BIND^} and
9262 @option{^-l^/ACTIONS=LINK^} are also specified.
9263 If the root unit specified by @var{file_name} is not a main unit, this is the
9264 default. Otherwise @command{gnatmake} will attempt binding and linking
9265 unless all objects are up to date and the executable is more recent than
9266 the objects.
9267
9268 @item ^-C^/MAPPING^
9269 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9270 Use a temporary mapping file. A mapping file is a way to communicate to the
9271 compiler two mappings: from unit names to file names (without any directory
9272 information) and from file names to path names (with full directory
9273 information). These mappings are used by the compiler to short-circuit the path
9274 search. When @command{gnatmake} is invoked with this switch, it will create
9275 a temporary mapping file, initially populated by the project manager,
9276 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
9277 Each invocation of the compiler will add the newly accessed sources to the
9278 mapping file. This will improve the source search during the next invocation
9279 of the compiler.
9280
9281 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9282 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9283 Use a specific mapping file. The file, specified as a path name (absolute or
9284 relative) by this switch, should already exist, otherwise the switch is
9285 ineffective. The specified mapping file will be communicated to the compiler.
9286 This switch is not compatible with a project file
9287 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9288 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9289
9290 @item ^-d^/DISPLAY_PROGRESS^
9291 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9292 Display progress for each source, up to date or not, as a single line
9293
9294 @smallexample
9295 completed x out of y (zz%)
9296 @end smallexample
9297
9298 If the file needs to be compiled this is displayed after the invocation of
9299 the compiler. These lines are displayed even in quiet output mode.
9300
9301 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9302 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9303 Put all object files and ALI file in directory @var{dir}.
9304 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9305 and ALI files go in the current working directory.
9306
9307 This switch cannot be used when using a project file.
9308
9309 @ifclear vms
9310 @item -eL
9311 @cindex @option{-eL} (@command{gnatmake})
9312 Follow all symbolic links when processing project files.
9313 @end ifclear
9314
9315 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9316 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9317 Output the commands for the compiler, the binder and the linker
9318 on ^standard output^SYS$OUTPUT^,
9319 instead of ^standard error^SYS$ERROR^.
9320
9321 @item ^-f^/FORCE_COMPILE^
9322 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9323 Force recompilations. Recompile all sources, even though some object
9324 files may be up to date, but don't recompile predefined or GNAT internal
9325 files or locked files (files with a write-protected ALI file),
9326 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9327
9328 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9329 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9330 When using project files, if some errors or warnings are detected during
9331 parsing and verbose mode is not in effect (no use of switch
9332 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9333 file, rather than its simple file name.
9334
9335 @item ^-g^/DEBUG^
9336 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9337 Enable debugging. This switch is simply passed to the compiler and to the
9338 linker.
9339
9340 @item ^-i^/IN_PLACE^
9341 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9342 In normal mode, @command{gnatmake} compiles all object files and ALI files
9343 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9344 then instead object files and ALI files that already exist are overwritten
9345 in place. This means that once a large project is organized into separate
9346 directories in the desired manner, then @command{gnatmake} will automatically
9347 maintain and update this organization. If no ALI files are found on the
9348 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9349 the new object and ALI files are created in the
9350 directory containing the source being compiled. If another organization
9351 is desired, where objects and sources are kept in different directories,
9352 a useful technique is to create dummy ALI files in the desired directories.
9353 When detecting such a dummy file, @command{gnatmake} will be forced to
9354 recompile the corresponding source file, and it will be put the resulting
9355 object and ALI files in the directory where it found the dummy file.
9356
9357 @item ^-j^/PROCESSES=^@var{n}
9358 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9359 @cindex Parallel make
9360 Use @var{n} processes to carry out the (re)compilations. On a
9361 multiprocessor machine compilations will occur in parallel. In the
9362 event of compilation errors, messages from various compilations might
9363 get interspersed (but @command{gnatmake} will give you the full ordered
9364 list of failing compiles at the end). If this is problematic, rerun
9365 the make process with n set to 1 to get a clean list of messages.
9366
9367 @item ^-k^/CONTINUE_ON_ERROR^
9368 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9369 Keep going. Continue as much as possible after a compilation error. To
9370 ease the programmer's task in case of compilation errors, the list of
9371 sources for which the compile fails is given when @command{gnatmake}
9372 terminates.
9373
9374 If @command{gnatmake} is invoked with several @file{file_names} and with this
9375 switch, if there are compilation errors when building an executable,
9376 @command{gnatmake} will not attempt to build the following executables.
9377
9378 @item ^-l^/ACTIONS=LINK^
9379 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9380 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9381 and linking. Linking will not be performed if combined with
9382 @option{^-c^/ACTIONS=COMPILE^}
9383 but not with @option{^-b^/ACTIONS=BIND^}.
9384 When not combined with @option{^-b^/ACTIONS=BIND^}
9385 all the units in the closure of the main program must have been previously
9386 compiled and must be up to date, and the main program needs to have been bound.
9387 The root unit specified by @var{file_name}
9388 may be given without extension, with the source extension or, if no GNAT
9389 Project File is specified, with the ALI file extension.
9390
9391 @item ^-m^/MINIMAL_RECOMPILATION^
9392 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9393 Specify that the minimum necessary amount of recompilations
9394 be performed. In this mode @command{gnatmake} ignores time
9395 stamp differences when the only
9396 modifications to a source file consist in adding/removing comments,
9397 empty lines, spaces or tabs. This means that if you have changed the
9398 comments in a source file or have simply reformatted it, using this
9399 switch will tell @command{gnatmake} not to recompile files that depend on it
9400 (provided other sources on which these files depend have undergone no
9401 semantic modifications). Note that the debugging information may be
9402 out of date with respect to the sources if the @option{-m} switch causes
9403 a compilation to be switched, so the use of this switch represents a
9404 trade-off between compilation time and accurate debugging information.
9405
9406 @item ^-M^/DEPENDENCIES_LIST^
9407 @cindex Dependencies, producing list
9408 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9409 Check if all objects are up to date. If they are, output the object
9410 dependences to @file{stdout} in a form that can be directly exploited in
9411 a @file{Makefile}. By default, each source file is prefixed with its
9412 (relative or absolute) directory name. This name is whatever you
9413 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9414 and @option{^-I^/SEARCH^} switches. If you use
9415 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9416 @option{^-q^/QUIET^}
9417 (see below), only the source file names,
9418 without relative paths, are output. If you just specify the
9419 @option{^-M^/DEPENDENCIES_LIST^}
9420 switch, dependencies of the GNAT internal system files are omitted. This
9421 is typically what you want. If you also specify
9422 the @option{^-a^/ALL_FILES^} switch,
9423 dependencies of the GNAT internal files are also listed. Note that
9424 dependencies of the objects in external Ada libraries (see switch
9425 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9426 are never reported.
9427
9428 @item ^-n^/DO_OBJECT_CHECK^
9429 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9430 Don't compile, bind, or link. Checks if all objects are up to date.
9431 If they are not, the full name of the first file that needs to be
9432 recompiled is printed.
9433 Repeated use of this option, followed by compiling the indicated source
9434 file, will eventually result in recompiling all required units.
9435
9436 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9437 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9438 Output executable name. The name of the final executable program will be
9439 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9440 name for the executable will be the name of the input file in appropriate form
9441 for an executable file on the host system.
9442
9443 This switch cannot be used when invoking @command{gnatmake} with several
9444 @file{file_names}.
9445
9446 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9447 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9448 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9449 automatically missing object directories, library directories and exec
9450 directories.
9451
9452 @item ^-P^/PROJECT_FILE=^@var{project}
9453 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9454 Use project file @var{project}. Only one such switch can be used.
9455 @xref{gnatmake and Project Files}.
9456
9457 @item ^-q^/QUIET^
9458 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9459 Quiet. When this flag is not set, the commands carried out by
9460 @command{gnatmake} are displayed.
9461
9462 @item ^-s^/SWITCH_CHECK/^
9463 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9464 Recompile if compiler switches have changed since last compilation.
9465 All compiler switches but -I and -o are taken into account in the
9466 following way:
9467 orders between different ``first letter'' switches are ignored, but
9468 orders between same switches are taken into account. For example,
9469 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9470 is equivalent to @option{-O -g}.
9471
9472 This switch is recommended when Integrated Preprocessing is used.
9473
9474 @item ^-u^/UNIQUE^
9475 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9476 Unique. Recompile at most the main files. It implies -c. Combined with
9477 -f, it is equivalent to calling the compiler directly. Note that using
9478 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9479 (@pxref{Project Files and Main Subprograms}).
9480
9481 @item ^-U^/ALL_PROJECTS^
9482 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9483 When used without a project file or with one or several mains on the command
9484 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9485 on the command line, all sources of all project files are checked and compiled
9486 if not up to date, and libraries are rebuilt, if necessary.
9487
9488 @item ^-v^/REASONS^
9489 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9490 Verbose. Display the reason for all recompilations @command{gnatmake}
9491 decides are necessary, with the highest verbosity level.
9492
9493 @item ^-vl^/LOW_VERBOSITY^
9494 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9495 Verbosity level Low. Display fewer lines than in verbosity Medium.
9496
9497 @item ^-vm^/MEDIUM_VERBOSITY^
9498 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9499 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9500
9501 @item ^-vh^/HIGH_VERBOSITY^
9502 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9503 Verbosity level High. Equivalent to ^-v^/REASONS^.
9504
9505 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9506 Indicate the verbosity of the parsing of GNAT project files.
9507 @xref{Switches Related to Project Files}.
9508
9509 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9510 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9511 Indicate that sources that are not part of any Project File may be compiled.
9512 Normally, when using Project Files, only sources that are part of a Project
9513 File may be compile. When this switch is used, a source outside of all Project
9514 Files may be compiled. The ALI file and the object file will be put in the
9515 object directory of the main Project. The compilation switches used will only
9516 be those specified on the command line. Even when
9517 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9518 command line need to be sources of a project file.
9519
9520 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9521 Indicate that external variable @var{name} has the value @var{value}.
9522 The Project Manager will use this value for occurrences of
9523 @code{external(name)} when parsing the project file.
9524 @xref{Switches Related to Project Files}.
9525
9526 @item ^-z^/NOMAIN^
9527 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9528 No main subprogram. Bind and link the program even if the unit name
9529 given on the command line is a package name. The resulting executable
9530 will execute the elaboration routines of the package and its closure,
9531 then the finalization routines.
9532
9533 @end table
9534
9535 @table @asis
9536 @item @command{gcc} @asis{switches}
9537 @ifclear vms
9538 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9539 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9540 @end ifclear
9541 @ifset vms
9542 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9543 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9544 automatically treated as a compiler switch, and passed on to all
9545 compilations that are carried out.
9546 @end ifset
9547 @end table
9548
9549 @noindent
9550 Source and library search path switches:
9551
9552 @table @option
9553 @c !sort!
9554 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9555 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9556 When looking for source files also look in directory @var{dir}.
9557 The order in which source files search is undertaken is
9558 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9559
9560 @item ^-aL^/SKIP_MISSING=^@var{dir}
9561 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9562 Consider @var{dir} as being an externally provided Ada library.
9563 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9564 files have been located in directory @var{dir}. This allows you to have
9565 missing bodies for the units in @var{dir} and to ignore out of date bodies
9566 for the same units. You still need to specify
9567 the location of the specs for these units by using the switches
9568 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9569 or @option{^-I^/SEARCH=^@var{dir}}.
9570 Note: this switch is provided for compatibility with previous versions
9571 of @command{gnatmake}. The easier method of causing standard libraries
9572 to be excluded from consideration is to write-protect the corresponding
9573 ALI files.
9574
9575 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9576 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9577 When searching for library and object files, look in directory
9578 @var{dir}. The order in which library files are searched is described in
9579 @ref{Search Paths for gnatbind}.
9580
9581 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9582 @cindex Search paths, for @command{gnatmake}
9583 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9584 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9585 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9586
9587 @item ^-I^/SEARCH=^@var{dir}
9588 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9589 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9590 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9591
9592 @item ^-I-^/NOCURRENT_DIRECTORY^
9593 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9594 @cindex Source files, suppressing search
9595 Do not look for source files in the directory containing the source
9596 file named in the command line.
9597 Do not look for ALI or object files in the directory
9598 where @command{gnatmake} was invoked.
9599
9600 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9601 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9602 @cindex Linker libraries
9603 Add directory @var{dir} to the list of directories in which the linker
9604 will search for libraries. This is equivalent to
9605 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9606 @ifclear vms
9607 Furthermore, under Windows, the sources pointed to by the libraries path
9608 set in the registry are not searched for.
9609 @end ifclear
9610
9611 @item -nostdinc
9612 @cindex @option{-nostdinc} (@command{gnatmake})
9613 Do not look for source files in the system default directory.
9614
9615 @item -nostdlib
9616 @cindex @option{-nostdlib} (@command{gnatmake})
9617 Do not look for library files in the system default directory.
9618
9619 @item --RTS=@var{rts-path}
9620 @cindex @option{--RTS} (@command{gnatmake})
9621 Specifies the default location of the runtime library. GNAT looks for the
9622 runtime
9623 in the following directories, and stops as soon as a valid runtime is found
9624 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9625 @file{ada_object_path} present):
9626
9627 @itemize @bullet
9628 @item <current directory>/$rts_path
9629
9630 @item <default-search-dir>/$rts_path
9631
9632 @item <default-search-dir>/rts-$rts_path
9633 @end itemize
9634
9635 @noindent
9636 The selected path is handled like a normal RTS path.
9637
9638 @end table
9639
9640 @node Mode Switches for gnatmake
9641 @section Mode Switches for @command{gnatmake}
9642
9643 @noindent
9644 The mode switches (referred to as @code{mode_switches}) allow the
9645 inclusion of switches that are to be passed to the compiler itself, the
9646 binder or the linker. The effect of a mode switch is to cause all
9647 subsequent switches up to the end of the switch list, or up to the next
9648 mode switch, to be interpreted as switches to be passed on to the
9649 designated component of GNAT.
9650
9651 @table @option
9652 @c !sort!
9653 @item -cargs @var{switches}
9654 @cindex @option{-cargs} (@command{gnatmake})
9655 Compiler switches. Here @var{switches} is a list of switches
9656 that are valid switches for @command{gcc}. They will be passed on to
9657 all compile steps performed by @command{gnatmake}.
9658
9659 @item -bargs @var{switches}
9660 @cindex @option{-bargs} (@command{gnatmake})
9661 Binder switches. Here @var{switches} is a list of switches
9662 that are valid switches for @code{gnatbind}. They will be passed on to
9663 all bind steps performed by @command{gnatmake}.
9664
9665 @item -largs @var{switches}
9666 @cindex @option{-largs} (@command{gnatmake})
9667 Linker switches. Here @var{switches} is a list of switches
9668 that are valid switches for @command{gnatlink}. They will be passed on to
9669 all link steps performed by @command{gnatmake}.
9670
9671 @item -margs @var{switches}
9672 @cindex @option{-margs} (@command{gnatmake})
9673 Make switches. The switches are directly interpreted by @command{gnatmake},
9674 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9675 or @option{-largs}.
9676 @end table
9677
9678 @node Notes on the Command Line
9679 @section Notes on the Command Line
9680
9681 @noindent
9682 This section contains some additional useful notes on the operation
9683 of the @command{gnatmake} command.
9684
9685 @itemize @bullet
9686 @item
9687 @cindex Recompilation, by @command{gnatmake}
9688 If @command{gnatmake} finds no ALI files, it recompiles the main program
9689 and all other units required by the main program.
9690 This means that @command{gnatmake}
9691 can be used for the initial compile, as well as during subsequent steps of
9692 the development cycle.
9693
9694 @item
9695 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9696 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9697 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9698 warning.
9699
9700 @item
9701 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9702 is used to specify both source and
9703 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9704 instead if you just want to specify
9705 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9706 if you want to specify library paths
9707 only.
9708
9709 @item
9710 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9711 This may conveniently be used to exclude standard libraries from
9712 consideration and in particular it means that the use of the
9713 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9714 unless @option{^-a^/ALL_FILES^} is also specified.
9715
9716 @item
9717 @command{gnatmake} has been designed to make the use of Ada libraries
9718 particularly convenient. Assume you have an Ada library organized
9719 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9720 of your Ada compilation units,
9721 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9722 specs of these units, but no bodies. Then to compile a unit
9723 stored in @code{main.adb}, which uses this Ada library you would just type
9724
9725 @smallexample
9726 @ifclear vms
9727 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9728 @end ifclear
9729 @ifset vms
9730 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9731            /SKIP_MISSING=@i{[OBJ_DIR]} main
9732 @end ifset
9733 @end smallexample
9734
9735 @item
9736 Using @command{gnatmake} along with the
9737 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9738 switch provides a mechanism for avoiding unnecessary recompilations. Using
9739 this switch,
9740 you can update the comments/format of your
9741 source files without having to recompile everything. Note, however, that
9742 adding or deleting lines in a source files may render its debugging
9743 info obsolete. If the file in question is a spec, the impact is rather
9744 limited, as that debugging info will only be useful during the
9745 elaboration phase of your program. For bodies the impact can be more
9746 significant. In all events, your debugger will warn you if a source file
9747 is more recent than the corresponding object, and alert you to the fact
9748 that the debugging information may be out of date.
9749 @end itemize
9750
9751 @node How gnatmake Works
9752 @section How @command{gnatmake} Works
9753
9754 @noindent
9755 Generally @command{gnatmake} automatically performs all necessary
9756 recompilations and you don't need to worry about how it works. However,
9757 it may be useful to have some basic understanding of the @command{gnatmake}
9758 approach and in particular to understand how it uses the results of
9759 previous compilations without incorrectly depending on them.
9760
9761 First a definition: an object file is considered @dfn{up to date} if the
9762 corresponding ALI file exists and if all the source files listed in the
9763 dependency section of this ALI file have time stamps matching those in
9764 the ALI file. This means that neither the source file itself nor any
9765 files that it depends on have been modified, and hence there is no need
9766 to recompile this file.
9767
9768 @command{gnatmake} works by first checking if the specified main unit is up
9769 to date. If so, no compilations are required for the main unit. If not,
9770 @command{gnatmake} compiles the main program to build a new ALI file that
9771 reflects the latest sources. Then the ALI file of the main unit is
9772 examined to find all the source files on which the main program depends,
9773 and @command{gnatmake} recursively applies the above procedure on all these
9774 files.
9775
9776 This process ensures that @command{gnatmake} only trusts the dependencies
9777 in an existing ALI file if they are known to be correct. Otherwise it
9778 always recompiles to determine a new, guaranteed accurate set of
9779 dependencies. As a result the program is compiled ``upside down'' from what may
9780 be more familiar as the required order of compilation in some other Ada
9781 systems. In particular, clients are compiled before the units on which
9782 they depend. The ability of GNAT to compile in any order is critical in
9783 allowing an order of compilation to be chosen that guarantees that
9784 @command{gnatmake} will recompute a correct set of new dependencies if
9785 necessary.
9786
9787 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9788 imported by several of the executables, it will be recompiled at most once.
9789
9790 Note: when using non-standard naming conventions
9791 (@pxref{Using Other File Names}), changing through a configuration pragmas
9792 file the version of a source and invoking @command{gnatmake} to recompile may
9793 have no effect, if the previous version of the source is still accessible
9794 by @command{gnatmake}. It may be necessary to use the switch
9795 ^-f^/FORCE_COMPILE^.
9796
9797 @node Examples of gnatmake Usage
9798 @section Examples of @command{gnatmake} Usage
9799
9800 @table @code
9801 @item gnatmake hello.adb
9802 Compile all files necessary to bind and link the main program
9803 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9804 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9805
9806 @item gnatmake main1 main2 main3
9807 Compile all files necessary to bind and link the main programs
9808 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9809 (containing unit @code{Main2}) and @file{main3.adb}
9810 (containing unit @code{Main3}) and bind and link the resulting object files
9811 to generate three executable files @file{^main1^MAIN1.EXE^},
9812 @file{^main2^MAIN2.EXE^}
9813 and @file{^main3^MAIN3.EXE^}.
9814
9815 @ifclear vms
9816 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9817 @end ifclear
9818
9819 @ifset vms
9820 @item gnatmake Main_Unit /QUIET
9821 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9822 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9823 @end ifset
9824 Compile all files necessary to bind and link the main program unit
9825 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9826 be done with optimization level 2 and the order of elaboration will be
9827 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9828 displaying commands it is executing.
9829 @end table
9830
9831 @c *************************
9832 @node Improving Performance
9833 @chapter Improving Performance
9834 @cindex Improving performance
9835
9836 @noindent
9837 This chapter presents several topics related to program performance.
9838 It first describes some of the tradeoffs that need to be considered
9839 and some of the techniques for making your program run faster.
9840 It then documents the @command{gnatelim} tool and unused subprogram/data
9841 elimination feature, which can reduce the size of program executables.
9842
9843 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9844 driver (see @ref{The GNAT Driver and Project Files}).
9845
9846 @ifnottex
9847 @menu
9848 * Performance Considerations::
9849 * Text_IO Suggestions::
9850 * Reducing Size of Ada Executables with gnatelim::
9851 * Reducing Size of Executables with unused subprogram/data elimination::
9852 @end menu
9853 @end ifnottex
9854
9855 @c *****************************
9856 @node Performance Considerations
9857 @section Performance Considerations
9858
9859 @noindent
9860 The GNAT system provides a number of options that allow a trade-off
9861 between
9862
9863 @itemize @bullet
9864 @item
9865 performance of the generated code
9866
9867 @item
9868 speed of compilation
9869
9870 @item
9871 minimization of dependences and recompilation
9872
9873 @item
9874 the degree of run-time checking.
9875 @end itemize
9876
9877 @noindent
9878 The defaults (if no options are selected) aim at improving the speed
9879 of compilation and minimizing dependences, at the expense of performance
9880 of the generated code:
9881
9882 @itemize @bullet
9883 @item
9884 no optimization
9885
9886 @item
9887 no inlining of subprogram calls
9888
9889 @item
9890 all run-time checks enabled except overflow and elaboration checks
9891 @end itemize
9892
9893 @noindent
9894 These options are suitable for most program development purposes. This
9895 chapter describes how you can modify these choices, and also provides
9896 some guidelines on debugging optimized code.
9897
9898 @menu
9899 * Controlling Run-Time Checks::
9900 * Use of Restrictions::
9901 * Optimization Levels::
9902 * Debugging Optimized Code::
9903 * Inlining of Subprograms::
9904 * Other Optimization Switches::
9905 * Optimization and Strict Aliasing::
9906
9907 @ifset vms
9908 * Coverage Analysis::
9909 @end ifset
9910 @end menu
9911
9912 @node Controlling Run-Time Checks
9913 @subsection Controlling Run-Time Checks
9914
9915 @noindent
9916 By default, GNAT generates all run-time checks, except integer overflow
9917 checks, stack overflow checks, and checks for access before elaboration on
9918 subprogram calls. The latter are not required in default mode, because all
9919 necessary checking is done at compile time.
9920 @cindex @option{-gnatp} (@command{gcc})
9921 @cindex @option{-gnato} (@command{gcc})
9922 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9923 be modified. @xref{Run-Time Checks}.
9924
9925 Our experience is that the default is suitable for most development
9926 purposes.
9927
9928 We treat integer overflow specially because these
9929 are quite expensive and in our experience are not as important as other
9930 run-time checks in the development process. Note that division by zero
9931 is not considered an overflow check, and divide by zero checks are
9932 generated where required by default.
9933
9934 Elaboration checks are off by default, and also not needed by default, since
9935 GNAT uses a static elaboration analysis approach that avoids the need for
9936 run-time checking. This manual contains a full chapter discussing the issue
9937 of elaboration checks, and if the default is not satisfactory for your use,
9938 you should read this chapter.
9939
9940 For validity checks, the minimal checks required by the Ada Reference
9941 Manual (for case statements and assignments to array elements) are on
9942 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9943 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9944 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9945 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9946 are also suppressed entirely if @option{-gnatp} is used.
9947
9948 @cindex Overflow checks
9949 @cindex Checks, overflow
9950 @findex Suppress
9951 @findex Unsuppress
9952 @cindex pragma Suppress
9953 @cindex pragma Unsuppress
9954 Note that the setting of the switches controls the default setting of
9955 the checks. They may be modified using either @code{pragma Suppress} (to
9956 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9957 checks) in the program source.
9958
9959 @node Use of Restrictions
9960 @subsection Use of Restrictions
9961
9962 @noindent
9963 The use of pragma Restrictions allows you to control which features are
9964 permitted in your program. Apart from the obvious point that if you avoid
9965 relatively expensive features like finalization (enforceable by the use
9966 of pragma Restrictions (No_Finalization), the use of this pragma does not
9967 affect the generated code in most cases.
9968
9969 One notable exception to this rule is that the possibility of task abort
9970 results in some distributed overhead, particularly if finalization or
9971 exception handlers are used. The reason is that certain sections of code
9972 have to be marked as non-abortable.
9973
9974 If you use neither the @code{abort} statement, nor asynchronous transfer
9975 of control (@code{select @dots{} then abort}), then this distributed overhead
9976 is removed, which may have a general positive effect in improving
9977 overall performance.  Especially code involving frequent use of tasking
9978 constructs and controlled types will show much improved performance.
9979 The relevant restrictions pragmas are
9980
9981 @smallexample @c ada
9982    pragma Restrictions (No_Abort_Statements);
9983    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9984 @end smallexample
9985
9986 @noindent
9987 It is recommended that these restriction pragmas be used if possible. Note
9988 that this also means that you can write code without worrying about the
9989 possibility of an immediate abort at any point.
9990
9991 @node Optimization Levels
9992 @subsection Optimization Levels
9993 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9994
9995 @noindent
9996 Without any optimization ^option,^qualifier,^
9997 the compiler's goal is to reduce the cost of
9998 compilation and to make debugging produce the expected results.
9999 Statements are independent: if you stop the program with a breakpoint between
10000 statements, you can then assign a new value to any variable or change
10001 the program counter to any other statement in the subprogram and get exactly
10002 the results you would expect from the source code.
10003
10004 Turning on optimization makes the compiler attempt to improve the
10005 performance and/or code size at the expense of compilation time and
10006 possibly the ability to debug the program.
10007
10008 If you use multiple
10009 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10010 the last such option is the one that is effective.
10011
10012 @noindent
10013 The default is optimization off. This results in the fastest compile
10014 times, but GNAT makes absolutely no attempt to optimize, and the
10015 generated programs are considerably larger and slower than when
10016 optimization is enabled. You can use the
10017 @ifclear vms
10018 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10019 @option{-O2}, @option{-O3}, and @option{-Os})
10020 @end ifclear
10021 @ifset vms
10022 @code{OPTIMIZE} qualifier
10023 @end ifset
10024 to @command{gcc} to control the optimization level:
10025
10026 @table @option
10027 @item ^-O0^/OPTIMIZE=NONE^
10028 No optimization (the default);
10029 generates unoptimized code but has
10030 the fastest compilation time.
10031
10032 Note that many other compilers do fairly extensive optimization
10033 even if ``no optimization'' is specified. With gcc, it is
10034 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10035 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10036 really does mean no optimization at all. This difference between
10037 gcc and other compilers should be kept in mind when doing
10038 performance comparisons.
10039
10040 @item ^-O1^/OPTIMIZE=SOME^
10041 Moderate optimization;
10042 optimizes reasonably well but does not
10043 degrade compilation time significantly.
10044
10045 @item ^-O2^/OPTIMIZE=ALL^
10046 @ifset vms
10047 @itemx /OPTIMIZE=DEVELOPMENT
10048 @end ifset
10049 Full optimization;
10050 generates highly optimized code and has
10051 the slowest compilation time.
10052
10053 @item ^-O3^/OPTIMIZE=INLINING^
10054 Full optimization as in @option{-O2},
10055 and also attempts automatic inlining of small
10056 subprograms within a unit (@pxref{Inlining of Subprograms}).
10057
10058 @item ^-Os^/OPTIMIZE=SPACE^
10059 Optimize space usage of resulting program.
10060 @end table
10061
10062 @noindent
10063 Higher optimization levels perform more global transformations on the
10064 program and apply more expensive analysis algorithms in order to generate
10065 faster and more compact code. The price in compilation time, and the
10066 resulting improvement in execution time,
10067 both depend on the particular application and the hardware environment.
10068 You should experiment to find the best level for your application.
10069
10070 Since the precise set of optimizations done at each level will vary from
10071 release to release (and sometime from target to target), it is best to think
10072 of the optimization settings in general terms.
10073 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10074 the GNU Compiler Collection (GCC)}, for details about
10075 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10076 individually enable or disable specific optimizations.
10077
10078 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10079 been tested extensively at all optimization levels. There are some bugs
10080 which appear only with optimization turned on, but there have also been
10081 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10082 level of optimization does not improve the reliability of the code
10083 generator, which in practice is highly reliable at all optimization
10084 levels.
10085
10086 Note regarding the use of @option{-O3}: The use of this optimization level
10087 is generally discouraged with GNAT, since it often results in larger
10088 executables which run more slowly. See further discussion of this point
10089 in @ref{Inlining of Subprograms}.
10090
10091 @node Debugging Optimized Code
10092 @subsection Debugging Optimized Code
10093 @cindex Debugging optimized code
10094 @cindex Optimization and debugging
10095
10096 @noindent
10097 Although it is possible to do a reasonable amount of debugging at
10098 @ifclear vms
10099 nonzero optimization levels,
10100 the higher the level the more likely that
10101 @end ifclear
10102 @ifset vms
10103 @option{/OPTIMIZE} settings other than @code{NONE},
10104 such settings will make it more likely that
10105 @end ifset
10106 source-level constructs will have been eliminated by optimization.
10107 For example, if a loop is strength-reduced, the loop
10108 control variable may be completely eliminated and thus cannot be
10109 displayed in the debugger.
10110 This can only happen at @option{-O2} or @option{-O3}.
10111 Explicit temporary variables that you code might be eliminated at
10112 ^level^setting^ @option{-O1} or higher.
10113
10114 The use of the @option{^-g^/DEBUG^} switch,
10115 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10116 which is needed for source-level debugging,
10117 affects the size of the program executable on disk,
10118 and indeed the debugging information can be quite large.
10119 However, it has no effect on the generated code (and thus does not
10120 degrade performance)
10121
10122 Since the compiler generates debugging tables for a compilation unit before
10123 it performs optimizations, the optimizing transformations may invalidate some
10124 of the debugging data.  You therefore need to anticipate certain
10125 anomalous situations that may arise while debugging optimized code.
10126 These are the most common cases:
10127
10128 @enumerate
10129 @item
10130 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10131 commands show
10132 the PC bouncing back and forth in the code.  This may result from any of
10133 the following optimizations:
10134
10135 @itemize @bullet
10136 @item
10137 @i{Common subexpression elimination:} using a single instance of code for a
10138 quantity that the source computes several times.  As a result you
10139 may not be able to stop on what looks like a statement.
10140
10141 @item
10142 @i{Invariant code motion:} moving an expression that does not change within a
10143 loop, to the beginning of the loop.
10144
10145 @item
10146 @i{Instruction scheduling:} moving instructions so as to
10147 overlap loads and stores (typically) with other code, or in
10148 general to move computations of values closer to their uses. Often
10149 this causes you to pass an assignment statement without the assignment
10150 happening and then later bounce back to the statement when the
10151 value is actually needed.  Placing a breakpoint on a line of code
10152 and then stepping over it may, therefore, not always cause all the
10153 expected side-effects.
10154 @end itemize
10155
10156 @item
10157 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10158 two identical pieces of code are merged and the program counter suddenly
10159 jumps to a statement that is not supposed to be executed, simply because
10160 it (and the code following) translates to the same thing as the code
10161 that @emph{was} supposed to be executed.  This effect is typically seen in
10162 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10163 a @code{break} in a C @code{^switch^switch^} statement.
10164
10165 @item
10166 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10167 There are various reasons for this effect:
10168
10169 @itemize @bullet
10170 @item
10171 In a subprogram prologue, a parameter may not yet have been moved to its
10172 ``home''.
10173
10174 @item
10175 A variable may be dead, and its register re-used.  This is
10176 probably the most common cause.
10177
10178 @item
10179 As mentioned above, the assignment of a value to a variable may
10180 have been moved.
10181
10182 @item
10183 A variable may be eliminated entirely by value propagation or
10184 other means.  In this case, GCC may incorrectly generate debugging
10185 information for the variable
10186 @end itemize
10187
10188 @noindent
10189 In general, when an unexpected value appears for a local variable or parameter
10190 you should first ascertain if that value was actually computed by
10191 your program, as opposed to being incorrectly reported by the debugger.
10192 Record fields or
10193 array elements in an object designated by an access value
10194 are generally less of a problem, once you have ascertained that the access
10195 value is sensible.
10196 Typically, this means checking variables in the preceding code and in the
10197 calling subprogram to verify that the value observed is explainable from other
10198 values (one must apply the procedure recursively to those
10199 other values); or re-running the code and stopping a little earlier
10200 (perhaps before the call) and stepping to better see how the variable obtained
10201 the value in question; or continuing to step @emph{from} the point of the
10202 strange value to see if code motion had simply moved the variable's
10203 assignments later.
10204 @end enumerate
10205
10206 @noindent
10207 In light of such anomalies, a recommended technique is to use @option{-O0}
10208 early in the software development cycle, when extensive debugging capabilities
10209 are most needed, and then move to @option{-O1} and later @option{-O2} as
10210 the debugger becomes less critical.
10211 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10212 a release management issue.
10213 @ifclear vms
10214 Note that if you use @option{-g} you can then use the @command{strip} program
10215 on the resulting executable,
10216 which removes both debugging information and global symbols.
10217 @end ifclear
10218
10219 @node Inlining of Subprograms
10220 @subsection Inlining of Subprograms
10221
10222 @noindent
10223 A call to a subprogram in the current unit is inlined if all the
10224 following conditions are met:
10225
10226 @itemize @bullet
10227 @item
10228 The optimization level is at least @option{-O1}.
10229
10230 @item
10231 The called subprogram is suitable for inlining: It must be small enough
10232 and not contain something that @command{gcc} cannot support in inlined
10233 subprograms.
10234
10235 @item
10236 @cindex pragma Inline
10237 @findex Inline
10238 Either @code{pragma Inline} applies to the subprogram, or it is local
10239 to the unit and called once from within it, or it is small and automatic
10240 inlining (optimization level @option{-O3}) is specified.
10241 @end itemize
10242
10243 @noindent
10244 Calls to subprograms in @code{with}'ed units are normally not inlined.
10245 To achieve actual inlining (that is, replacement of the call by the code
10246 in the body of the subprogram), the following conditions must all be true.
10247
10248 @itemize @bullet
10249 @item
10250 The optimization level is at least @option{-O1}.
10251
10252 @item
10253 The called subprogram is suitable for inlining: It must be small enough
10254 and not contain something that @command{gcc} cannot support in inlined
10255 subprograms.
10256
10257 @item
10258 The call appears in a body (not in a package spec).
10259
10260 @item
10261 There is a @code{pragma Inline} for the subprogram.
10262
10263 @item
10264 @cindex @option{-gnatn} (@command{gcc})
10265 The @option{^-gnatn^/INLINE^} switch
10266 is used in the @command{gcc} command line
10267 @end itemize
10268
10269 Even if all these conditions are met, it may not be possible for
10270 the compiler to inline the call, due to the length of the body,
10271 or features in the body that make it impossible for the compiler
10272 to do the inlining.
10273
10274 Note that specifying the @option{-gnatn} switch causes additional
10275 compilation dependencies. Consider the following:
10276
10277 @smallexample @c ada
10278 @cartouche
10279 package R is
10280    procedure Q;
10281    pragma Inline (Q);
10282 end R;
10283 package body R is
10284    @dots{}
10285 end R;
10286
10287 with R;
10288 procedure Main is
10289 begin
10290    @dots{}
10291    R.Q;
10292 end Main;
10293 @end cartouche
10294 @end smallexample
10295
10296 @noindent
10297 With the default behavior (no @option{-gnatn} switch specified), the
10298 compilation of the @code{Main} procedure depends only on its own source,
10299 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10300 means that editing the body of @code{R} does not require recompiling
10301 @code{Main}.
10302
10303 On the other hand, the call @code{R.Q} is not inlined under these
10304 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10305 is compiled, the call will be inlined if the body of @code{Q} is small
10306 enough, but now @code{Main} depends on the body of @code{R} in
10307 @file{r.adb} as well as on the spec. This means that if this body is edited,
10308 the main program must be recompiled. Note that this extra dependency
10309 occurs whether or not the call is in fact inlined by @command{gcc}.
10310
10311 The use of front end inlining with @option{-gnatN} generates similar
10312 additional dependencies.
10313
10314 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10315 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10316 can be used to prevent
10317 all inlining. This switch overrides all other conditions and ensures
10318 that no inlining occurs. The extra dependences resulting from
10319 @option{-gnatn} will still be active, even if
10320 this switch is used to suppress the resulting inlining actions.
10321
10322 @cindex @option{-fno-inline-functions} (@command{gcc})
10323 Note: The @option{-fno-inline-functions} switch can be used to prevent
10324 automatic inlining of small subprograms if @option{-O3} is used.
10325
10326 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10327 Note: The @option{-fno-inline-functions-called-once} switch
10328 can be used to prevent inlining of subprograms local to the unit
10329 and called once from within it if @option{-O1} is used.
10330
10331 Note regarding the use of @option{-O3}: There is no difference in inlining
10332 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10333 pragma @code{Inline} assuming the use of @option{-gnatn}
10334 or @option{-gnatN} (the switches that activate inlining). If you have used
10335 pragma @code{Inline} in appropriate cases, then it is usually much better
10336 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10337 in this case only has the effect of inlining subprograms you did not
10338 think should be inlined. We often find that the use of @option{-O3} slows
10339 down code by performing excessive inlining, leading to increased instruction
10340 cache pressure from the increased code size. So the bottom line here is
10341 that you should not automatically assume that @option{-O3} is better than
10342 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10343 it actually improves performance.
10344
10345 @node Other Optimization Switches
10346 @subsection Other Optimization Switches
10347 @cindex Optimization Switches
10348
10349 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10350 @command{gcc} optimization switches are potentially usable. These switches
10351 have not been extensively tested with GNAT but can generally be expected
10352 to work. Examples of switches in this category are
10353 @option{-funroll-loops} and
10354 the various target-specific @option{-m} options (in particular, it has been
10355 observed that @option{-march=pentium4} can significantly improve performance
10356 on appropriate machines). For full details of these switches, see
10357 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10358 the GNU Compiler Collection (GCC)}.
10359
10360 @node Optimization and Strict Aliasing
10361 @subsection Optimization and Strict Aliasing
10362 @cindex Aliasing
10363 @cindex Strict Aliasing
10364 @cindex No_Strict_Aliasing
10365
10366 @noindent
10367 The strong typing capabilities of Ada allow an optimizer to generate
10368 efficient code in situations where other languages would be forced to
10369 make worst case assumptions preventing such optimizations. Consider
10370 the following example:
10371
10372 @smallexample @c ada
10373 @cartouche
10374 procedure R is
10375    type Int1 is new Integer;
10376    type Int2 is new Integer;
10377    type Int1A is access Int1;
10378    type Int2A is access Int2;
10379    Int1V : Int1A;
10380    Int2V : Int2A;
10381    @dots{}
10382
10383 begin
10384    @dots{}
10385    for J in Data'Range loop
10386       if Data (J) = Int1V.all then
10387          Int2V.all := Int2V.all + 1;
10388       end if;
10389    end loop;
10390    @dots{}
10391 end R;
10392 @end cartouche
10393 @end smallexample
10394
10395 @noindent
10396 In this example, since the variable @code{Int1V} can only access objects
10397 of type @code{Int1}, and @code{Int2V} can only access objects of type
10398 @code{Int2}, there is no possibility that the assignment to
10399 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10400 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10401 for all iterations of the loop and avoid the extra memory reference
10402 required to dereference it each time through the loop.
10403
10404 This kind of optimization, called strict aliasing analysis, is
10405 triggered by specifying an optimization level of @option{-O2} or
10406 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10407 when access values are involved.
10408
10409 However, although this optimization is always correct in terms of
10410 the formal semantics of the Ada Reference Manual, difficulties can
10411 arise if features like @code{Unchecked_Conversion} are used to break
10412 the typing system. Consider the following complete program example:
10413
10414 @smallexample @c ada
10415 @cartouche
10416 package p1 is
10417    type int1 is new integer;
10418    type int2 is new integer;
10419    type a1 is access int1;
10420    type a2 is access int2;
10421 end p1;
10422
10423 with p1; use p1;
10424 package p2 is
10425    function to_a2 (Input : a1) return a2;
10426 end p2;
10427
10428 with Unchecked_Conversion;
10429 package body p2 is
10430    function to_a2 (Input : a1) return a2 is
10431       function to_a2u is
10432         new Unchecked_Conversion (a1, a2);
10433    begin
10434       return to_a2u (Input);
10435    end to_a2;
10436 end p2;
10437
10438 with p2; use p2;
10439 with p1; use p1;
10440 with Text_IO; use Text_IO;
10441 procedure m is
10442    v1 : a1 := new int1;
10443    v2 : a2 := to_a2 (v1);
10444 begin
10445    v1.all := 1;
10446    v2.all := 0;
10447    put_line (int1'image (v1.all));
10448 end;
10449 @end cartouche
10450 @end smallexample
10451
10452 @noindent
10453 This program prints out 0 in @option{-O0} or @option{-O1}
10454 mode, but it prints out 1 in @option{-O2} mode. That's
10455 because in strict aliasing mode, the compiler can and
10456 does assume that the assignment to @code{v2.all} could not
10457 affect the value of @code{v1.all}, since different types
10458 are involved.
10459
10460 This behavior is not a case of non-conformance with the standard, since
10461 the Ada RM specifies that an unchecked conversion where the resulting
10462 bit pattern is not a correct value of the target type can result in an
10463 abnormal value and attempting to reference an abnormal value makes the
10464 execution of a program erroneous.  That's the case here since the result
10465 does not point to an object of type @code{int2}.  This means that the
10466 effect is entirely unpredictable.
10467
10468 However, although that explanation may satisfy a language
10469 lawyer, in practice an applications programmer expects an
10470 unchecked conversion involving pointers to create true
10471 aliases and the behavior of printing 1 seems plain wrong.
10472 In this case, the strict aliasing optimization is unwelcome.
10473
10474 Indeed the compiler recognizes this possibility, and the
10475 unchecked conversion generates a warning:
10476
10477 @smallexample
10478 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10479 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10480 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10481 @end smallexample
10482
10483 @noindent
10484 Unfortunately the problem is recognized when compiling the body of
10485 package @code{p2}, but the actual "bad" code is generated while
10486 compiling the body of @code{m} and this latter compilation does not see
10487 the suspicious @code{Unchecked_Conversion}.
10488
10489 As implied by the warning message, there are approaches you can use to
10490 avoid the unwanted strict aliasing optimization in a case like this.
10491
10492 One possibility is to simply avoid the use of @option{-O2}, but
10493 that is a bit drastic, since it throws away a number of useful
10494 optimizations that do not involve strict aliasing assumptions.
10495
10496 A less drastic approach is to compile the program using the
10497 option @option{-fno-strict-aliasing}. Actually it is only the
10498 unit containing the dereferencing of the suspicious pointer
10499 that needs to be compiled. So in this case, if we compile
10500 unit @code{m} with this switch, then we get the expected
10501 value of zero printed. Analyzing which units might need
10502 the switch can be painful, so a more reasonable approach
10503 is to compile the entire program with options @option{-O2}
10504 and @option{-fno-strict-aliasing}. If the performance is
10505 satisfactory with this combination of options, then the
10506 advantage is that the entire issue of possible "wrong"
10507 optimization due to strict aliasing is avoided.
10508
10509 To avoid the use of compiler switches, the configuration
10510 pragma @code{No_Strict_Aliasing} with no parameters may be
10511 used to specify that for all access types, the strict
10512 aliasing optimization should be suppressed.
10513
10514 However, these approaches are still overkill, in that they causes
10515 all manipulations of all access values to be deoptimized. A more
10516 refined approach is to concentrate attention on the specific
10517 access type identified as problematic.
10518
10519 First, if a careful analysis of uses of the pointer shows
10520 that there are no possible problematic references, then
10521 the warning can be suppressed by bracketing the
10522 instantiation of @code{Unchecked_Conversion} to turn
10523 the warning off:
10524
10525 @smallexample @c ada
10526    pragma Warnings (Off);
10527    function to_a2u is
10528      new Unchecked_Conversion (a1, a2);
10529    pragma Warnings (On);
10530 @end smallexample
10531
10532 @noindent
10533 Of course that approach is not appropriate for this particular
10534 example, since indeed there is a problematic reference. In this
10535 case we can take one of two other approaches.
10536
10537 The first possibility is to move the instantiation of unchecked
10538 conversion to the unit in which the type is declared. In
10539 this example, we would move the instantiation of
10540 @code{Unchecked_Conversion} from the body of package
10541 @code{p2} to the spec of package @code{p1}. Now the
10542 warning disappears. That's because any use of the
10543 access type knows there is a suspicious unchecked
10544 conversion, and the strict aliasing optimization
10545 is automatically suppressed for the type.
10546
10547 If it is not practical to move the unchecked conversion to the same unit
10548 in which the destination access type is declared (perhaps because the
10549 source type is not visible in that unit), you may use pragma
10550 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10551 same declarative sequence as the declaration of the access type:
10552
10553 @smallexample @c ada
10554    type a2 is access int2;
10555    pragma No_Strict_Aliasing (a2);
10556 @end smallexample
10557
10558 @noindent
10559 Here again, the compiler now knows that the strict aliasing optimization
10560 should be suppressed for any reference to type @code{a2} and the
10561 expected behavior is obtained.
10562
10563 Finally, note that although the compiler can generate warnings for
10564 simple cases of unchecked conversions, there are tricker and more
10565 indirect ways of creating type incorrect aliases which the compiler
10566 cannot detect. Examples are the use of address overlays and unchecked
10567 conversions involving composite types containing access types as
10568 components. In such cases, no warnings are generated, but there can
10569 still be aliasing problems. One safe coding practice is to forbid the
10570 use of address clauses for type overlaying, and to allow unchecked
10571 conversion only for primitive types. This is not really a significant
10572 restriction since any possible desired effect can be achieved by
10573 unchecked conversion of access values.
10574
10575 The aliasing analysis done in strict aliasing mode can certainly
10576 have significant benefits. We have seen cases of large scale
10577 application code where the time is increased by up to 5% by turning
10578 this optimization off. If you have code that includes significant
10579 usage of unchecked conversion, you might want to just stick with
10580 @option{-O1} and avoid the entire issue. If you get adequate
10581 performance at this level of optimization level, that's probably
10582 the safest approach. If tests show that you really need higher
10583 levels of optimization, then you can experiment with @option{-O2}
10584 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10585 has on size and speed of the code. If you really need to use
10586 @option{-O2} with strict aliasing in effect, then you should
10587 review any uses of unchecked conversion of access types,
10588 particularly if you are getting the warnings described above.
10589
10590 @ifset vms
10591 @node Coverage Analysis
10592 @subsection Coverage Analysis
10593
10594 @noindent
10595 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10596 the user to determine the distribution of execution time across a program,
10597 @pxref{Profiling} for details of usage.
10598 @end ifset
10599
10600
10601 @node Text_IO Suggestions
10602 @section @code{Text_IO} Suggestions
10603 @cindex @code{Text_IO} and performance
10604
10605 @noindent
10606 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10607 the requirement of maintaining page and line counts. If performance
10608 is critical, a recommendation is to use @code{Stream_IO} instead of
10609 @code{Text_IO} for volume output, since this package has less overhead.
10610
10611 If @code{Text_IO} must be used, note that by default output to the standard
10612 output and standard error files is unbuffered (this provides better
10613 behavior when output statements are used for debugging, or if the
10614 progress of a program is observed by tracking the output, e.g. by
10615 using the Unix @command{tail -f} command to watch redirected output.
10616
10617 If you are generating large volumes of output with @code{Text_IO} and
10618 performance is an important factor, use a designated file instead
10619 of the standard output file, or change the standard output file to
10620 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10621
10622
10623
10624 @node Reducing Size of Ada Executables with gnatelim
10625 @section Reducing Size of Ada Executables with @code{gnatelim}
10626 @findex gnatelim
10627
10628 @noindent
10629 This section describes @command{gnatelim}, a tool which detects unused
10630 subprograms and helps the compiler to create a smaller executable for your
10631 program.
10632
10633 @menu
10634 * About gnatelim::
10635 * Running gnatelim::
10636 * Correcting the List of Eliminate Pragmas::
10637 * Making Your Executables Smaller::
10638 * Summary of the gnatelim Usage Cycle::
10639 @end menu
10640
10641 @node About gnatelim
10642 @subsection About @code{gnatelim}
10643
10644 @noindent
10645 When a program shares a set of Ada
10646 packages with other programs, it may happen that this program uses
10647 only a fraction of the subprograms defined in these packages. The code
10648 created for these unused subprograms increases the size of the executable.
10649
10650 @code{gnatelim} tracks unused subprograms in an Ada program and
10651 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10652 subprograms that are declared but never called. By placing the list of
10653 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10654 recompiling your program, you may decrease the size of its executable,
10655 because the compiler will not generate the code for 'eliminated' subprograms.
10656 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10657 information about this pragma.
10658
10659 @code{gnatelim} needs as its input data the name of the main subprogram
10660 and a bind file for a main subprogram.
10661
10662 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10663 the main subprogram. @code{gnatelim} can work with both Ada and C
10664 bind files; when both are present, it uses the Ada bind file.
10665 The following commands will build the program and create the bind file:
10666
10667 @smallexample
10668 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10669 $ gnatbind main_prog
10670 @end smallexample
10671
10672 Note that @code{gnatelim} needs neither object nor ALI files.
10673
10674 @node Running gnatelim
10675 @subsection Running @code{gnatelim}
10676
10677 @noindent
10678 @code{gnatelim} has the following command-line interface:
10679
10680 @smallexample
10681 $ gnatelim @ovar{options} name
10682 @end smallexample
10683
10684 @noindent
10685 @code{name} should be a name of a source file that contains the main subprogram
10686 of a program (partition).
10687
10688 @code{gnatelim} has the following switches:
10689
10690 @table @option
10691 @c !sort!
10692 @item ^-q^/QUIET^
10693 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10694 Quiet mode: by default @code{gnatelim} outputs to the standard error
10695 stream the number of program units left to be processed. This option turns
10696 this trace off.
10697
10698 @item ^-v^/VERBOSE^
10699 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10700 Verbose mode: @code{gnatelim} version information is printed as Ada
10701 comments to the standard output stream. Also, in addition to the number of
10702 program units left @code{gnatelim} will output the name of the current unit
10703 being processed.
10704
10705 @item ^-a^/ALL^
10706 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10707 Also look for subprograms from the GNAT run time that can be eliminated. Note
10708 that when @file{gnat.adc} is produced using this switch, the entire program
10709 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10710
10711 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10712 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10713 When looking for source files also look in directory @var{dir}. Specifying
10714 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10715 sources in the current directory.
10716
10717 @item ^-b^/BIND_FILE=^@var{bind_file}
10718 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10719 Specifies @var{bind_file} as the bind file to process. If not set, the name
10720 of the bind file is computed from the full expanded Ada name
10721 of a main subprogram.
10722
10723 @item ^-C^/CONFIG_FILE=^@var{config_file}
10724 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10725 Specifies a file @var{config_file} that contains configuration pragmas. The
10726 file must be specified with full path.
10727
10728 @item ^--GCC^/COMPILER^=@var{compiler_name}
10729 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10730 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10731 available on the path.
10732
10733 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10734 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10735 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10736 available on the path.
10737 @end table
10738
10739 @noindent
10740 @code{gnatelim} sends its output to the standard output stream, and all the
10741 tracing and debug information is sent to the standard error stream.
10742 In order to produce a proper GNAT configuration file
10743 @file{gnat.adc}, redirection must be used:
10744
10745 @smallexample
10746 @ifset vms
10747 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10748 @end ifset
10749 @ifclear vms
10750 $ gnatelim main_prog.adb > gnat.adc
10751 @end ifclear
10752 @end smallexample
10753
10754 @ifclear vms
10755 @noindent
10756 or
10757
10758 @smallexample
10759 $ gnatelim main_prog.adb >> gnat.adc
10760 @end smallexample
10761
10762 @noindent
10763 in order to append the @code{gnatelim} output to the existing contents of
10764 @file{gnat.adc}.
10765 @end ifclear
10766
10767 @node Correcting the List of Eliminate Pragmas
10768 @subsection Correcting the List of Eliminate Pragmas
10769
10770 @noindent
10771 In some rare cases @code{gnatelim} may try to eliminate
10772 subprograms that are actually called in the program. In this case, the
10773 compiler will generate an error message of the form:
10774
10775 @smallexample
10776 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10777 @end smallexample
10778
10779 @noindent
10780 You will need to manually remove the wrong @code{Eliminate} pragmas from
10781 the @file{gnat.adc} file. You should recompile your program
10782 from scratch after that, because you need a consistent @file{gnat.adc} file
10783 during the entire compilation.
10784
10785 @node Making Your Executables Smaller
10786 @subsection Making Your Executables Smaller
10787
10788 @noindent
10789 In order to get a smaller executable for your program you now have to
10790 recompile the program completely with the new @file{gnat.adc} file
10791 created by @code{gnatelim} in your current directory:
10792
10793 @smallexample
10794 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10795 @end smallexample
10796
10797 @noindent
10798 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10799 recompile everything
10800 with the set of pragmas @code{Eliminate} that you have obtained with
10801 @command{gnatelim}).
10802
10803 Be aware that the set of @code{Eliminate} pragmas is specific to each
10804 program. It is not recommended to merge sets of @code{Eliminate}
10805 pragmas created for different programs in one @file{gnat.adc} file.
10806
10807 @node Summary of the gnatelim Usage Cycle
10808 @subsection Summary of the gnatelim Usage Cycle
10809
10810 @noindent
10811 Here is a quick summary of the steps to be taken in order to reduce
10812 the size of your executables with @code{gnatelim}. You may use
10813 other GNAT options to control the optimization level,
10814 to produce the debugging information, to set search path, etc.
10815
10816 @enumerate
10817 @item
10818 Produce a bind file
10819
10820 @smallexample
10821 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10822 $ gnatbind main_prog
10823 @end smallexample
10824
10825 @item
10826 Generate a list of @code{Eliminate} pragmas
10827 @smallexample
10828 @ifset vms
10829 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10830 @end ifset
10831 @ifclear vms
10832 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10833 @end ifclear
10834 @end smallexample
10835
10836 @item
10837 Recompile the application
10838
10839 @smallexample
10840 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10841 @end smallexample
10842
10843 @end enumerate
10844
10845 @node Reducing Size of Executables with unused subprogram/data elimination
10846 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10847 @findex unused subprogram/data elimination
10848
10849 @noindent
10850 This section describes how you can eliminate unused subprograms and data from
10851 your executable just by setting options at compilation time.
10852
10853 @menu
10854 * About unused subprogram/data elimination::
10855 * Compilation options::
10856 * Example of unused subprogram/data elimination::
10857 @end menu
10858
10859 @node About unused subprogram/data elimination
10860 @subsection About unused subprogram/data elimination
10861
10862 @noindent
10863 By default, an executable contains all code and data of its composing objects
10864 (directly linked or coming from statically linked libraries), even data or code
10865 never used by this executable.
10866
10867 This feature will allow you to eliminate such unused code from your
10868 executable, making it smaller (in disk and in memory).
10869
10870 This functionality is available on all Linux platforms except for the IA-64
10871 architecture and on all cross platforms using the ELF binary file format.
10872 In both cases GNU binutils version 2.16 or later are required to enable it.
10873
10874 @node Compilation options
10875 @subsection Compilation options
10876
10877 @noindent
10878 The operation of eliminating the unused code and data from the final executable
10879 is directly performed by the linker.
10880
10881 In order to do this, it has to work with objects compiled with the
10882 following options:
10883 @option{-ffunction-sections} @option{-fdata-sections}.
10884 @cindex @option{-ffunction-sections} (@command{gcc})
10885 @cindex @option{-fdata-sections} (@command{gcc})
10886 These options are usable with C and Ada files.
10887 They will place respectively each
10888 function or data in a separate section in the resulting object file.
10889
10890 Once the objects and static libraries are created with these options, the
10891 linker can perform the dead code elimination. You can do this by setting
10892 the @option{-Wl,--gc-sections} option to gcc command or in the
10893 @option{-largs} section of @command{gnatmake}. This will perform a
10894 garbage collection of code and data never referenced.
10895
10896 If the linker performs a partial link (@option{-r} ld linker option), then you
10897 will need to provide one or several entry point using the
10898 @option{-e} / @option{--entry} ld option.
10899
10900 Note that objects compiled without the @option{-ffunction-sections} and
10901 @option{-fdata-sections} options can still be linked with the executable.
10902 However, no dead code elimination will be performed on those objects (they will
10903 be linked as is).
10904
10905 The GNAT static library is now compiled with -ffunction-sections and
10906 -fdata-sections on some platforms. This allows you to eliminate the unused code
10907 and data of the GNAT library from your executable.
10908
10909 @node Example of unused subprogram/data elimination
10910 @subsection Example of unused subprogram/data elimination
10911
10912 @noindent
10913 Here is a simple example:
10914
10915 @smallexample @c ada
10916 with Aux;
10917
10918 procedure Test is
10919 begin
10920    Aux.Used (10);
10921 end Test;
10922
10923 package Aux is
10924    Used_Data   : Integer;
10925    Unused_Data : Integer;
10926
10927    procedure Used   (Data : Integer);
10928    procedure Unused (Data : Integer);
10929 end Aux;
10930
10931 package body Aux is
10932    procedure Used (Data : Integer) is
10933    begin
10934       Used_Data := Data;
10935    end Used;
10936
10937    procedure Unused (Data : Integer) is
10938    begin
10939       Unused_Data := Data;
10940    end Unused;
10941 end Aux;
10942 @end smallexample
10943
10944 @noindent
10945 @code{Unused} and @code{Unused_Data} are never referenced in this code
10946 excerpt, and hence they may be safely removed from the final executable.
10947
10948 @smallexample
10949 $ gnatmake test
10950
10951 $ nm test | grep used
10952 020015f0 T aux__unused
10953 02005d88 B aux__unused_data
10954 020015cc T aux__used
10955 02005d84 B aux__used_data
10956
10957 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10958      -largs -Wl,--gc-sections
10959
10960 $ nm test | grep used
10961 02005350 T aux__used
10962 0201ffe0 B aux__used_data
10963 @end smallexample
10964
10965 @noindent
10966 It can be observed that the procedure @code{Unused} and the object
10967 @code{Unused_Data} are removed by the linker when using the
10968 appropriate options.
10969
10970 @c ********************************
10971 @node Renaming Files Using gnatchop
10972 @chapter Renaming Files Using @code{gnatchop}
10973 @findex gnatchop
10974
10975 @noindent
10976 This chapter discusses how to handle files with multiple units by using
10977 the @code{gnatchop} utility. This utility is also useful in renaming
10978 files to meet the standard GNAT default file naming conventions.
10979
10980 @menu
10981 * Handling Files with Multiple Units::
10982 * Operating gnatchop in Compilation Mode::
10983 * Command Line for gnatchop::
10984 * Switches for gnatchop::
10985 * Examples of gnatchop Usage::
10986 @end menu
10987
10988 @node Handling Files with Multiple Units
10989 @section Handling Files with Multiple Units
10990
10991 @noindent
10992 The basic compilation model of GNAT requires that a file submitted to the
10993 compiler have only one unit and there be a strict correspondence
10994 between the file name and the unit name.
10995
10996 The @code{gnatchop} utility allows both of these rules to be relaxed,
10997 allowing GNAT to process files which contain multiple compilation units
10998 and files with arbitrary file names. @code{gnatchop}
10999 reads the specified file and generates one or more output files,
11000 containing one unit per file. The unit and the file name correspond,
11001 as required by GNAT.
11002
11003 If you want to permanently restructure a set of ``foreign'' files so that
11004 they match the GNAT rules, and do the remaining development using the
11005 GNAT structure, you can simply use @command{gnatchop} once, generate the
11006 new set of files and work with them from that point on.
11007
11008 Alternatively, if you want to keep your files in the ``foreign'' format,
11009 perhaps to maintain compatibility with some other Ada compilation
11010 system, you can set up a procedure where you use @command{gnatchop} each
11011 time you compile, regarding the source files that it writes as temporary
11012 files that you throw away.
11013
11014 Note that if your file containing multiple units starts with a byte order
11015 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11016 will each start with a copy of this BOM, meaning that they can be compiled
11017 automatically in UTF-8 mode without needing to specify an explicit encoding.
11018
11019 @node Operating gnatchop in Compilation Mode
11020 @section Operating gnatchop in Compilation Mode
11021
11022 @noindent
11023 The basic function of @code{gnatchop} is to take a file with multiple units
11024 and split it into separate files. The boundary between files is reasonably
11025 clear, except for the issue of comments and pragmas. In default mode, the
11026 rule is that any pragmas between units belong to the previous unit, except
11027 that configuration pragmas always belong to the following unit. Any comments
11028 belong to the following unit. These rules
11029 almost always result in the right choice of
11030 the split point without needing to mark it explicitly and most users will
11031 find this default to be what they want. In this default mode it is incorrect to
11032 submit a file containing only configuration pragmas, or one that ends in
11033 configuration pragmas, to @code{gnatchop}.
11034
11035 However, using a special option to activate ``compilation mode'',
11036 @code{gnatchop}
11037 can perform another function, which is to provide exactly the semantics
11038 required by the RM for handling of configuration pragmas in a compilation.
11039 In the absence of configuration pragmas (at the main file level), this
11040 option has no effect, but it causes such configuration pragmas to be handled
11041 in a quite different manner.
11042
11043 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11044 only configuration pragmas, then this file is appended to the
11045 @file{gnat.adc} file in the current directory. This behavior provides
11046 the required behavior described in the RM for the actions to be taken
11047 on submitting such a file to the compiler, namely that these pragmas
11048 should apply to all subsequent compilations in the same compilation
11049 environment. Using GNAT, the current directory, possibly containing a
11050 @file{gnat.adc} file is the representation
11051 of a compilation environment. For more information on the
11052 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11053
11054 Second, in compilation mode, if @code{gnatchop}
11055 is given a file that starts with
11056 configuration pragmas, and contains one or more units, then these
11057 configuration pragmas are prepended to each of the chopped files. This
11058 behavior provides the required behavior described in the RM for the
11059 actions to be taken on compiling such a file, namely that the pragmas
11060 apply to all units in the compilation, but not to subsequently compiled
11061 units.
11062
11063 Finally, if configuration pragmas appear between units, they are appended
11064 to the previous unit. This results in the previous unit being illegal,
11065 since the compiler does not accept configuration pragmas that follow
11066 a unit. This provides the required RM behavior that forbids configuration
11067 pragmas other than those preceding the first compilation unit of a
11068 compilation.
11069
11070 For most purposes, @code{gnatchop} will be used in default mode. The
11071 compilation mode described above is used only if you need exactly
11072 accurate behavior with respect to compilations, and you have files
11073 that contain multiple units and configuration pragmas. In this
11074 circumstance the use of @code{gnatchop} with the compilation mode
11075 switch provides the required behavior, and is for example the mode
11076 in which GNAT processes the ACVC tests.
11077
11078 @node Command Line for gnatchop
11079 @section Command Line for @code{gnatchop}
11080
11081 @noindent
11082 The @code{gnatchop} command has the form:
11083
11084 @smallexample
11085 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11086       @ovar{directory}
11087 @end smallexample
11088
11089 @noindent
11090 The only required argument is the file name of the file to be chopped.
11091 There are no restrictions on the form of this file name. The file itself
11092 contains one or more Ada units, in normal GNAT format, concatenated
11093 together. As shown, more than one file may be presented to be chopped.
11094
11095 When run in default mode, @code{gnatchop} generates one output file in
11096 the current directory for each unit in each of the files.
11097
11098 @var{directory}, if specified, gives the name of the directory to which
11099 the output files will be written. If it is not specified, all files are
11100 written to the current directory.
11101
11102 For example, given a
11103 file called @file{hellofiles} containing
11104
11105 @smallexample @c ada
11106 @group
11107 @cartouche
11108 procedure hello;
11109
11110 with Text_IO; use Text_IO;
11111 procedure hello is
11112 begin
11113    Put_Line ("Hello");
11114 end hello;
11115 @end cartouche
11116 @end group
11117 @end smallexample
11118
11119 @noindent
11120 the command
11121
11122 @smallexample
11123 $ gnatchop ^hellofiles^HELLOFILES.^
11124 @end smallexample
11125
11126 @noindent
11127 generates two files in the current directory, one called
11128 @file{hello.ads} containing the single line that is the procedure spec,
11129 and the other called @file{hello.adb} containing the remaining text. The
11130 original file is not affected. The generated files can be compiled in
11131 the normal manner.
11132
11133 @noindent
11134 When gnatchop is invoked on a file that is empty or that contains only empty
11135 lines and/or comments, gnatchop will not fail, but will not produce any
11136 new sources.
11137
11138 For example, given a
11139 file called @file{toto.txt} containing
11140
11141 @smallexample @c ada
11142 @group
11143 @cartouche
11144 --  Just a comment
11145 @end cartouche
11146 @end group
11147 @end smallexample
11148
11149 @noindent
11150 the command
11151
11152 @smallexample
11153 $ gnatchop ^toto.txt^TOT.TXT^
11154 @end smallexample
11155
11156 @noindent
11157 will not produce any new file and will result in the following warnings:
11158
11159 @smallexample
11160 toto.txt:1:01: warning: empty file, contains no compilation units
11161 no compilation units found
11162 no source files written
11163 @end smallexample
11164
11165 @node Switches for gnatchop
11166 @section Switches for @code{gnatchop}
11167
11168 @noindent
11169 @command{gnatchop} recognizes the following switches:
11170
11171 @table @option
11172 @c !sort!
11173
11174 @item --version
11175 @cindex @option{--version} @command{gnatchop}
11176 Display Copyright and version, then exit disregarding all other options.
11177
11178 @item --help
11179 @cindex @option{--help} @command{gnatchop}
11180 If @option{--version} was not used, display usage, then exit disregarding
11181 all other options.
11182
11183 @item ^-c^/COMPILATION^
11184 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11185 Causes @code{gnatchop} to operate in compilation mode, in which
11186 configuration pragmas are handled according to strict RM rules. See
11187 previous section for a full description of this mode.
11188
11189 @ifclear vms
11190 @item -gnat@var{xxx}
11191 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11192 used to parse the given file. Not all @var{xxx} options make sense,
11193 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11194 process a source file that uses Latin-2 coding for identifiers.
11195 @end ifclear
11196
11197 @item ^-h^/HELP^
11198 Causes @code{gnatchop} to generate a brief help summary to the standard
11199 output file showing usage information.
11200
11201 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11202 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11203 Limit generated file names to the specified number @code{mm}
11204 of characters.
11205 This is useful if the
11206 resulting set of files is required to be interoperable with systems
11207 which limit the length of file names.
11208 @ifset vms
11209 If no value is given, or
11210 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11211 a default of 39, suitable for OpenVMS Alpha
11212 Systems, is assumed
11213 @end ifset
11214 @ifclear vms
11215 No space is allowed between the @option{-k} and the numeric value. The numeric
11216 value may be omitted in which case a default of @option{-k8},
11217 suitable for use
11218 with DOS-like file systems, is used. If no @option{-k} switch
11219 is present then
11220 there is no limit on the length of file names.
11221 @end ifclear
11222
11223 @item ^-p^/PRESERVE^
11224 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11225 Causes the file ^modification^creation^ time stamp of the input file to be
11226 preserved and used for the time stamp of the output file(s). This may be
11227 useful for preserving coherency of time stamps in an environment where
11228 @code{gnatchop} is used as part of a standard build process.
11229
11230 @item ^-q^/QUIET^
11231 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11232 Causes output of informational messages indicating the set of generated
11233 files to be suppressed. Warnings and error messages are unaffected.
11234
11235 @item ^-r^/REFERENCE^
11236 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11237 @findex Source_Reference
11238 Generate @code{Source_Reference} pragmas. Use this switch if the output
11239 files are regarded as temporary and development is to be done in terms
11240 of the original unchopped file. This switch causes
11241 @code{Source_Reference} pragmas to be inserted into each of the
11242 generated files to refers back to the original file name and line number.
11243 The result is that all error messages refer back to the original
11244 unchopped file.
11245 In addition, the debugging information placed into the object file (when
11246 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11247 specified)
11248 also refers back to this original file so that tools like profilers and
11249 debuggers will give information in terms of the original unchopped file.
11250
11251 If the original file to be chopped itself contains
11252 a @code{Source_Reference}
11253 pragma referencing a third file, then gnatchop respects
11254 this pragma, and the generated @code{Source_Reference} pragmas
11255 in the chopped file refer to the original file, with appropriate
11256 line numbers. This is particularly useful when @code{gnatchop}
11257 is used in conjunction with @code{gnatprep} to compile files that
11258 contain preprocessing statements and multiple units.
11259
11260 @item ^-v^/VERBOSE^
11261 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11262 Causes @code{gnatchop} to operate in verbose mode. The version
11263 number and copyright notice are output, as well as exact copies of
11264 the gnat1 commands spawned to obtain the chop control information.
11265
11266 @item ^-w^/OVERWRITE^
11267 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11268 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11269 fatal error if there is already a file with the same name as a
11270 file it would otherwise output, in other words if the files to be
11271 chopped contain duplicated units. This switch bypasses this
11272 check, and causes all but the last instance of such duplicated
11273 units to be skipped.
11274
11275 @ifclear vms
11276 @item --GCC=@var{xxxx}
11277 @cindex @option{--GCC=} (@code{gnatchop})
11278 Specify the path of the GNAT parser to be used. When this switch is used,
11279 no attempt is made to add the prefix to the GNAT parser executable.
11280 @end ifclear
11281 @end table
11282
11283 @node Examples of gnatchop Usage
11284 @section Examples of @code{gnatchop} Usage
11285
11286 @table @code
11287 @ifset vms
11288 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11289 @end ifset
11290 @ifclear vms
11291 @item gnatchop -w hello_s.ada prerelease/files
11292 @end ifclear
11293
11294 Chops the source file @file{hello_s.ada}. The output files will be
11295 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11296 overwriting any
11297 files with matching names in that directory (no files in the current
11298 directory are modified).
11299
11300 @item gnatchop ^archive^ARCHIVE.^
11301 Chops the source file @file{^archive^ARCHIVE.^}
11302 into the current directory. One
11303 useful application of @code{gnatchop} is in sending sets of sources
11304 around, for example in email messages. The required sources are simply
11305 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11306 command), and then
11307 @command{gnatchop} is used at the other end to reconstitute the original
11308 file names.
11309
11310 @item gnatchop file1 file2 file3 direc
11311 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11312 the resulting files in the directory @file{direc}. Note that if any units
11313 occur more than once anywhere within this set of files, an error message
11314 is generated, and no files are written. To override this check, use the
11315 @option{^-w^/OVERWRITE^} switch,
11316 in which case the last occurrence in the last file will
11317 be the one that is output, and earlier duplicate occurrences for a given
11318 unit will be skipped.
11319 @end table
11320
11321 @node Configuration Pragmas
11322 @chapter Configuration Pragmas
11323 @cindex Configuration pragmas
11324 @cindex Pragmas, configuration
11325
11326 @noindent
11327 Configuration pragmas include those pragmas described as
11328 such in the Ada Reference Manual, as well as
11329 implementation-dependent pragmas that are configuration pragmas.
11330 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11331 for details on these additional GNAT-specific configuration pragmas.
11332 Most notably, the pragma @code{Source_File_Name}, which allows
11333 specifying non-default names for source files, is a configuration
11334 pragma. The following is a complete list of configuration pragmas
11335 recognized by GNAT:
11336
11337 @smallexample
11338    Ada_83
11339    Ada_95
11340    Ada_05
11341    Ada_2005
11342    Assertion_Policy
11343    Assume_No_Invalid_Values
11344    C_Pass_By_Copy
11345    Check_Name
11346    Check_Policy
11347    Compile_Time_Error
11348    Compile_Time_Warning
11349    Compiler_Unit
11350    Component_Alignment
11351    Convention_Identifier
11352    Debug_Policy
11353    Detect_Blocking
11354    Discard_Names
11355    Elaboration_Checks
11356    Eliminate
11357    Extend_System
11358    Extensions_Allowed
11359    External_Name_Casing
11360    Fast_Math
11361    Favor_Top_Level
11362    Float_Representation
11363    Implicit_Packing
11364    Initialize_Scalars
11365    Interrupt_State
11366    License
11367    Locking_Policy
11368    Long_Float
11369    No_Run_Time
11370    No_Strict_Aliasing
11371    Normalize_Scalars
11372    Optimize_Alignment
11373    Persistent_BSS
11374    Polling
11375    Priority_Specific_Dispatching
11376    Profile
11377    Profile_Warnings
11378    Propagate_Exceptions
11379    Queuing_Policy
11380    Ravenscar
11381    Restricted_Run_Time
11382    Restrictions
11383    Restrictions_Warnings
11384    Reviewable
11385    Source_File_Name
11386    Source_File_Name_Project
11387    Style_Checks
11388    Suppress
11389    Suppress_Exception_Locations
11390    Task_Dispatching_Policy
11391    Universal_Data
11392    Unsuppress
11393    Use_VADS_Size
11394    Validity_Checks
11395    Warnings
11396    Wide_Character_Encoding
11397
11398 @end smallexample
11399
11400 @menu
11401 * Handling of Configuration Pragmas::
11402 * The Configuration Pragmas Files::
11403 @end menu
11404
11405 @node Handling of Configuration Pragmas
11406 @section Handling of Configuration Pragmas
11407
11408 Configuration pragmas may either appear at the start of a compilation
11409 unit, in which case they apply only to that unit, or they may apply to
11410 all compilations performed in a given compilation environment.
11411
11412 GNAT also provides the @code{gnatchop} utility to provide an automatic
11413 way to handle configuration pragmas following the semantics for
11414 compilations (that is, files with multiple units), described in the RM.
11415 See @ref{Operating gnatchop in Compilation Mode} for details.
11416 However, for most purposes, it will be more convenient to edit the
11417 @file{gnat.adc} file that contains configuration pragmas directly,
11418 as described in the following section.
11419
11420 @node The Configuration Pragmas Files
11421 @section The Configuration Pragmas Files
11422 @cindex @file{gnat.adc}
11423
11424 @noindent
11425 In GNAT a compilation environment is defined by the current
11426 directory at the time that a compile command is given. This current
11427 directory is searched for a file whose name is @file{gnat.adc}. If
11428 this file is present, it is expected to contain one or more
11429 configuration pragmas that will be applied to the current compilation.
11430 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11431 considered.
11432
11433 Configuration pragmas may be entered into the @file{gnat.adc} file
11434 either by running @code{gnatchop} on a source file that consists only of
11435 configuration pragmas, or more conveniently  by
11436 direct editing of the @file{gnat.adc} file, which is a standard format
11437 source file.
11438
11439 In addition to @file{gnat.adc}, additional files containing configuration
11440 pragmas may be applied to the current compilation using the switch
11441 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11442 contains only configuration pragmas. These configuration pragmas are
11443 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11444 is present and switch @option{-gnatA} is not used).
11445
11446 It is allowed to specify several switches @option{-gnatec}, all of which
11447 will be taken into account.
11448
11449 If you are using project file, a separate mechanism is provided using
11450 project attributes, see @ref{Specifying Configuration Pragmas} for more
11451 details.
11452
11453 @ifset vms
11454 Of special interest to GNAT OpenVMS Alpha is the following
11455 configuration pragma:
11456
11457 @smallexample @c ada
11458 @cartouche
11459 pragma Extend_System (Aux_DEC);
11460 @end cartouche
11461 @end smallexample
11462
11463 @noindent
11464 In the presence of this pragma, GNAT adds to the definition of the
11465 predefined package SYSTEM all the additional types and subprograms that are
11466 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11467 @end ifset
11468
11469 @node Handling Arbitrary File Naming Conventions Using gnatname
11470 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11471 @cindex Arbitrary File Naming Conventions
11472
11473 @menu
11474 * Arbitrary File Naming Conventions::
11475 * Running gnatname::
11476 * Switches for gnatname::
11477 * Examples of gnatname Usage::
11478 @end menu
11479
11480 @node Arbitrary File Naming Conventions
11481 @section Arbitrary File Naming Conventions
11482
11483 @noindent
11484 The GNAT compiler must be able to know the source file name of a compilation
11485 unit.  When using the standard GNAT default file naming conventions
11486 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11487 does not need additional information.
11488
11489 @noindent
11490 When the source file names do not follow the standard GNAT default file naming
11491 conventions, the GNAT compiler must be given additional information through
11492 a configuration pragmas file (@pxref{Configuration Pragmas})
11493 or a project file.
11494 When the non-standard file naming conventions are well-defined,
11495 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11496 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11497 if the file naming conventions are irregular or arbitrary, a number
11498 of pragma @code{Source_File_Name} for individual compilation units
11499 must be defined.
11500 To help maintain the correspondence between compilation unit names and
11501 source file names within the compiler,
11502 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11503 set of files.
11504
11505 @node Running gnatname
11506 @section Running @code{gnatname}
11507
11508 @noindent
11509 The usual form of the @code{gnatname} command is
11510
11511 @smallexample
11512 $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11513       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11514 @end smallexample
11515
11516 @noindent
11517 All of the arguments are optional. If invoked without any argument,
11518 @code{gnatname} will display its usage.
11519
11520 @noindent
11521 When used with at least one naming pattern, @code{gnatname} will attempt to
11522 find all the compilation units in files that follow at least one of the
11523 naming patterns. To find these compilation units,
11524 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11525 regular files.
11526
11527 @noindent
11528 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11529 Each Naming Pattern is enclosed between double quotes.
11530 A Naming Pattern is a regular expression similar to the wildcard patterns
11531 used in file names by the Unix shells or the DOS prompt.
11532
11533 @noindent
11534 @code{gnatname} may be called with several sections of directories/patterns.
11535 Sections are separated by switch @code{--and}. In each section, there must be
11536 at least one pattern. If no directory is specified in a section, the current
11537 directory (or the project directory is @code{-P} is used) is implied.
11538 The options other that the directory switches and the patterns apply globally
11539 even if they are in different sections.
11540
11541 @noindent
11542 Examples of Naming Patterns are
11543
11544 @smallexample
11545    "*.[12].ada"
11546    "*.ad[sb]*"
11547    "body_*"    "spec_*"
11548 @end smallexample
11549
11550 @noindent
11551 For a more complete description of the syntax of Naming Patterns,
11552 see the second kind of regular expressions described in @file{g-regexp.ads}
11553 (the ``Glob'' regular expressions).
11554
11555 @noindent
11556 When invoked with no switch @code{-P}, @code{gnatname} will create a
11557 configuration pragmas file @file{gnat.adc} in the current working directory,
11558 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11559 unit.
11560
11561 @node Switches for gnatname
11562 @section Switches for @code{gnatname}
11563
11564 @noindent
11565 Switches for @code{gnatname} must precede any specified Naming Pattern.
11566
11567 @noindent
11568 You may specify any of the following switches to @code{gnatname}:
11569
11570 @table @option
11571 @c !sort!
11572
11573 @item --version
11574 @cindex @option{--version} @command{gnatname}
11575 Display Copyright and version, then exit disregarding all other options.
11576
11577 @item --help
11578 @cindex @option{--help} @command{gnatname}
11579 If @option{--version} was not used, display usage, then exit disregarding
11580 all other options.
11581
11582 @item --and
11583 Start another section of directories/patterns.
11584
11585 @item ^-c^/CONFIG_FILE=^@file{file}
11586 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11587 Create a configuration pragmas file @file{file} (instead of the default
11588 @file{gnat.adc}).
11589 @ifclear vms
11590 There may be zero, one or more space between @option{-c} and
11591 @file{file}.
11592 @end ifclear
11593 @file{file} may include directory information. @file{file} must be
11594 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11595 When a switch @option{^-c^/CONFIG_FILE^} is
11596 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11597
11598 @item ^-d^/SOURCE_DIRS=^@file{dir}
11599 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11600 Look for source files in directory @file{dir}. There may be zero, one or more
11601 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11602 When a switch @option{^-d^/SOURCE_DIRS^}
11603 is specified, the current working directory will not be searched for source
11604 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11605 or @option{^-D^/DIR_FILES^} switch.
11606 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11607 If @file{dir} is a relative path, it is relative to the directory of
11608 the configuration pragmas file specified with switch
11609 @option{^-c^/CONFIG_FILE^},
11610 or to the directory of the project file specified with switch
11611 @option{^-P^/PROJECT_FILE^} or,
11612 if neither switch @option{^-c^/CONFIG_FILE^}
11613 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11614 current working directory. The directory
11615 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11616
11617 @item ^-D^/DIRS_FILE=^@file{file}
11618 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11619 Look for source files in all directories listed in text file @file{file}.
11620 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11621 and @file{file}.
11622 @file{file} must be an existing, readable text file.
11623 Each nonempty line in @file{file} must be a directory.
11624 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11625 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11626 @file{file}.
11627
11628 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11629 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11630 Foreign patterns. Using this switch, it is possible to add sources of languages
11631 other than Ada to the list of sources of a project file.
11632 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11633 For example,
11634 @smallexample
11635 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11636 @end smallexample
11637 @noindent
11638 will look for Ada units in all files with the @file{.ada} extension,
11639 and will add to the list of file for project @file{prj.gpr} the C files
11640 with extension @file{.^c^C^}.
11641
11642 @item ^-h^/HELP^
11643 @cindex @option{^-h^/HELP^} (@code{gnatname})
11644 Output usage (help) information. The output is written to @file{stdout}.
11645
11646 @item ^-P^/PROJECT_FILE=^@file{proj}
11647 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11648 Create or update project file @file{proj}. There may be zero, one or more space
11649 between @option{-P} and @file{proj}. @file{proj} may include directory
11650 information. @file{proj} must be writable.
11651 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11652 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11653 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11654
11655 @item ^-v^/VERBOSE^
11656 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11657 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11658 This includes name of the file written, the name of the directories to search
11659 and, for each file in those directories whose name matches at least one of
11660 the Naming Patterns, an indication of whether the file contains a unit,
11661 and if so the name of the unit.
11662
11663 @item ^-v -v^/VERBOSE /VERBOSE^
11664 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11665 Very Verbose mode. In addition to the output produced in verbose mode,
11666 for each file in the searched directories whose name matches none of
11667 the Naming Patterns, an indication is given that there is no match.
11668
11669 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11670 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11671 Excluded patterns. Using this switch, it is possible to exclude some files
11672 that would match the name patterns. For example,
11673 @smallexample
11674 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11675 @end smallexample
11676 @noindent
11677 will look for Ada units in all files with the @file{.ada} extension,
11678 except those whose names end with @file{_nt.ada}.
11679
11680 @end table
11681
11682 @node Examples of gnatname Usage
11683 @section Examples of @code{gnatname} Usage
11684
11685 @ifset vms
11686 @smallexample
11687 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11688 @end smallexample
11689 @end ifset
11690
11691 @ifclear vms
11692 @smallexample
11693 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11694 @end smallexample
11695 @end ifclear
11696
11697 @noindent
11698 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11699 and be writable. In addition, the directory
11700 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11701 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11702
11703 @ifclear vms
11704 Note the optional spaces after @option{-c} and @option{-d}.
11705 @end ifclear
11706
11707 @smallexample
11708 @ifclear vms
11709 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11710   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11711 @end ifclear
11712 @ifset vms
11713 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11714   /EXCLUDED_PATTERN=*_nt_body.ada
11715   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11716   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11717 @end ifset
11718 @end smallexample
11719
11720 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11721 even in conjunction with one or several switches
11722 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11723 are used in this example.
11724
11725 @c *****************************************
11726 @c * G N A T  P r o j e c t  M a n a g e r *
11727 @c *****************************************
11728 @node GNAT Project Manager
11729 @chapter GNAT Project Manager
11730
11731 @menu
11732 * Introduction::
11733 * Examples of Project Files::
11734 * Project File Syntax::
11735 * Objects and Sources in Project Files::
11736 * Importing Projects::
11737 * Project Extension::
11738 * Project Hierarchy Extension::
11739 * External References in Project Files::
11740 * Packages in Project Files::
11741 * Variables from Imported Projects::
11742 * Naming Schemes::
11743 * Library Projects::
11744 * Stand-alone Library Projects::
11745 * Switches Related to Project Files::
11746 * Tools Supporting Project Files::
11747 * An Extended Example::
11748 * Project File Complete Syntax::
11749 @end menu
11750
11751 @c ****************
11752 @c * Introduction *
11753 @c ****************
11754
11755 @node Introduction
11756 @section Introduction
11757
11758 @noindent
11759 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11760 you to manage complex builds involving a number of source files, directories,
11761 and compilation options for different system configurations. In particular,
11762 project files allow you to specify:
11763 @itemize @bullet
11764 @item
11765 The directory or set of directories containing the source files, and/or the
11766 names of the specific source files themselves
11767 @item
11768 The directory in which the compiler's output
11769 (@file{ALI} files, object files, tree files) is to be placed
11770 @item
11771 The directory in which the executable programs is to be placed
11772 @item
11773 ^Switch^Switch^ settings for any of the project-enabled tools
11774 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11775 @code{gnatfind}); you can apply these settings either globally or to individual
11776 compilation units.
11777 @item
11778 The source files containing the main subprogram(s) to be built
11779 @item
11780 The source programming language(s) (currently Ada and/or C)
11781 @item
11782 Source file naming conventions; you can specify these either globally or for
11783 individual compilation units
11784 @end itemize
11785
11786 @menu
11787 * Project Files::
11788 @end menu
11789
11790 @node Project Files
11791 @subsection Project Files
11792
11793 @noindent
11794 Project files are written in a syntax close to that of Ada, using  familiar
11795 notions such as packages, context clauses, declarations, default values,
11796 assignments, and inheritance. Finally, project files can be built
11797 hierarchically from other project files, simplifying complex system
11798 integration and project reuse.
11799
11800 A @dfn{project} is a specific set of values for various compilation properties.
11801 The settings for a given project are described by means of
11802 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11803 Property values in project files are either strings or lists of strings.
11804 Properties that are not explicitly set receive default values.  A project
11805 file may interrogate the values of @dfn{external variables} (user-defined
11806 command-line switches or environment variables), and it may specify property
11807 settings conditionally, based on the value of such variables.
11808
11809 In simple cases, a project's source files depend only on other source files
11810 in the same project, or on the predefined libraries.  (@emph{Dependence} is
11811 used in
11812 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
11813 the Project Manager also allows more sophisticated arrangements,
11814 where the source files in one project depend on source files in other
11815 projects:
11816 @itemize @bullet
11817 @item
11818 One project can @emph{import} other projects containing needed source files.
11819 @item
11820 You can organize GNAT projects in a hierarchy: a @emph{child} project
11821 can extend a @emph{parent} project, inheriting the parent's source files and
11822 optionally overriding any of them with alternative versions
11823 @end itemize
11824
11825 @noindent
11826 More generally, the Project Manager lets you structure large development
11827 efforts into hierarchical subsystems, where build decisions are delegated
11828 to the subsystem level, and thus different compilation environments
11829 (^switch^switch^ settings) used for different subsystems.
11830
11831 The Project Manager is invoked through the
11832 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11833 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11834 @ifclear vms
11835 There may be zero, one or more spaces between @option{-P} and
11836 @option{@emph{projectfile}}.
11837 @end ifclear
11838 If you want to define (on the command line) an external variable that is
11839 queried by the project file, you must use the
11840 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11841 The Project Manager parses and interprets the project file, and drives the
11842 invoked tool based on the project settings.
11843
11844 The Project Manager supports a wide range of development strategies,
11845 for systems of all sizes.  Here are some typical practices that are
11846 easily handled:
11847 @itemize @bullet
11848 @item
11849 Using a common set of source files, but generating object files in different
11850 directories via different ^switch^switch^ settings
11851 @item
11852 Using a mostly-shared set of source files, but with different versions of
11853 some unit or units
11854 @end itemize
11855
11856 @noindent
11857 The destination of an executable can be controlled inside a project file
11858 using the @option{^-o^-o^}
11859 ^switch^switch^.
11860 In the absence of such a ^switch^switch^ either inside
11861 the project file or on the command line, any executable files generated by
11862 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11863 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11864 in the object directory of the project.
11865
11866 You can use project files to achieve some of the effects of a source
11867 versioning system (for example, defining separate projects for
11868 the different sets of sources that comprise different releases) but the
11869 Project Manager is independent of any source configuration management tools
11870 that might be used by the developers.
11871
11872 The next section introduces the main features of GNAT's project facility
11873 through a sequence of examples; subsequent sections will present the syntax
11874 and semantics in more detail. A more formal description of the project
11875 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11876 Reference Manual}.
11877
11878 @c *****************************
11879 @c * Examples of Project Files *
11880 @c *****************************
11881
11882 @node Examples of Project Files
11883 @section Examples of Project Files
11884 @noindent
11885 This section illustrates some of the typical uses of project files and
11886 explains their basic structure and behavior.
11887
11888 @menu
11889 * Common Sources with Different ^Switches^Switches^ and Directories::
11890 * Using External Variables::
11891 * Importing Other Projects::
11892 * Extending a Project::
11893 @end menu
11894
11895 @node Common Sources with Different ^Switches^Switches^ and Directories
11896 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11897
11898 @menu
11899 * Source Files::
11900 * Specifying the Object Directory::
11901 * Specifying the Exec Directory::
11902 * Project File Packages::
11903 * Specifying ^Switch^Switch^ Settings::
11904 * Main Subprograms::
11905 * Executable File Names::
11906 * Source File Naming Conventions::
11907 * Source Language(s)::
11908 @end menu
11909
11910 @noindent
11911 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11912 @file{proc.adb} are in the @file{/common} directory.  The file
11913 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11914 package @code{Pack}.  We want to compile these source files under two sets
11915 of ^switches^switches^:
11916 @itemize @bullet
11917 @item
11918 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11919 and the @option{^-gnata^-gnata^},
11920 @option{^-gnato^-gnato^},
11921 and @option{^-gnatE^-gnatE^} switches to the
11922 compiler; the compiler's output is to appear in @file{/common/debug}
11923 @item
11924 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11925 to the compiler; the compiler's output is to appear in @file{/common/release}
11926 @end itemize
11927
11928 @noindent
11929 The GNAT project files shown below, respectively @file{debug.gpr} and
11930 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11931
11932 Schematically:
11933 @smallexample
11934 @group
11935 ^/common^[COMMON]^
11936   debug.gpr
11937   release.gpr
11938   pack.ads
11939   pack.adb
11940   proc.adb
11941 @end group
11942 @group
11943 ^/common/debug^[COMMON.DEBUG]^
11944   proc.ali, proc.o
11945   pack.ali, pack.o
11946 @end group
11947 @group
11948 ^/common/release^[COMMON.RELEASE]^
11949   proc.ali, proc.o
11950   pack.ali, pack.o
11951 @end group
11952 @end smallexample
11953 Here are the corresponding project files:
11954
11955 @smallexample @c projectfile
11956 @group
11957 project Debug is
11958   for Object_Dir use "debug";
11959   for Main use ("proc");
11960
11961   package Builder is
11962     for ^Default_Switches^Default_Switches^ ("Ada")
11963         use ("^-g^-g^");
11964     for Executable ("proc.adb") use "proc1";
11965   end Builder;
11966 @end group
11967
11968 @group
11969   package Compiler is
11970     for ^Default_Switches^Default_Switches^ ("Ada")
11971        use ("-fstack-check",
11972             "^-gnata^-gnata^",
11973             "^-gnato^-gnato^",
11974             "^-gnatE^-gnatE^");
11975   end Compiler;
11976 end Debug;
11977 @end group
11978 @end smallexample
11979
11980 @smallexample @c projectfile
11981 @group
11982 project Release is
11983   for Object_Dir use "release";
11984   for Exec_Dir use ".";
11985   for Main use ("proc");
11986
11987   package Compiler is
11988     for ^Default_Switches^Default_Switches^ ("Ada")
11989         use ("^-O2^-O2^");
11990   end Compiler;
11991 end Release;
11992 @end group
11993 @end smallexample
11994
11995 @noindent
11996 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11997 insensitive), and analogously the project defined by @file{release.gpr} is
11998 @code{"Release"}.  For consistency the file should have the same name as the
11999 project, and the project file's extension should be @code{"gpr"}. These
12000 conventions are not required, but a warning is issued if they are not followed.
12001
12002 If the current directory is @file{^/temp^[TEMP]^}, then the command
12003 @smallexample
12004 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
12005 @end smallexample
12006
12007 @noindent
12008 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
12009 as well as the @code{^proc1^PROC1.EXE^} executable,
12010 using the ^switch^switch^ settings defined in the project file.
12011
12012 Likewise, the command
12013 @smallexample
12014 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
12015 @end smallexample
12016
12017 @noindent
12018 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
12019 and the @code{^proc^PROC.EXE^}
12020 executable in @file{^/common^[COMMON]^},
12021 using the ^switch^switch^ settings from the project file.
12022
12023 @node Source Files
12024 @unnumberedsubsubsec Source Files
12025
12026 @noindent
12027 If a project file does not explicitly specify a set of source directories or
12028 a set of source files, then by default the project's source files are the
12029 Ada source files in the project file directory.  Thus @file{pack.ads},
12030 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
12031
12032 @node Specifying the Object Directory
12033 @unnumberedsubsubsec Specifying the Object Directory
12034
12035 @noindent
12036 Several project properties are modeled by Ada-style @emph{attributes};
12037 a property is defined by supplying the equivalent of an Ada attribute
12038 definition clause in the project file.
12039 A project's object directory is another such a property; the corresponding
12040 attribute is @code{Object_Dir}, and its value is also a string expression,
12041 specified either as absolute or relative. In the later case,
12042 it is relative to the project file directory. Thus the compiler's
12043 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
12044 (for the @code{Debug} project)
12045 and to @file{^/common/release^[COMMON.RELEASE]^}
12046 (for the @code{Release} project).
12047 If @code{Object_Dir} is not specified, then the default is the project file
12048 directory itself.
12049
12050 @node Specifying the Exec Directory
12051 @unnumberedsubsubsec Specifying the Exec Directory
12052
12053 @noindent
12054 A project's exec directory is another property; the corresponding
12055 attribute is @code{Exec_Dir}, and its value is also a string expression,
12056 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
12057 then the default is the object directory (which may also be the project file
12058 directory if attribute @code{Object_Dir} is not specified). Thus the executable
12059 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
12060 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
12061 and in @file{^/common^[COMMON]^} for the @code{Release} project.
12062
12063 @node Project File Packages
12064 @unnumberedsubsubsec Project File Packages
12065
12066 @noindent
12067 A GNAT tool that is integrated with the Project Manager is modeled by a
12068 corresponding package in the project file. In the example above,
12069 The @code{Debug} project defines the packages @code{Builder}
12070 (for @command{gnatmake}) and @code{Compiler};
12071 the @code{Release} project defines only the @code{Compiler} package.
12072
12073 The Ada-like package syntax is not to be taken literally.  Although packages in
12074 project files bear a surface resemblance to packages in Ada source code, the
12075 notation is simply a way to convey a grouping of properties for a named
12076 entity.  Indeed, the package names permitted in project files are restricted
12077 to a predefined set, corresponding to the project-aware tools, and the contents
12078 of packages are limited to a small set of constructs.
12079 The packages in the example above contain attribute definitions.
12080
12081 @node Specifying ^Switch^Switch^ Settings
12082 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
12083
12084 @noindent
12085 ^Switch^Switch^ settings for a project-aware tool can be specified through
12086 attributes in the package that corresponds to the tool.
12087 The example above illustrates one of the relevant attributes,
12088 @code{^Default_Switches^Default_Switches^}, which is defined in packages
12089 in both project files.
12090 Unlike simple attributes like @code{Source_Dirs},
12091 @code{^Default_Switches^Default_Switches^} is
12092 known as an @emph{associative array}.  When you define this attribute, you must
12093 supply an ``index'' (a literal string), and the effect of the attribute
12094 definition is to set the value of the array at the specified index.
12095 For the @code{^Default_Switches^Default_Switches^} attribute,
12096 the index is a programming language (in our case, Ada),
12097 and the value specified (after @code{use}) must be a list
12098 of string expressions.
12099
12100 The attributes permitted in project files are restricted to a predefined set.
12101 Some may appear at project level, others in packages.
12102 For any attribute that is an associative array, the index must always be a
12103 literal string, but the restrictions on this string (e.g., a file name or a
12104 language name) depend on the individual attribute.
12105 Also depending on the attribute, its specified value will need to be either a
12106 string or a string list.
12107
12108 In the @code{Debug} project, we set the switches for two tools,
12109 @command{gnatmake} and the compiler, and thus we include the two corresponding
12110 packages; each package defines the @code{^Default_Switches^Default_Switches^}
12111 attribute with index @code{"Ada"}.
12112 Note that the package corresponding to
12113 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
12114 similar, but only includes the @code{Compiler} package.
12115
12116 In project @code{Debug} above, the ^switches^switches^ starting with
12117 @option{-gnat} that are specified in package @code{Compiler}
12118 could have been placed in package @code{Builder}, since @command{gnatmake}
12119 transmits all such ^switches^switches^ to the compiler.
12120
12121 @node Main Subprograms
12122 @unnumberedsubsubsec Main Subprograms
12123
12124 @noindent
12125 One of the specifiable properties of a project is a list of files that contain
12126 main subprograms.  This property is captured in the @code{Main} attribute,
12127 whose value is a list of strings.  If a project defines the @code{Main}
12128 attribute, it is not necessary to identify the main subprogram(s) when
12129 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
12130
12131 @node Executable File Names
12132 @unnumberedsubsubsec Executable File Names
12133
12134 @noindent
12135 By default, the executable file name corresponding to a main source is
12136 deduced from the main source file name. Through the attributes
12137 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
12138 it is possible to change this default.
12139 In project @code{Debug} above, the executable file name
12140 for main source @file{^proc.adb^PROC.ADB^} is
12141 @file{^proc1^PROC1.EXE^}.
12142 Attribute @code{Executable_Suffix}, when specified, may change the suffix
12143 of the executable files, when no attribute @code{Executable} applies:
12144 its value replace the platform-specific executable suffix.
12145 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
12146 specify a non-default executable file name when several mains are built at once
12147 in a single @command{gnatmake} command.
12148
12149 @node Source File Naming Conventions
12150 @unnumberedsubsubsec Source File Naming Conventions
12151
12152 @noindent
12153 Since the project files above do not specify any source file naming
12154 conventions, the GNAT defaults are used.  The mechanism for defining source
12155 file naming conventions -- a package named @code{Naming} --
12156 is described below (@pxref{Naming Schemes}).
12157
12158 @node Source Language(s)
12159 @unnumberedsubsubsec Source Language(s)
12160
12161 @noindent
12162 Since the project files do not specify a @code{Languages} attribute, by
12163 default the GNAT tools assume that the language of the project file is Ada.
12164 More generally, a project can comprise source files
12165 in Ada, C, and/or other languages.
12166
12167 @node Using External Variables
12168 @subsection Using External Variables
12169
12170 @noindent
12171 Instead of supplying different project files for debug and release, we can
12172 define a single project file that queries an external variable (set either
12173 on the command line or via an ^environment variable^logical name^) in order to
12174 conditionally define the appropriate settings.  Again, assume that the
12175 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
12176 located in directory @file{^/common^[COMMON]^}.  The following project file,
12177 @file{build.gpr}, queries the external variable named @code{STYLE} and
12178 defines an object directory and ^switch^switch^ settings based on whether
12179 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
12180 the default is @code{"deb"}.
12181
12182 @smallexample @c projectfile
12183 @group
12184 project Build is
12185   for Main use ("proc");
12186
12187   type Style_Type is ("deb", "rel");
12188   Style : Style_Type := external ("STYLE", "deb");
12189
12190   case Style is
12191     when "deb" =>
12192       for Object_Dir use "debug";
12193
12194     when "rel" =>
12195       for Object_Dir use "release";
12196       for Exec_Dir use ".";
12197   end case;
12198 @end group
12199
12200 @group
12201   package Builder is
12202
12203     case Style is
12204       when "deb" =>
12205         for ^Default_Switches^Default_Switches^ ("Ada")
12206             use ("^-g^-g^");
12207         for Executable ("proc") use "proc1";
12208       when others =>
12209         null;
12210     end case;
12211
12212   end Builder;
12213 @end group
12214
12215 @group
12216   package Compiler is
12217
12218     case Style is
12219       when "deb" =>
12220         for ^Default_Switches^Default_Switches^ ("Ada")
12221             use ("^-gnata^-gnata^",
12222                  "^-gnato^-gnato^",
12223                  "^-gnatE^-gnatE^");
12224
12225       when "rel" =>
12226         for ^Default_Switches^Default_Switches^ ("Ada")
12227             use ("^-O2^-O2^");
12228     end case;
12229
12230   end Compiler;
12231
12232 end Build;
12233 @end group
12234 @end smallexample
12235
12236 @noindent
12237 @code{Style_Type} is an example of a @emph{string type}, which is the project
12238 file analog of an Ada enumeration type but whose components are string literals
12239 rather than identifiers.  @code{Style} is declared as a variable of this type.
12240
12241 The form @code{external("STYLE", "deb")} is known as an
12242 @emph{external reference}; its first argument is the name of an
12243 @emph{external variable}, and the second argument is a default value to be
12244 used if the external variable doesn't exist.  You can define an external
12245 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
12246 or you can use ^an environment variable^a logical name^
12247 as an external variable.
12248
12249 Each @code{case} construct is expanded by the Project Manager based on the
12250 value of @code{Style}. Thus the command
12251 @ifclear vms
12252 @smallexample
12253 gnatmake -P/common/build.gpr -XSTYLE=deb
12254 @end smallexample
12255 @end ifclear
12256
12257 @ifset vms
12258 @smallexample
12259 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
12260 @end smallexample
12261 @end ifset
12262
12263 @noindent
12264 is equivalent to the @command{gnatmake} invocation using the project file
12265 @file{debug.gpr} in the earlier example.  So is the command
12266 @smallexample
12267 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
12268 @end smallexample
12269
12270 @noindent
12271 since @code{"deb"} is the default for @code{STYLE}.
12272
12273 Analogously,
12274
12275 @ifclear vms
12276 @smallexample
12277 gnatmake -P/common/build.gpr -XSTYLE=rel
12278 @end smallexample
12279 @end ifclear
12280
12281 @ifset vms
12282 @smallexample
12283 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
12284 @end smallexample
12285 @end ifset
12286
12287 @noindent
12288 is equivalent to the @command{gnatmake} invocation using the project file
12289 @file{release.gpr} in the earlier example.
12290
12291 @node Importing Other Projects
12292 @subsection Importing Other Projects
12293 @cindex @code{ADA_PROJECT_PATH}
12294 @cindex @code{GPR_PROJECT_PATH}
12295
12296 @noindent
12297 A compilation unit in a source file in one project may depend on compilation
12298 units in source files in other projects.  To compile this unit under
12299 control of a project file, the
12300 dependent project must @emph{import} the projects containing the needed source
12301 files.
12302 This effect is obtained using syntax similar to an Ada @code{with} clause,
12303 but where @code{with}ed entities are strings that denote project files.
12304
12305 As an example, suppose that the two projects @code{GUI_Proj} and
12306 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
12307 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
12308 and @file{^/comm^[COMM]^}, respectively.
12309 Suppose that the source files for @code{GUI_Proj} are
12310 @file{gui.ads} and @file{gui.adb}, and that the source files for
12311 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
12312 files is located in its respective project file directory.  Schematically:
12313
12314 @smallexample
12315 @group
12316 ^/gui^[GUI]^
12317   gui_proj.gpr
12318   gui.ads
12319   gui.adb
12320 @end group
12321
12322 @group
12323 ^/comm^[COMM]^
12324   comm_proj.gpr
12325   comm.ads
12326   comm.adb
12327 @end group
12328 @end smallexample
12329
12330 @noindent
12331 We want to develop an application in directory @file{^/app^[APP]^} that
12332 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12333 the corresponding project files (e.g.@: the ^switch^switch^ settings
12334 and object directory).
12335 Skeletal code for a main procedure might be something like the following:
12336
12337 @smallexample @c ada
12338 @group
12339 with GUI, Comm;
12340 procedure App_Main is
12341    @dots{}
12342 begin
12343    @dots{}
12344 end App_Main;
12345 @end group
12346 @end smallexample
12347
12348 @noindent
12349 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12350 effect:
12351
12352 @smallexample @c projectfile
12353 @group
12354 with "/gui/gui_proj", "/comm/comm_proj";
12355 project App_Proj is
12356    for Main use ("app_main");
12357 end App_Proj;
12358 @end group
12359 @end smallexample
12360
12361 @noindent
12362 Building an executable is achieved through the command:
12363 @smallexample
12364 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12365 @end smallexample
12366 @noindent
12367 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12368 in the directory where @file{app_proj.gpr} resides.
12369
12370 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12371 (as illustrated above) the @code{with} clause can omit the extension.
12372
12373 Our example specified an absolute path for each imported project file.
12374 Alternatively, the directory name of an imported object can be omitted
12375 if either
12376 @itemize @bullet
12377 @item
12378 The imported project file is in the same directory as the importing project
12379 file, or
12380 @item
12381 You have defined one or two ^environment variables^logical names^
12382 that includes the directory containing
12383 the needed project file. The syntax of @code{GPR_PROJECT_PATH} and
12384 @code{ADA_PROJECT_PATH} is the same as
12385 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12386 directory names separated by colons (semicolons on Windows).
12387 @end itemize
12388
12389 @noindent
12390 Thus, if we define @code{ADA_PROJECT_PATH} or @code{GPR_PROJECT_PATH}
12391 to include @file{^/gui^[GUI]^} and
12392 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12393 as follows:
12394
12395 @smallexample @c projectfile
12396 @group
12397 with "gui_proj", "comm_proj";
12398 project App_Proj is
12399    for Main use ("app_main");
12400 end App_Proj;
12401 @end group
12402 @end smallexample
12403
12404 @noindent
12405 Importing other projects can create ambiguities.
12406 For example, the same unit might be present in different imported projects, or
12407 it might be present in both the importing project and in an imported project.
12408 Both of these conditions are errors.  Note that in the current version of
12409 the Project Manager, it is illegal to have an ambiguous unit even if the
12410 unit is never referenced by the importing project.  This restriction may be
12411 relaxed in a future release.
12412
12413 @node Extending a Project
12414 @subsection Extending a Project
12415
12416 @noindent
12417 In large software systems it is common to have multiple
12418 implementations of a common interface; in Ada terms, multiple versions of a
12419 package body for the same spec.  For example, one implementation
12420 might be safe for use in tasking programs, while another might only be used
12421 in sequential applications.  This can be modeled in GNAT using the concept
12422 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
12423 another project (the ``parent'') then by default all source files of the
12424 parent project are inherited by the child, but the child project can
12425 override any of the parent's source files with new versions, and can also
12426 add new files.  This facility is the project analog of a type extension in
12427 Object-Oriented Programming.  Project hierarchies are permitted (a child
12428 project may be the parent of yet another project), and a project that
12429 inherits one project can also import other projects.
12430
12431 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12432 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12433 @file{pack.adb}, and @file{proc.adb}:
12434
12435 @smallexample
12436 @group
12437 ^/seq^[SEQ]^
12438   pack.ads
12439   pack.adb
12440   proc.adb
12441   seq_proj.gpr
12442 @end group
12443 @end smallexample
12444
12445 @noindent
12446 Note that the project file can simply be empty (that is, no attribute or
12447 package is defined):
12448
12449 @smallexample @c projectfile
12450 @group
12451 project Seq_Proj is
12452 end Seq_Proj;
12453 @end group
12454 @end smallexample
12455
12456 @noindent
12457 implying that its source files are all the Ada source files in the project
12458 directory.
12459
12460 Suppose we want to supply an alternate version of @file{pack.adb}, in
12461 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12462 @file{pack.ads} and @file{proc.adb}.  We can define a project
12463 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12464
12465 @smallexample
12466 @group
12467 ^/tasking^[TASKING]^
12468   pack.adb
12469   tasking_proj.gpr
12470 @end group
12471
12472 @group
12473 project Tasking_Proj extends "/seq/seq_proj" is
12474 end Tasking_Proj;
12475 @end group
12476 @end smallexample
12477
12478 @noindent
12479 The version of @file{pack.adb} used in a build depends on which project file
12480 is specified.
12481
12482 Note that we could have obtained the desired behavior using project import
12483 rather than project inheritance; a @code{base} project would contain the
12484 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12485 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12486 would import @code{base} and add a different version of @file{pack.adb}.  The
12487 choice depends on whether other sources in the original project need to be
12488 overridden.  If they do, then project extension is necessary, otherwise,
12489 importing is sufficient.
12490
12491 @noindent
12492 In a project file that extends another project file, it is possible to
12493 indicate that an inherited source is not part of the sources of the extending
12494 project. This is necessary sometimes when a package spec has been overloaded
12495 and no longer requires a body: in this case, it is necessary to indicate that
12496 the inherited body is not part of the sources of the project, otherwise there
12497 will be a compilation error when compiling the spec.
12498
12499 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12500 Its value is a string list: a list of file names. It is also possible to use
12501 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12502 the file name of a text file containing a list of file names, one per line.
12503
12504 @smallexample @c @projectfile
12505 project B extends "a" is
12506    for Source_Files use ("pkg.ads");
12507    --  New spec of Pkg does not need a completion
12508    for Excluded_Source_Files use ("pkg.adb");
12509 end B;
12510 @end smallexample
12511
12512 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12513 is still needed: if it is possible to build using @command{gnatmake} when such
12514 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12515 it is possible to remove the source completely from a system that includes
12516 project P.
12517
12518 @c ***********************
12519 @c * Project File Syntax *
12520 @c ***********************
12521
12522 @node Project File Syntax
12523 @section Project File Syntax
12524
12525 @menu
12526 * Basic Syntax::
12527 * Qualified Projects::
12528 * Packages::
12529 * Expressions::
12530 * String Types::
12531 * Variables::
12532 * Attributes::
12533 * Associative Array Attributes::
12534 * case Constructions::
12535 @end menu
12536
12537 @noindent
12538 This section describes the structure of project files.
12539
12540 A project may be an @emph{independent project}, entirely defined by a single
12541 project file. Any Ada source file in an independent project depends only
12542 on the predefined library and other Ada source files in the same project.
12543
12544 @noindent
12545 A project may also @dfn{depend on} other projects, in either or both of
12546 the following ways:
12547 @itemize @bullet
12548 @item It may import any number of projects
12549 @item It may extend at most one other project
12550 @end itemize
12551
12552 @noindent
12553 The dependence relation is a directed acyclic graph (the subgraph reflecting
12554 the ``extends'' relation is a tree).
12555
12556 A project's @dfn{immediate sources} are the source files directly defined by
12557 that project, either implicitly by residing in the project file's directory,
12558 or explicitly through any of the source-related attributes described below.
12559 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12560 of @var{proj} together with the immediate sources (unless overridden) of any
12561 project on which @var{proj} depends (either directly or indirectly).
12562
12563 @node Basic Syntax
12564 @subsection Basic Syntax
12565
12566 @noindent
12567 As seen in the earlier examples, project files have an Ada-like syntax.
12568 The minimal project file is:
12569 @smallexample @c projectfile
12570 @group
12571 project Empty is
12572
12573 end Empty;
12574 @end group
12575 @end smallexample
12576
12577 @noindent
12578 The identifier @code{Empty} is the name of the project.
12579 This project name must be present after the reserved
12580 word @code{end} at the end of the project file, followed by a semi-colon.
12581
12582 Any name in a project file, such as the project name or a variable name,
12583 has the same syntax as an Ada identifier.
12584
12585 The reserved words of project files are the Ada 95 reserved words plus
12586 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
12587 reserved words currently used in project file syntax are:
12588
12589 @itemize @bullet
12590 @item
12591 @code{all}
12592 @item
12593 @code{at}
12594 @item
12595 @code{case}
12596 @item
12597 @code{end}
12598 @item
12599 @code{for}
12600 @item
12601 @code{is}
12602 @item
12603 @code{limited}
12604 @item
12605 @code{null}
12606 @item
12607 @code{others}
12608 @item
12609 @code{package}
12610 @item
12611 @code{renames}
12612 @item
12613 @code{type}
12614 @item
12615 @code{use}
12616 @item
12617 @code{when}
12618 @item
12619 @code{with}
12620 @end itemize
12621
12622 @noindent
12623 Comments in project files have the same syntax as in Ada, two consecutive
12624 hyphens through the end of the line.
12625
12626 @node Qualified Projects
12627 @subsection Qualified Projects
12628
12629 @noindent
12630 Before the reserved @code{project}, there may be one or two "qualifiers", that
12631 is identifiers or other reserved words, to qualify the project.
12632
12633 The current list of qualifiers is:
12634
12635 @itemize @bullet
12636 @item
12637 @code{abstract}: qualify a project with no sources. A qualified abstract
12638 project must either have no declaration of attributes @code{Source_Dirs},
12639 @code{Source_Files}, @code{Languages} or @code{Source_List_File}, or one of
12640 @code{Source_Dirs}, @code{Source_Files}, or @code{Languages} must be declared
12641 as empty. If it extends another project, the project it extends must also be a
12642 qualified abstract project.
12643
12644 @item
12645 @code{standard}: a standard project is a non library project with sources.
12646
12647 @item
12648 @code{aggregate}: for future extension
12649
12650 @item
12651 @code{aggregate library}: for future extension
12652
12653 @item
12654 @code{library}: a library project must declare both attributes
12655 @code{Library_Name} and @code{Library_Dir}.
12656
12657 @item
12658 @code{configuration}: a configuration project cannot be in a project tree.
12659 @end itemize
12660
12661 @node Packages
12662 @subsection Packages
12663
12664 @noindent
12665 A project file may contain @emph{packages}. The name of a package must be one
12666 of the identifiers from the following list. A package
12667 with a given name may only appear once in a project file. Package names are
12668 case insensitive. The following package names are legal:
12669
12670 @itemize @bullet
12671 @item
12672 @code{Naming}
12673 @item
12674 @code{Builder}
12675 @item
12676 @code{Compiler}
12677 @item
12678 @code{Binder}
12679 @item
12680 @code{Linker}
12681 @item
12682 @code{Finder}
12683 @item
12684 @code{Cross_Reference}
12685 @item
12686 @code{Eliminate}
12687 @item
12688 @code{Pretty_Printer}
12689 @item
12690 @code{Metrics}
12691 @item
12692 @code{gnatls}
12693 @item
12694 @code{gnatstub}
12695 @item
12696 @code{IDE}
12697 @item
12698 @code{Language_Processing}
12699 @end itemize
12700
12701 @noindent
12702 In its simplest form, a package may be empty:
12703
12704 @smallexample @c projectfile
12705 @group
12706 project Simple is
12707   package Builder is
12708   end Builder;
12709 end Simple;
12710 @end group
12711 @end smallexample
12712
12713 @noindent
12714 A package may contain @emph{attribute declarations},
12715 @emph{variable declarations} and @emph{case constructions}, as will be
12716 described below.
12717
12718 When there is ambiguity between a project name and a package name,
12719 the name always designates the project. To avoid possible confusion, it is
12720 always a good idea to avoid naming a project with one of the
12721 names allowed for packages or any name that starts with @code{gnat}.
12722
12723 @node Expressions
12724 @subsection Expressions
12725
12726 @noindent
12727 An @emph{expression} is either a @emph{string expression} or a
12728 @emph{string list expression}.
12729
12730 A @emph{string expression} is either a @emph{simple string expression} or a
12731 @emph{compound string expression}.
12732
12733 A @emph{simple string expression} is one of the following:
12734 @itemize @bullet
12735 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12736 @item A string-valued variable reference (@pxref{Variables})
12737 @item A string-valued attribute reference (@pxref{Attributes})
12738 @item An external reference (@pxref{External References in Project Files})
12739 @end itemize
12740
12741 @noindent
12742 A @emph{compound string expression} is a concatenation of string expressions,
12743 using the operator @code{"&"}
12744 @smallexample
12745        Path & "/" & File_Name & ".ads"
12746 @end smallexample
12747
12748 @noindent
12749 A @emph{string list expression} is either a
12750 @emph{simple string list expression} or a
12751 @emph{compound string list expression}.
12752
12753 A @emph{simple string list expression} is one of the following:
12754 @itemize @bullet
12755 @item A parenthesized list of zero or more string expressions,
12756 separated by commas
12757 @smallexample
12758    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12759    Empty_List := ();
12760 @end smallexample
12761 @item A string list-valued variable reference
12762 @item A string list-valued attribute reference
12763 @end itemize
12764
12765 @noindent
12766 A @emph{compound string list expression} is the concatenation (using
12767 @code{"&"}) of a simple string list expression and an expression.  Note that
12768 each term in a compound string list expression, except the first, may be
12769 either a string expression or a string list expression.
12770
12771 @smallexample @c projectfile
12772 @group
12773    File_Name_List := () & File_Name; --  One string in this list
12774    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12775    --  Two strings
12776    Big_List := File_Name_List & Extended_File_Name_List;
12777    --  Concatenation of two string lists: three strings
12778    Illegal_List := "gnat.adc" & Extended_File_Name_List;
12779    --  Illegal: must start with a string list
12780 @end group
12781 @end smallexample
12782
12783 @node String Types
12784 @subsection String Types
12785
12786 @noindent
12787 A @emph{string type declaration} introduces a discrete set of string literals.
12788 If a string variable is declared to have this type, its value
12789 is restricted to the given set of literals.
12790
12791 Here is an example of a string type declaration:
12792
12793 @smallexample @c projectfile
12794    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12795 @end smallexample
12796
12797 @noindent
12798 Variables of a string type are called @emph{typed variables}; all other
12799 variables are called @emph{untyped variables}. Typed variables are
12800 particularly useful in @code{case} constructions, to support conditional
12801 attribute declarations.
12802 (@pxref{case Constructions}).
12803
12804 The string literals in the list are case sensitive and must all be different.
12805 They may include any graphic characters allowed in Ada, including spaces.
12806
12807 A string type may only be declared at the project level, not inside a package.
12808
12809 A string type may be referenced by its name if it has been declared in the same
12810 project file, or by an expanded name whose prefix is the name of the project
12811 in which it is declared.
12812
12813 @node Variables
12814 @subsection Variables
12815
12816 @noindent
12817 A variable may be declared at the project file level, or within a package.
12818 Here are some examples of variable declarations:
12819
12820 @smallexample @c projectfile
12821 @group
12822    This_OS : OS := external ("OS"); --  a typed variable declaration
12823    That_OS := "GNU/Linux";          --  an untyped variable declaration
12824 @end group
12825 @end smallexample
12826
12827 @noindent
12828 The syntax of a @emph{typed variable declaration} is identical to the Ada
12829 syntax for an object declaration. By contrast, the syntax of an untyped
12830 variable declaration is identical to an Ada assignment statement. In fact,
12831 variable declarations in project files have some of the characteristics of
12832 an assignment, in that successive declarations for the same variable are
12833 allowed. Untyped variable declarations do establish the expected kind of the
12834 variable (string or string list), and successive declarations for it must
12835 respect the initial kind.
12836
12837 @noindent
12838 A string variable declaration (typed or untyped) declares a variable
12839 whose value is a string. This variable may be used as a string expression.
12840 @smallexample @c projectfile
12841    File_Name       := "readme.txt";
12842    Saved_File_Name := File_Name & ".saved";
12843 @end smallexample
12844
12845 @noindent
12846 A string list variable declaration declares a variable whose value is a list
12847 of strings. The list may contain any number (zero or more) of strings.
12848
12849 @smallexample @c projectfile
12850    Empty_List := ();
12851    List_With_One_Element := ("^-gnaty^-gnaty^");
12852    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12853    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12854                  "pack2.ada", "util_.ada", "util.ada");
12855 @end smallexample
12856
12857 @noindent
12858 The same typed variable may not be declared more than once at project level,
12859 and it may not be declared more than once in any package; it is in effect
12860 a constant.
12861
12862 The same untyped variable may be declared several times. Declarations are
12863 elaborated in the order in which they appear, so  the new value replaces
12864 the old one, and any subsequent reference to the variable uses the new value.
12865 However, as noted above, if a variable has been declared as a string, all
12866 subsequent
12867 declarations must give it a string value. Similarly, if a variable has
12868 been declared as a string list, all subsequent declarations
12869 must give it a string list value.
12870
12871 A @emph{variable reference} may take several forms:
12872
12873 @itemize @bullet
12874 @item The simple variable name, for a variable in the current package (if any)
12875 or in the current project
12876 @item An expanded name, whose prefix is a context name.
12877 @end itemize
12878
12879 @noindent
12880 A @emph{context} may be one of the following:
12881
12882 @itemize @bullet
12883 @item The name of an existing package in the current project
12884 @item The name of an imported project of the current project
12885 @item The name of an ancestor project (i.e., a project extended by the current
12886 project, either directly or indirectly)
12887 @item An expanded name whose prefix is an imported/parent project name, and
12888 whose selector is a package name in that project.
12889 @end itemize
12890
12891 @noindent
12892 A variable reference may be used in an expression.
12893
12894 @node Attributes
12895 @subsection Attributes
12896
12897 @noindent
12898 A project (and its packages) may have @emph{attributes} that define
12899 the project's properties.  Some attributes have values that are strings;
12900 others have values that are string lists.
12901
12902 There are two categories of attributes: @emph{simple attributes}
12903 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12904
12905 Legal project attribute names, and attribute names for each legal package are
12906 listed below. Attributes names are case-insensitive.
12907
12908 The following attributes are defined on projects (all are simple attributes):
12909
12910 @multitable @columnfractions .4 .3
12911 @item @emph{Attribute Name}
12912 @tab @emph{Value}
12913 @item @code{Source_Files}
12914 @tab string list
12915 @item @code{Source_Dirs}
12916 @tab string list
12917 @item @code{Source_List_File}
12918 @tab string
12919 @item @code{Object_Dir}
12920 @tab string
12921 @item @code{Exec_Dir}
12922 @tab string
12923 @item @code{Excluded_Source_Dirs}
12924 @tab string list
12925 @item @code{Excluded_Source_Files}
12926 @tab string list
12927 @item @code{Excluded_Source_List_File}
12928 @tab string
12929 @item @code{Languages}
12930 @tab string list
12931 @item @code{Main}
12932 @tab string list
12933 @item @code{Library_Dir}
12934 @tab string
12935 @item @code{Library_Name}
12936 @tab string
12937 @item @code{Library_Kind}
12938 @tab string
12939 @item @code{Library_Version}
12940 @tab string
12941 @item @code{Library_Interface}
12942 @tab string
12943 @item @code{Library_Auto_Init}
12944 @tab string
12945 @item @code{Library_Options}
12946 @tab string list
12947 @item @code{Library_Src_Dir}
12948 @tab string
12949 @item @code{Library_ALI_Dir}
12950 @tab string
12951 @item @code{Library_GCC}
12952 @tab string
12953 @item @code{Library_Symbol_File}
12954 @tab string
12955 @item @code{Library_Symbol_Policy}
12956 @tab string
12957 @item @code{Library_Reference_Symbol_File}
12958 @tab string
12959 @item @code{Externally_Built}
12960 @tab string
12961 @end multitable
12962
12963 @noindent
12964 The following attributes are defined for package  @code{Naming}
12965 (@pxref{Naming Schemes}):
12966
12967 @multitable @columnfractions .4 .2 .2 .2
12968 @item Attribute Name @tab Category @tab Index @tab Value
12969 @item @code{Spec_Suffix}
12970 @tab associative array
12971 @tab language name
12972 @tab string
12973 @item @code{Body_Suffix}
12974 @tab associative array
12975 @tab language name
12976 @tab string
12977 @item @code{Separate_Suffix}
12978 @tab simple attribute
12979 @tab n/a
12980 @tab string
12981 @item @code{Casing}
12982 @tab simple attribute
12983 @tab n/a
12984 @tab string
12985 @item @code{Dot_Replacement}
12986 @tab simple attribute
12987 @tab n/a
12988 @tab string
12989 @item @code{Spec}
12990 @tab associative array
12991 @tab Ada unit name
12992 @tab string
12993 @item @code{Body}
12994 @tab associative array
12995 @tab Ada unit name
12996 @tab string
12997 @item @code{Specification_Exceptions}
12998 @tab associative array
12999 @tab language name
13000 @tab string list
13001 @item @code{Implementation_Exceptions}
13002 @tab associative array
13003 @tab language name
13004 @tab string list
13005 @end multitable
13006
13007 @noindent
13008 The following attributes are defined for packages @code{Builder},
13009 @code{Compiler}, @code{Binder},
13010 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
13011 (@pxref{^Switches^Switches^ and Project Files}).
13012
13013 @multitable @columnfractions .4 .2 .2 .2
13014 @item Attribute Name @tab Category @tab Index @tab Value
13015 @item @code{^Default_Switches^Default_Switches^}
13016 @tab associative array
13017 @tab language name
13018 @tab string list
13019 @item @code{^Switches^Switches^}
13020 @tab associative array
13021 @tab file name
13022 @tab string list
13023 @end multitable
13024
13025 @noindent
13026 In addition, package @code{Compiler} has a single string attribute
13027 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
13028 string attribute @code{Global_Configuration_Pragmas}.
13029
13030 @noindent
13031 Each simple attribute has a default value: the empty string (for string-valued
13032 attributes) and the empty list (for string list-valued attributes).
13033
13034 An attribute declaration defines a new value for an attribute.
13035
13036 Examples of simple attribute declarations:
13037
13038 @smallexample @c projectfile
13039    for Object_Dir use "objects";
13040    for Source_Dirs use ("units", "test/drivers");
13041 @end smallexample
13042
13043 @noindent
13044 The syntax of a @dfn{simple attribute declaration} is similar to that of an
13045 attribute definition clause in Ada.
13046
13047 Attributes references may be appear in expressions.
13048 The general form for such a reference is @code{<entity>'<attribute>}:
13049 Associative array attributes are functions. Associative
13050 array attribute references must have an argument that is a string literal.
13051
13052 Examples are:
13053
13054 @smallexample @c projectfile
13055   project'Object_Dir
13056   Naming'Dot_Replacement
13057   Imported_Project'Source_Dirs
13058   Imported_Project.Naming'Casing
13059   Builder'^Default_Switches^Default_Switches^("Ada")
13060 @end smallexample
13061
13062 @noindent
13063 The prefix of an attribute may be:
13064 @itemize @bullet
13065 @item @code{project} for an attribute of the current project
13066 @item The name of an existing package of the current project
13067 @item The name of an imported project
13068 @item The name of a parent project that is extended by the current project
13069 @item An expanded name whose prefix is imported/parent project name,
13070 and whose selector is a package name
13071 @end itemize
13072
13073 @noindent
13074 Example:
13075 @smallexample @c projectfile
13076 @group
13077    project Prj is
13078      for Source_Dirs use project'Source_Dirs & "units";
13079      for Source_Dirs use project'Source_Dirs & "test/drivers"
13080    end Prj;
13081 @end group
13082 @end smallexample
13083
13084 @noindent
13085 In the first attribute declaration, initially the attribute @code{Source_Dirs}
13086 has the default value: an empty string list. After this declaration,
13087 @code{Source_Dirs} is a string list of one element: @code{"units"}.
13088 After the second attribute declaration @code{Source_Dirs} is a string list of
13089 two elements: @code{"units"} and @code{"test/drivers"}.
13090
13091 Note: this example is for illustration only. In practice,
13092 the project file would contain only one attribute declaration:
13093
13094 @smallexample @c projectfile
13095    for Source_Dirs use ("units", "test/drivers");
13096 @end smallexample
13097
13098 @node Associative Array Attributes
13099 @subsection Associative Array Attributes
13100
13101 @noindent
13102 Some attributes are defined as @emph{associative arrays}. An associative
13103 array may be regarded as a function that takes a string as a parameter
13104 and delivers a string or string list value as its result.
13105
13106 Here are some examples of single associative array attribute associations:
13107
13108 @smallexample @c projectfile
13109    for Body ("main") use "Main.ada";
13110    for ^Switches^Switches^ ("main.ada")
13111        use ("^-v^-v^",
13112             "^-gnatv^-gnatv^");
13113    for ^Switches^Switches^ ("main.ada")
13114             use Builder'^Switches^Switches^ ("main.ada")
13115               & "^-g^-g^";
13116 @end smallexample
13117
13118 @noindent
13119 Like untyped variables and simple attributes, associative array attributes
13120 may be declared several times. Each declaration supplies a new value for the
13121 attribute, and replaces the previous setting.
13122
13123 @noindent
13124 An associative array attribute may be declared as a full associative array
13125 declaration, with the value of the same attribute in an imported or extended
13126 project.
13127
13128 @smallexample @c projectfile
13129    package Builder is
13130       for Default_Switches use Default.Builder'Default_Switches;
13131    end Builder;
13132 @end smallexample
13133
13134 @noindent
13135 In this example, @code{Default} must be either a project imported by the
13136 current project, or the project that the current project extends. If the
13137 attribute is in a package (in this case, in package @code{Builder}), the same
13138 package needs to be specified.
13139
13140 @noindent
13141 A full associative array declaration replaces any other declaration for the
13142 attribute, including other full associative array declaration. Single
13143 associative array associations may be declare after a full associative
13144 declaration, modifying the value for a single association of the attribute.
13145
13146 @node case Constructions
13147 @subsection @code{case} Constructions
13148
13149 @noindent
13150 A @code{case} construction is used in a project file to effect conditional
13151 behavior.
13152 Here is a typical example:
13153
13154 @smallexample @c projectfile
13155 @group
13156 project MyProj is
13157    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
13158
13159    OS : OS_Type := external ("OS", "GNU/Linux");
13160 @end group
13161
13162 @group
13163    package Compiler is
13164      case OS is
13165        when "GNU/Linux" | "Unix" =>
13166          for ^Default_Switches^Default_Switches^ ("Ada")
13167              use ("^-gnath^-gnath^");
13168        when "NT" =>
13169          for ^Default_Switches^Default_Switches^ ("Ada")
13170              use ("^-gnatP^-gnatP^");
13171        when others =>
13172      end case;
13173    end Compiler;
13174 end MyProj;
13175 @end group
13176 @end smallexample
13177
13178 @noindent
13179 The syntax of a @code{case} construction is based on the Ada case statement
13180 (although there is no @code{null} construction for empty alternatives).
13181
13182 The case expression must be a typed string variable.
13183 Each alternative comprises the reserved word @code{when}, either a list of
13184 literal strings separated by the @code{"|"} character or the reserved word
13185 @code{others},  and the @code{"=>"} token.
13186 Each literal string must belong to the string type that is the type of the
13187 case variable.
13188 An @code{others} alternative, if present, must occur last.
13189
13190 After each @code{=>}, there are zero or more constructions.  The only
13191 constructions allowed in a case construction are other case constructions,
13192 attribute declarations and variable declarations. String type declarations and
13193 package declarations are not allowed. Variable declarations are restricted to
13194 variables that have already been declared before the case construction.
13195
13196 The value of the case variable is often given by an external reference
13197 (@pxref{External References in Project Files}).
13198
13199 @c ****************************************
13200 @c * Objects and Sources in Project Files *
13201 @c ****************************************
13202
13203 @node Objects and Sources in Project Files
13204 @section Objects and Sources in Project Files
13205
13206 @menu
13207 * Object Directory::
13208 * Exec Directory::
13209 * Source Directories::
13210 * Source File Names::
13211 @end menu
13212
13213 @noindent
13214 Each project has exactly one object directory and one or more source
13215 directories. The source directories must contain at least one source file,
13216 unless  the project file explicitly specifies that no source files are present
13217 (@pxref{Source File Names}).
13218
13219 @node Object Directory
13220 @subsection Object Directory
13221
13222 @noindent
13223 The object directory for a project is the directory containing the compiler's
13224 output (such as @file{ALI} files and object files) for the project's immediate
13225 sources.
13226
13227 The object directory is given by the value of the attribute @code{Object_Dir}
13228 in the project file.
13229
13230 @smallexample @c projectfile
13231    for Object_Dir use "objects";
13232 @end smallexample
13233
13234 @noindent
13235 The attribute @code{Object_Dir} has a string value, the path name of the object
13236 directory. The path name may be absolute or relative to the directory of the
13237 project file. This directory must already exist, and be readable and writable.
13238
13239 By default, when the attribute @code{Object_Dir} is not given an explicit value
13240 or when its value is the empty string, the object directory is the same as the
13241 directory containing the project file.
13242
13243 @node Exec Directory
13244 @subsection Exec Directory
13245
13246 @noindent
13247 The exec directory for a project is the directory containing the executables
13248 for the project's main subprograms.
13249
13250 The exec directory is given by the value of the attribute @code{Exec_Dir}
13251 in the project file.
13252
13253 @smallexample @c projectfile
13254    for Exec_Dir use "executables";
13255 @end smallexample
13256
13257 @noindent
13258 The attribute @code{Exec_Dir} has a string value, the path name of the exec
13259 directory. The path name may be absolute or relative to the directory of the
13260 project file. This directory must already exist, and be writable.
13261
13262 By default, when the attribute @code{Exec_Dir} is not given an explicit value
13263 or when its value is the empty string, the exec directory is the same as the
13264 object directory of the project file.
13265
13266 @node Source Directories
13267 @subsection Source Directories
13268
13269 @noindent
13270 The source directories of a project are specified by the project file
13271 attribute @code{Source_Dirs}.
13272
13273 This attribute's value is a string list. If the attribute is not given an
13274 explicit value, then there is only one source directory, the one where the
13275 project file resides.
13276
13277 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
13278 as in
13279
13280 @smallexample @c projectfile
13281     for Source_Dirs use ();
13282 @end smallexample
13283
13284 @noindent
13285 indicates that the project contains no source files.
13286
13287 Otherwise, each string in the string list designates one or more
13288 source directories.
13289
13290 @smallexample @c projectfile
13291    for Source_Dirs use ("sources", "test/drivers");
13292 @end smallexample
13293
13294 @noindent
13295 If a string in the list ends with @code{"/**"},  then the directory whose path
13296 name precedes the two asterisks, as well as all its subdirectories
13297 (recursively), are source directories.
13298
13299 @smallexample @c projectfile
13300    for Source_Dirs use ("/system/sources/**");
13301 @end smallexample
13302
13303 @noindent
13304 Here the directory @code{/system/sources} and all of its subdirectories
13305 (recursively) are source directories.
13306
13307 To specify that the source directories are the directory of the project file
13308 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
13309 @smallexample @c projectfile
13310    for Source_Dirs use ("./**");
13311 @end smallexample
13312
13313 @noindent
13314 Each of the source directories must exist and be readable.
13315
13316 @node Source File Names
13317 @subsection Source File Names
13318
13319 @noindent
13320 In a project that contains source files, their names may be specified by the
13321 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
13322 (a string). Source file names never include any directory information.
13323
13324 If the attribute @code{Source_Files} is given an explicit value, then each
13325 element of the list is a source file name.
13326
13327 @smallexample @c projectfile
13328    for Source_Files use ("main.adb");
13329    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
13330 @end smallexample
13331
13332 @noindent
13333 If the attribute @code{Source_Files} is not given an explicit value,
13334 but the attribute @code{Source_List_File} is given a string value,
13335 then the source file names are contained in the text file whose path name
13336 (absolute or relative to the directory of the project file) is the
13337 value of the attribute @code{Source_List_File}.
13338
13339 Each line in the file that is not empty or is not a comment
13340 contains a source file name.
13341
13342 @smallexample @c projectfile
13343    for Source_List_File use "source_list.txt";
13344 @end smallexample
13345
13346 @noindent
13347 By default, if neither the attribute @code{Source_Files} nor the attribute
13348 @code{Source_List_File} is given an explicit value, then each file in the
13349 source directories that conforms to the project's naming scheme
13350 (@pxref{Naming Schemes}) is an immediate source of the project.
13351
13352 A warning is issued if both attributes @code{Source_Files} and
13353 @code{Source_List_File} are given explicit values. In this case, the attribute
13354 @code{Source_Files} prevails.
13355
13356 Each source file name must be the name of one existing source file
13357 in one of the source directories.
13358
13359 A @code{Source_Files} attribute whose value is an empty list
13360 indicates that there are no source files in the project.
13361
13362 If the order of the source directories is known statically, that is if
13363 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13364 be several files with the same source file name. In this case, only the file
13365 in the first directory is considered as an immediate source of the project
13366 file. If the order of the source directories is not known statically, it is
13367 an error to have several files with the same source file name.
13368
13369 Projects can be specified to have no Ada source
13370 files: the value of @code{Source_Dirs} or @code{Source_Files} may be an empty
13371 list, or the @code{"Ada"} may be absent from @code{Languages}:
13372
13373 @smallexample @c projectfile
13374    for Source_Dirs use ();
13375    for Source_Files use ();
13376    for Languages use ("C", "C++");
13377 @end smallexample
13378
13379 @noindent
13380 Otherwise, a project must contain at least one immediate source.
13381
13382 Projects with no source files are useful as template packages
13383 (@pxref{Packages in Project Files}) for other projects; in particular to
13384 define a package @code{Naming} (@pxref{Naming Schemes}).
13385
13386 @c ****************************
13387 @c * Importing Projects *
13388 @c ****************************
13389
13390 @node  Importing Projects
13391 @section Importing Projects
13392 @cindex @code{ADA_PROJECT_PATH}
13393 @cindex @code{GPR_PROJECT_PATH}
13394
13395 @noindent
13396 An immediate source of a project P may depend on source files that
13397 are neither immediate sources of P nor in the predefined library.
13398 To get this effect, P must @emph{import} the projects that contain the needed
13399 source files.
13400
13401 @smallexample @c projectfile
13402 @group
13403   with "project1", "utilities.gpr";
13404   with "/namings/apex.gpr";
13405   project Main is
13406     @dots{}
13407 @end group
13408 @end smallexample
13409
13410 @noindent
13411 As can be seen in this example, the syntax for importing projects is similar
13412 to the syntax for importing compilation units in Ada. However, project files
13413 use literal strings instead of names, and the @code{with} clause identifies
13414 project files rather than packages.
13415
13416 Each literal string is the file name or path name (absolute or relative) of a
13417 project file. If a string corresponds to a file name, with no path or a
13418 relative path, then its location is determined by the @emph{project path}. The
13419 latter can be queried using @code{gnatls -v}. It contains:
13420
13421 @itemize @bullet
13422 @item
13423 In first position, the directory containing the current project file.
13424 @item
13425 In last position, the default project directory. This default project directory
13426 is part of the GNAT installation and is the standard place to install project
13427 files giving access to standard support libraries.
13428 @ifclear vms
13429 @ref{Installing a library}
13430 @end ifclear
13431
13432 @item
13433 In between, all the directories referenced in the
13434 ^environment variables^logical names^ @env{GPR_PROJECT_PATH}
13435 and @env{ADA_PROJECT_PATH} if they exist, and in that order.
13436 @end itemize
13437
13438 @noindent
13439 If a relative pathname is used, as in
13440
13441 @smallexample @c projectfile
13442   with "tests/proj";
13443 @end smallexample
13444
13445 @noindent
13446 then the full path for the project is constructed by concatenating this
13447 relative path to those in the project path, in order, until a matching file is
13448 found. Any symbolic link will be fully resolved in the directory of the
13449 importing project file before the imported project file is examined.
13450
13451 If the @code{with}'ed project file name does not have an extension,
13452 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13453 then the file name as specified in the @code{with} clause (no extension) will
13454 be used. In the above example, if a file @code{project1.gpr} is found, then it
13455 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13456 then it will be used; if neither file exists, this is an error.
13457
13458 A warning is issued if the name of the project file does not match the
13459 name of the project; this check is case insensitive.
13460
13461 Any source file that is an immediate source of the imported project can be
13462 used by the immediate sources of the importing project, transitively. Thus
13463 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13464 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13465 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13466 because if and when @code{B} ceases to import @code{C}, some sources in
13467 @code{A} will no longer compile.
13468
13469 A side effect of this capability is that normally cyclic dependencies are not
13470 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13471 is not allowed to import @code{A}. However, there are cases when cyclic
13472 dependencies would be beneficial. For these cases, another form of import
13473 between projects exists, the @code{limited with}: a project @code{A} that
13474 imports a project @code{B} with a straight @code{with} may also be imported,
13475 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13476 to @code{A} include at least one @code{limited with}.
13477
13478 @smallexample @c 0projectfile
13479 with "../b/b.gpr";
13480 with "../c/c.gpr";
13481 project A is
13482 end A;
13483
13484 limited with "../a/a.gpr";
13485 project B is
13486 end B;
13487
13488 with "../d/d.gpr";
13489 project C is
13490 end C;
13491
13492 limited with "../a/a.gpr";
13493 project D is
13494 end D;
13495 @end smallexample
13496
13497 @noindent
13498 In the above legal example, there are two project cycles:
13499 @itemize @bullet
13500 @item A-> B-> A
13501 @item A -> C -> D -> A
13502 @end itemize
13503
13504 @noindent
13505 In each of these cycle there is one @code{limited with}: import of @code{A}
13506 from @code{B} and import of @code{A} from @code{D}.
13507
13508 The difference between straight @code{with} and @code{limited with} is that
13509 the name of a project imported with a @code{limited with} cannot be used in the
13510 project that imports it. In particular, its packages cannot be renamed and
13511 its variables cannot be referred to.
13512
13513 An exception to the above rules for @code{limited with} is that for the main
13514 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13515 @code{limited with} is equivalent to a straight @code{with}. For example,
13516 in the example above, projects @code{B} and @code{D} could not be main
13517 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13518 each have a @code{limited with} that is the only one in a cycle of importing
13519 projects.
13520
13521 @c *********************
13522 @c * Project Extension *
13523 @c *********************
13524
13525 @node Project Extension
13526 @section Project Extension
13527
13528 @noindent
13529 During development of a large system, it is sometimes necessary to use
13530 modified versions of some of the source files, without changing the original
13531 sources. This can be achieved through the @emph{project extension} facility.
13532
13533 @smallexample @c projectfile
13534    project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13535 @end smallexample
13536
13537 @noindent
13538 A project extension declaration introduces an extending project
13539 (the @emph{child}) and a project being extended (the @emph{parent}).
13540
13541 By default, a child project inherits all the sources of its parent.
13542 However, inherited sources can be overridden: a unit in a parent is hidden
13543 by a unit of the same name in the child.
13544
13545 Inherited sources are considered to be sources (but not immediate sources)
13546 of the child project; see @ref{Project File Syntax}.
13547
13548 An inherited source file retains any switches specified in the parent project.
13549
13550 For example if the project @code{Utilities} contains the spec and the
13551 body of an Ada package @code{Util_IO}, then the project
13552 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13553 The original body of @code{Util_IO} will not be considered in program builds.
13554 However, the package spec will still be found in the project
13555 @code{Utilities}.
13556
13557 A child project can have only one parent, except when it is qualified as
13558 abstract. But it may import any number of other projects.
13559
13560 A project is not allowed to import directly or indirectly at the same time a
13561 child project and any of its ancestors.
13562
13563 @c *******************************
13564 @c * Project Hierarchy Extension *
13565 @c *******************************
13566
13567 @node Project Hierarchy Extension
13568 @section Project Hierarchy Extension
13569
13570 @noindent
13571 When extending a large system spanning multiple projects, it is often
13572 inconvenient to extend every project in the hierarchy that is impacted by a
13573 small change introduced. In such cases, it is possible to create a virtual
13574 extension of entire hierarchy using @code{extends all} relationship.
13575
13576 When the project is extended using @code{extends all} inheritance, all projects
13577 that are imported by it, both directly and indirectly, are considered virtually
13578 extended. That is, the Project Manager creates "virtual projects"
13579 that extend every project in the hierarchy; all these virtual projects have
13580 no sources of their own and have as object directory the object directory of
13581 the root of "extending all" project.
13582
13583 It is possible to explicitly extend one or more projects in the hierarchy
13584 in order to modify the sources. These extending projects must be imported by
13585 the "extending all" project, which will replace the corresponding virtual
13586 projects with the explicit ones.
13587
13588 When building such a project hierarchy extension, the Project Manager will
13589 ensure that both modified sources and sources in virtual extending projects
13590 that depend on them, are recompiled.
13591
13592 By means of example, consider the following hierarchy of projects.
13593
13594 @enumerate
13595 @item
13596 project A, containing package P1
13597 @item
13598 project B importing A and containing package P2 which depends on P1
13599 @item
13600 project C importing B and containing package P3 which depends on P2
13601 @end enumerate
13602
13603 @noindent
13604 We want to modify packages P1 and P3.
13605
13606 This project hierarchy will need to be extended as follows:
13607
13608 @enumerate
13609 @item
13610 Create project A1 that extends A, placing modified P1 there:
13611
13612 @smallexample @c 0projectfile
13613 project A1 extends "(@dots{})/A" is
13614 end A1;
13615 @end smallexample
13616
13617 @item
13618 Create project C1 that "extends all" C and imports A1, placing modified
13619 P3 there:
13620
13621 @smallexample @c 0projectfile
13622 with "(@dots{})/A1";
13623 project C1 extends all "(@dots{})/C" is
13624 end C1;
13625 @end smallexample
13626 @end enumerate
13627
13628 When you build project C1, your entire modified project space will be
13629 recompiled, including the virtual project B1 that has been impacted by the
13630 "extending all" inheritance of project C.
13631
13632 Note that if a Library Project in the hierarchy is virtually extended,
13633 the virtual project that extends the Library Project is not a Library Project.
13634
13635 @c ****************************************
13636 @c * External References in Project Files *
13637 @c ****************************************
13638
13639 @node  External References in Project Files
13640 @section External References in Project Files
13641
13642 @noindent
13643 A project file may contain references to external variables; such references
13644 are called @emph{external references}.
13645
13646 An external variable is either defined as part of the environment (an
13647 environment variable in Unix, for example) or else specified on the command
13648 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13649 If both, then the command line value is used.
13650
13651 The value of an external reference is obtained by means of the built-in
13652 function @code{external}, which returns a string value.
13653 This function has two forms:
13654 @itemize @bullet
13655 @item @code{external (external_variable_name)}
13656 @item @code{external (external_variable_name, default_value)}
13657 @end itemize
13658
13659 @noindent
13660 Each parameter must be a string literal.  For example:
13661
13662 @smallexample @c projectfile
13663    external ("USER")
13664    external ("OS", "GNU/Linux")
13665 @end smallexample
13666
13667 @noindent
13668 In the form with one parameter, the function returns the value of
13669 the external variable given as parameter. If this name is not present in the
13670 environment, the function returns an empty string.
13671
13672 In the form with two string parameters, the second argument is
13673 the value returned when the variable given as the first argument is not
13674 present in the environment. In the example above, if @code{"OS"} is not
13675 the name of ^an environment variable^a logical name^ and is not passed on
13676 the command line, then the returned value is @code{"GNU/Linux"}.
13677
13678 An external reference may be part of a string expression or of a string
13679 list expression, and can therefore appear in a variable declaration or
13680 an attribute declaration.
13681
13682 @smallexample @c projectfile
13683 @group
13684    type Mode_Type is ("Debug", "Release");
13685    Mode : Mode_Type := external ("MODE");
13686    case Mode is
13687      when "Debug" =>
13688         @dots{}
13689 @end group
13690 @end smallexample
13691
13692 @c *****************************
13693 @c * Packages in Project Files *
13694 @c *****************************
13695
13696 @node  Packages in Project Files
13697 @section Packages in Project Files
13698
13699 @noindent
13700 A @emph{package} defines the settings for project-aware tools within a
13701 project.
13702 For each such tool one can declare a package; the names for these
13703 packages are preset (@pxref{Packages}).
13704 A package may contain variable declarations, attribute declarations, and case
13705 constructions.
13706
13707 @smallexample @c projectfile
13708 @group
13709    project Proj is
13710       package Builder is  -- used by gnatmake
13711          for ^Default_Switches^Default_Switches^ ("Ada")
13712              use ("^-v^-v^",
13713                   "^-g^-g^");
13714       end Builder;
13715    end Proj;
13716 @end group
13717 @end smallexample
13718
13719 @noindent
13720 The syntax of package declarations mimics that of package in Ada.
13721
13722 Most of the packages have an attribute
13723 @code{^Default_Switches^Default_Switches^}.
13724 This attribute is an associative array, and its value is a string list.
13725 The index of the associative array is the name of a programming language (case
13726 insensitive). This attribute indicates the ^switch^switch^
13727 or ^switches^switches^ to be used
13728 with the corresponding tool.
13729
13730 Some packages also have another attribute, @code{^Switches^Switches^},
13731 an associative array whose value is a string list.
13732 The index is the name of a source file.
13733 This attribute indicates the ^switch^switch^
13734 or ^switches^switches^ to be used by the corresponding
13735 tool when dealing with this specific file.
13736
13737 Further information on these ^switch^switch^-related attributes is found in
13738 @ref{^Switches^Switches^ and Project Files}.
13739
13740 A package may be declared as a @emph{renaming} of another package; e.g., from
13741 the project file for an imported project.
13742
13743 @smallexample @c projectfile
13744 @group
13745   with "/global/apex.gpr";
13746   project Example is
13747     package Naming renames Apex.Naming;
13748     @dots{}
13749   end Example;
13750 @end group
13751 @end smallexample
13752
13753 @noindent
13754 Packages that are renamed in other project files often come from project files
13755 that have no sources: they are just used as templates. Any modification in the
13756 template will be reflected automatically in all the project files that rename
13757 a package from the template.
13758
13759 In addition to the tool-oriented packages, you can also declare a package
13760 named @code{Naming} to establish specialized source file naming conventions
13761 (@pxref{Naming Schemes}).
13762
13763 @c ************************************
13764 @c * Variables from Imported Projects *
13765 @c ************************************
13766
13767 @node Variables from Imported Projects
13768 @section Variables from Imported Projects
13769
13770 @noindent
13771 An attribute or variable defined in an imported or parent project can
13772 be used in expressions in the importing / extending project.
13773 Such an attribute or variable is denoted by an expanded name whose prefix
13774 is either the name of the project or the expanded name of a package within
13775 a project.
13776
13777 @smallexample @c projectfile
13778 @group
13779   with "imported";
13780   project Main extends "base" is
13781      Var1 := Imported.Var;
13782      Var2 := Base.Var & ".new";
13783 @end group
13784
13785 @group
13786      package Builder is
13787         for ^Default_Switches^Default_Switches^ ("Ada")
13788             use Imported.Builder'Ada_^Switches^Switches^ &
13789                 "^-gnatg^-gnatg^" &
13790                 "^-v^-v^";
13791      end Builder;
13792 @end group
13793
13794 @group
13795      package Compiler is
13796         for ^Default_Switches^Default_Switches^ ("Ada")
13797             use Base.Compiler'Ada_^Switches^Switches^;
13798      end Compiler;
13799   end Main;
13800 @end group
13801 @end smallexample
13802
13803 @noindent
13804 In this example:
13805
13806 @itemize @bullet
13807 @item
13808 The value of @code{Var1} is a copy of the variable @code{Var} defined
13809 in the project file @file{"imported.gpr"}
13810 @item
13811 the value of @code{Var2} is a copy of the value of variable @code{Var}
13812 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13813 @item
13814 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13815 @code{Builder} is a string list that includes in its value a copy of the value
13816 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13817 in project file @file{imported.gpr} plus two new elements:
13818 @option{"^-gnatg^-gnatg^"}
13819 and @option{"^-v^-v^"};
13820 @item
13821 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13822 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13823 defined in the @code{Compiler} package in project file @file{base.gpr},
13824 the project being extended.
13825 @end itemize
13826
13827 @c ******************
13828 @c * Naming Schemes *
13829 @c ******************
13830
13831 @node  Naming Schemes
13832 @section Naming Schemes
13833
13834 @noindent
13835 Sometimes an Ada software system is ported from a foreign compilation
13836 environment to GNAT, and the file names do not use the default GNAT
13837 conventions. Instead of changing all the file names (which for a variety
13838 of reasons might not be possible), you can define the relevant file
13839 naming scheme in the @code{Naming} package in your project file.
13840
13841 @noindent
13842 Note that the use of pragmas described in
13843 @ref{Alternative File Naming Schemes} by mean of a configuration
13844 pragmas file is not supported when using project files. You must use
13845 the features described in this paragraph. You can however use specify
13846 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13847
13848 @ifclear vms
13849 For example, the following
13850 package models the Apex file naming rules:
13851
13852 @smallexample @c projectfile
13853 @group
13854   package Naming is
13855     for Casing               use "lowercase";
13856     for Dot_Replacement      use ".";
13857     for Spec_Suffix ("Ada")  use ".1.ada";
13858     for Body_Suffix ("Ada")  use ".2.ada";
13859   end Naming;
13860 @end group
13861 @end smallexample
13862 @end ifclear
13863
13864 @ifset vms
13865 For example, the following package models the HP Ada file naming rules:
13866
13867 @smallexample @c projectfile
13868 @group
13869   package Naming is
13870     for Casing               use "lowercase";
13871     for Dot_Replacement      use "__";
13872     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
13873     for Body_Suffix ("Ada")  use ".^ada^ada^";
13874   end Naming;
13875 @end group
13876 @end smallexample
13877
13878 @noindent
13879 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13880 names in lower case)
13881 @end ifset
13882
13883 @noindent
13884 You can define the following attributes in package @code{Naming}:
13885
13886 @table @code
13887
13888 @item @code{Casing}
13889 This must be a string with one of the three values @code{"lowercase"},
13890 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13891
13892 @noindent
13893 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13894
13895 @item @code{Dot_Replacement}
13896 This must be a string whose value satisfies the following conditions:
13897
13898 @itemize @bullet
13899 @item It must not be empty
13900 @item It cannot start or end with an alphanumeric character
13901 @item It cannot be a single underscore
13902 @item It cannot start with an underscore followed by an alphanumeric
13903 @item It cannot contain a dot @code{'.'} except if the entire string
13904 is @code{"."}
13905 @end itemize
13906
13907 @noindent
13908 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13909
13910 @item @code{Spec_Suffix}
13911 This is an associative array (indexed by the programming language name, case
13912 insensitive) whose value is a string that must satisfy the following
13913 conditions:
13914
13915 @itemize @bullet
13916 @item It must not be empty
13917 @item It must include at least one dot
13918 @end itemize
13919 @noindent
13920 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13921 @code{"^.ads^.ADS^"}.
13922
13923 @item @code{Body_Suffix}
13924 This is an associative array (indexed by the programming language name, case
13925 insensitive) whose value is a string that must satisfy the following
13926 conditions:
13927
13928 @itemize @bullet
13929 @item It must not be empty
13930 @item It must include at least one dot
13931 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13932 @end itemize
13933 @noindent
13934 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13935 same string, then a file name that ends with the longest of these two suffixes
13936 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13937 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13938
13939 If the suffix does not start with a '.', a file with a name exactly equal
13940 to the suffix will also be part of the project (for instance if you define
13941 the suffix as @code{Makefile}, a file called @file{Makefile} will be part
13942 of the project. This is not interesting in general when using projects to
13943 compile. However, it might become useful when a project is also used to
13944 find the list of source files in an editor, like the GNAT Programming System
13945 (GPS).
13946
13947 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13948 @code{"^.adb^.ADB^"}.
13949
13950 @item @code{Separate_Suffix}
13951 This must be a string whose value satisfies the same conditions as
13952 @code{Body_Suffix}. The same "longest suffix" rules apply.
13953
13954 @noindent
13955 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13956 value as @code{Body_Suffix ("Ada")}.
13957
13958 @item @code{Spec}
13959 @noindent
13960 You can use the associative array attribute @code{Spec}  to define
13961 the source file name for an individual Ada compilation unit's spec. The array
13962 index must be a string literal that identifies the Ada unit (case insensitive).
13963 The value of this attribute must be a string that identifies the file that
13964 contains this unit's spec (case sensitive or insensitive depending on the
13965 operating system).
13966
13967 @smallexample @c projectfile
13968    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13969 @end smallexample
13970
13971 When the source file contains several units, you can indicate at what
13972 position the unit occurs in the file, with the following. The first unit
13973 in the file has index 1
13974
13975 @smallexample @c projectfile
13976   for Body ("top") use "foo.a" at 1;
13977   for Body ("foo") use "foo.a" at 2;
13978 @end smallexample
13979
13980 @item @code{Body}
13981
13982 You can use the associative array attribute @code{Body} to
13983 define the source file name for an individual Ada compilation unit's body
13984 (possibly a subunit).  The array index must be a string literal that identifies
13985 the Ada unit (case insensitive).  The value of this attribute must be a string
13986 that identifies the file that contains this unit's body or subunit (case
13987 sensitive or insensitive depending on the operating system).
13988
13989 @smallexample @c projectfile
13990    for Body ("MyPack.MyChild") use "mypack.mychild.body";
13991 @end smallexample
13992 @end table
13993
13994 @c ********************
13995 @c * Library Projects *
13996 @c ********************
13997
13998 @node Library Projects
13999 @section Library Projects
14000
14001 @noindent
14002 @emph{Library projects} are projects whose object code is placed in a library.
14003 (Note that this facility is not yet supported on all platforms).
14004
14005 @code{gnatmake} or @code{gprbuild} will collect all object files into a
14006 single archive, which might either be a shared or a static library. This
14007 library can later on be linked with multiple executables, potentially
14008 reducing their sizes.
14009
14010 If your project file specifies languages other than Ada, but you are still
14011 using @code{gnatmake} to compile and link, the latter will not try to
14012 compile your sources other than Ada (you should use @code{gprbuild} if that
14013 is your intent). However, @code{gnatmake} will automatically link all object
14014 files found in the object directory, whether or not they were compiled from
14015 an Ada source file. This specific behavior only applies when multiple
14016 languages are specified.
14017
14018 To create a library project, you need to define in its project file
14019 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
14020 Additionally, you may define other library-related attributes such as
14021 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
14022 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
14023
14024 The @code{Library_Name} attribute has a string value. There is no restriction
14025 on the name of a library. It is the responsibility of the developer to
14026 choose a name that will be accepted by the platform. It is recommended to
14027 choose names that could be Ada identifiers; such names are almost guaranteed
14028 to be acceptable on all platforms.
14029
14030 The @code{Library_Dir} attribute has a string value that designates the path
14031 (absolute or relative) of the directory where the library will reside.
14032 It must designate an existing directory, and this directory must be writable,
14033 different from the project's object directory and from any source directory
14034 in the project tree.
14035
14036 If both @code{Library_Name} and @code{Library_Dir} are specified and
14037 are legal, then the project file defines a library project.  The optional
14038 library-related attributes are checked only for such project files.
14039
14040 The @code{Library_Kind} attribute has a string value that must be one of the
14041 following (case insensitive): @code{"static"}, @code{"dynamic"} or
14042 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
14043 attribute is not specified, the library is a static library, that is
14044 an archive of object files that can be potentially linked into a
14045 static executable. Otherwise, the library may be dynamic or
14046 relocatable, that is a library that is loaded only at the start of execution.
14047
14048 If you need to build both a static and a dynamic library, you should use two
14049 different object directories, since in some cases some extra code needs to
14050 be generated for the latter. For such cases, it is recommended to either use
14051 two different project files, or a single one which uses external variables
14052 to indicate what kind of library should be build.
14053
14054 The @code{Library_ALI_Dir} attribute may be specified to indicate the
14055 directory where the ALI files of the library will be copied. When it is
14056 not specified, the ALI files are copied to the directory specified in
14057 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
14058 must be writable and different from the project's object directory and from
14059 any source directory in the project tree.
14060
14061 The @code{Library_Version} attribute has a string value whose interpretation
14062 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
14063 used only for dynamic/relocatable libraries as the internal name of the
14064 library (the @code{"soname"}). If the library file name (built from the
14065 @code{Library_Name}) is different from the @code{Library_Version}, then the
14066 library file will be a symbolic link to the actual file whose name will be
14067 @code{Library_Version}.
14068
14069 Example (on Unix):
14070
14071 @smallexample @c projectfile
14072 @group
14073 project Plib is
14074
14075    Version := "1";
14076
14077    for Library_Dir use "lib_dir";
14078    for Library_Name use "dummy";
14079    for Library_Kind use "relocatable";
14080    for Library_Version use "libdummy.so." & Version;
14081
14082 end Plib;
14083 @end group
14084 @end smallexample
14085
14086 @noindent
14087 Directory @file{lib_dir} will contain the internal library file whose name
14088 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
14089 @file{libdummy.so.1}.
14090
14091 When @command{gnatmake} detects that a project file
14092 is a library project file, it will check all immediate sources of the project
14093 and rebuild the library if any of the sources have been recompiled.
14094
14095 Standard project files can import library project files. In such cases,
14096 the libraries will only be rebuilt if some of its sources are recompiled
14097 because they are in the closure of some other source in an importing project.
14098 Sources of the library project files that are not in such a closure will
14099 not be checked, unless the full library is checked, because one of its sources
14100 needs to be recompiled.
14101
14102 For instance, assume the project file @code{A} imports the library project file
14103 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
14104 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
14105 @file{l2.ads}, @file{l2.adb}.
14106
14107 If @file{l1.adb} has been modified, then the library associated with @code{L}
14108 will be rebuilt when compiling all the immediate sources of @code{A} only
14109 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
14110 @code{"with L1;"}.
14111
14112 To be sure that all the sources in the library associated with @code{L} are
14113 up to date, and that all the sources of project @code{A} are also up to date,
14114 the following two commands needs to be used:
14115
14116 @smallexample
14117 gnatmake -Pl.gpr
14118 gnatmake -Pa.gpr
14119 @end smallexample
14120
14121 When a library is built or rebuilt, an attempt is made first to delete all
14122 files in the library directory.
14123 All @file{ALI} files will also be copied from the object directory to the
14124 library directory. To build executables, @command{gnatmake} will use the
14125 library rather than the individual object files.
14126
14127 @ifclear vms
14128 It is also possible to create library project files for third-party libraries
14129 that are precompiled and cannot be compiled locally thanks to the
14130 @code{externally_built} attribute. (See @ref{Installing a library}).
14131 @end ifclear
14132
14133 @c *******************************
14134 @c * Stand-alone Library Projects *
14135 @c *******************************
14136
14137 @node Stand-alone Library Projects
14138 @section Stand-alone Library Projects
14139
14140 @noindent
14141 A Stand-alone Library is a library that contains the necessary code to
14142 elaborate the Ada units that are included in the library. A Stand-alone
14143 Library is suitable to be used in an executable when the main is not
14144 in Ada. However, Stand-alone Libraries may also be used with an Ada main
14145 subprogram.
14146
14147 A Stand-alone Library Project is a Library Project where the library is
14148 a Stand-alone Library.
14149
14150 To be a Stand-alone Library Project, in addition to the two attributes
14151 that make a project a Library Project (@code{Library_Name} and
14152 @code{Library_Dir}, see @ref{Library Projects}), the attribute
14153 @code{Library_Interface} must be defined.
14154
14155 @smallexample @c projectfile
14156 @group
14157    for Library_Dir use "lib_dir";
14158    for Library_Name use "dummy";
14159    for Library_Interface use ("int1", "int1.child");
14160 @end group
14161 @end smallexample
14162
14163 Attribute @code{Library_Interface} has a nonempty string list value,
14164 each string in the list designating a unit contained in an immediate source
14165 of the project file.
14166
14167 When a Stand-alone Library is built, first the binder is invoked to build
14168 a package whose name depends on the library name
14169 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
14170 This binder-generated package includes initialization and
14171 finalization procedures whose
14172 names depend on the library name (dummyinit and dummyfinal in the example
14173 above). The object corresponding to this package is included in the library.
14174
14175 A dynamic or relocatable Stand-alone Library is automatically initialized
14176 if automatic initialization of Stand-alone Libraries is supported on the
14177 platform and if attribute @code{Library_Auto_Init} is not specified or
14178 is specified with the value "true". A static Stand-alone Library is never
14179 automatically initialized.
14180
14181 Single string attribute @code{Library_Auto_Init} may be specified with only
14182 two possible values: "false" or "true" (case-insensitive). Specifying
14183 "false" for attribute @code{Library_Auto_Init} will prevent automatic
14184 initialization of dynamic or relocatable libraries.
14185
14186 When a non-automatically initialized Stand-alone Library is used
14187 in an executable, its initialization procedure must be called before
14188 any service of the library is used.
14189 When the main subprogram is in Ada, it may mean that the initialization
14190 procedure has to be called during elaboration of another package.
14191
14192 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
14193 (those that are listed in attribute @code{Library_Interface}) are copied to
14194 the Library Directory. As a consequence, only the Interface Units may be
14195 imported from Ada units outside of the library. If other units are imported,
14196 the binding phase will fail.
14197
14198 When a Stand-Alone Library is bound, the switches that are specified in
14199 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
14200 used in the call to @command{gnatbind}.
14201
14202 The string list attribute @code{Library_Options} may be used to specified
14203 additional switches to the call to @command{gcc} to link the library.
14204
14205 The attribute @code{Library_Src_Dir}, may be specified for a
14206 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
14207 single string value. Its value must be the path (absolute or relative to the
14208 project directory) of an existing directory. This directory cannot be the
14209 object directory or one of the source directories, but it can be the same as
14210 the library directory. The sources of the Interface
14211 Units of the library, necessary to an Ada client of the library, will be
14212 copied to the designated directory, called Interface Copy directory.
14213 These sources includes the specs of the Interface Units, but they may also
14214 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
14215 are used, or when there is a generic units in the spec. Before the sources
14216 are copied to the Interface Copy directory, an attempt is made to delete all
14217 files in the Interface Copy directory.
14218
14219 @c *************************************
14220 @c * Switches Related to Project Files *
14221 @c *************************************
14222 @node Switches Related to Project Files
14223 @section Switches Related to Project Files
14224
14225 @noindent
14226 The following switches are used by GNAT tools that support project files:
14227
14228 @table @option
14229
14230 @item ^-P^/PROJECT_FILE=^@var{project}
14231 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
14232 Indicates the name of a project file. This project file will be parsed with
14233 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
14234 if any, and using the external references indicated
14235 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
14236 @ifclear vms
14237 There may zero, one or more spaces between @option{-P} and @var{project}.
14238 @end ifclear
14239
14240 @noindent
14241 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
14242
14243 @noindent
14244 Since the Project Manager parses the project file only after all the switches
14245 on the command line are checked, the order of the switches
14246 @option{^-P^/PROJECT_FILE^},
14247 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
14248 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
14249
14250 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
14251 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
14252 Indicates that external variable @var{name} has the value @var{value}.
14253 The Project Manager will use this value for occurrences of
14254 @code{external(name)} when parsing the project file.
14255
14256 @ifclear vms
14257 @noindent
14258 If @var{name} or @var{value} includes a space, then @var{name=value} should be
14259 put between quotes.
14260 @smallexample
14261   -XOS=NT
14262   -X"user=John Doe"
14263 @end smallexample
14264 @end ifclear
14265
14266 @noindent
14267 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
14268 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
14269 @var{name}, only the last one is used.
14270
14271 @noindent
14272 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
14273 takes precedence over the value of the same name in the environment.
14274
14275 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
14276 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
14277 Indicates the verbosity of the parsing of GNAT project files.
14278
14279 @ifclear vms
14280 @option{-vP0} means Default;
14281 @option{-vP1} means Medium;
14282 @option{-vP2} means High.
14283 @end ifclear
14284
14285 @ifset vms
14286 There are three possible options for this qualifier: DEFAULT, MEDIUM and
14287 HIGH.
14288 @end ifset
14289
14290 @noindent
14291 The default is ^Default^DEFAULT^: no output for syntactically correct
14292 project files.
14293 @noindent
14294 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
14295 only the last one is used.
14296
14297 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
14298 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
14299 Add directory <dir> at the beginning of the project search path, in order,
14300 after the current working directory.
14301
14302 @ifclear vms
14303 @item -eL
14304 @cindex @option{-eL} (any project-aware tool)
14305 Follow all symbolic links when processing project files.
14306 @end ifclear
14307
14308 @item ^--subdirs^/SUBDIRS^=<subdir>
14309 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
14310 This switch is recognized by gnatmake and gnatclean. It indicate that the real
14311 directories (except the source directories) are the subdirectories <subdir>
14312 of the directories specified in the project files. This applies in particular
14313 to object directories, library directories and exec directories. If the
14314 subdirectories do not exist, they are created automatically.
14315
14316 @end table
14317
14318 @c **********************************
14319 @c * Tools Supporting Project Files *
14320 @c **********************************
14321
14322 @node  Tools Supporting Project Files
14323 @section Tools Supporting Project Files
14324
14325 @menu
14326 * gnatmake and Project Files::
14327 * The GNAT Driver and Project Files::
14328 @end menu
14329
14330 @node gnatmake and Project Files
14331 @subsection gnatmake and Project Files
14332
14333 @noindent
14334 This section covers several topics related to @command{gnatmake} and
14335 project files: defining ^switches^switches^ for @command{gnatmake}
14336 and for the tools that it invokes; specifying configuration pragmas;
14337 the use of the @code{Main} attribute; building and rebuilding library project
14338 files.
14339
14340 @menu
14341 * ^Switches^Switches^ and Project Files::
14342 * Specifying Configuration Pragmas::
14343 * Project Files and Main Subprograms::
14344 * Library Project Files::
14345 @end menu
14346
14347 @node ^Switches^Switches^ and Project Files
14348 @subsubsection ^Switches^Switches^ and Project Files
14349
14350 @ifset vms
14351 It is not currently possible to specify VMS style qualifiers in the project
14352 files; only Unix style ^switches^switches^ may be specified.
14353 @end ifset
14354
14355 @noindent
14356 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14357 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14358 attribute, a @code{^Switches^Switches^} attribute, or both;
14359 as their names imply, these ^switch^switch^-related
14360 attributes affect the ^switches^switches^ that are used for each of these GNAT
14361 components when
14362 @command{gnatmake} is invoked.  As will be explained below, these
14363 component-specific ^switches^switches^ precede
14364 the ^switches^switches^ provided on the @command{gnatmake} command line.
14365
14366 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14367 array indexed by language name (case insensitive) whose value is a string list.
14368 For example:
14369
14370 @smallexample @c projectfile
14371 @group
14372 package Compiler is
14373   for ^Default_Switches^Default_Switches^ ("Ada")
14374       use ("^-gnaty^-gnaty^",
14375            "^-v^-v^");
14376 end Compiler;
14377 @end group
14378 @end smallexample
14379
14380 @noindent
14381 The @code{^Switches^Switches^} attribute is also an associative array,
14382 indexed by a file name (which may or may not be case sensitive, depending
14383 on the operating system) whose value is a string list.  For example:
14384
14385 @smallexample @c projectfile
14386 @group
14387 package Builder is
14388    for ^Switches^Switches^ ("main1.adb")
14389        use ("^-O2^-O2^");
14390    for ^Switches^Switches^ ("main2.adb")
14391        use ("^-g^-g^");
14392 end Builder;
14393 @end group
14394 @end smallexample
14395
14396 @noindent
14397 For the @code{Builder} package, the file names must designate source files
14398 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
14399 file names must designate @file{ALI} or source files for main subprograms.
14400 In each case just the file name without an explicit extension is acceptable.
14401
14402 For each tool used in a program build (@command{gnatmake}, the compiler, the
14403 binder, and the linker), the corresponding package @dfn{contributes} a set of
14404 ^switches^switches^ for each file on which the tool is invoked, based on the
14405 ^switch^switch^-related attributes defined in the package.
14406 In particular, the ^switches^switches^
14407 that each of these packages contributes for a given file @var{f} comprise:
14408
14409 @itemize @bullet
14410 @item
14411 the value of attribute @code{^Switches^Switches^ (@var{f})},
14412 if it is specified in the package for the given file,
14413 @item
14414 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14415 if it is specified in the package.
14416 @end itemize
14417
14418 @noindent
14419 If neither of these attributes is defined in the package, then the package does
14420 not contribute any ^switches^switches^ for the given file.
14421
14422 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14423 two sets, in the following order: those contributed for the file
14424 by the @code{Builder} package;
14425 and the switches passed on the command line.
14426
14427 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14428 the ^switches^switches^ passed to the tool comprise three sets,
14429 in the following order:
14430
14431 @enumerate
14432 @item
14433 the applicable ^switches^switches^ contributed for the file
14434 by the @code{Builder} package in the project file supplied on the command line;
14435
14436 @item
14437 those contributed for the file by the package (in the relevant project file --
14438 see below) corresponding to the tool; and
14439
14440 @item
14441 the applicable switches passed on the command line.
14442 @end enumerate
14443
14444 @noindent
14445 The term @emph{applicable ^switches^switches^} reflects the fact that
14446 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14447 tools, depending on the individual ^switch^switch^.
14448
14449 @command{gnatmake} may invoke the compiler on source files from different
14450 projects. The Project Manager will use the appropriate project file to
14451 determine the @code{Compiler} package for each source file being compiled.
14452 Likewise for the @code{Binder} and @code{Linker} packages.
14453
14454 As an example, consider the following package in a project file:
14455
14456 @smallexample @c projectfile
14457 @group
14458 project Proj1 is
14459    package Compiler is
14460       for ^Default_Switches^Default_Switches^ ("Ada")
14461           use ("^-g^-g^");
14462       for ^Switches^Switches^ ("a.adb")
14463           use ("^-O1^-O1^");
14464       for ^Switches^Switches^ ("b.adb")
14465           use ("^-O2^-O2^",
14466                "^-gnaty^-gnaty^");
14467    end Compiler;
14468 end Proj1;
14469 @end group
14470 @end smallexample
14471
14472 @noindent
14473 If @command{gnatmake} is invoked with this project file, and it needs to
14474 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14475 @file{a.adb} will be compiled with the ^switch^switch^
14476 @option{^-O1^-O1^},
14477 @file{b.adb} with ^switches^switches^
14478 @option{^-O2^-O2^}
14479 and @option{^-gnaty^-gnaty^},
14480 and @file{c.adb} with @option{^-g^-g^}.
14481
14482 The following example illustrates the ordering of the ^switches^switches^
14483 contributed by different packages:
14484
14485 @smallexample @c projectfile
14486 @group
14487 project Proj2 is
14488    package Builder is
14489       for ^Switches^Switches^ ("main.adb")
14490           use ("^-g^-g^",
14491                "^-O1^-)1^",
14492                "^-f^-f^");
14493    end Builder;
14494 @end group
14495
14496 @group
14497    package Compiler is
14498       for ^Switches^Switches^ ("main.adb")
14499           use ("^-O2^-O2^");
14500    end Compiler;
14501 end Proj2;
14502 @end group
14503 @end smallexample
14504
14505 @noindent
14506 If you issue the command:
14507
14508 @smallexample
14509     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14510 @end smallexample
14511
14512 @noindent
14513 then the compiler will be invoked on @file{main.adb} with the following
14514 sequence of ^switches^switches^
14515
14516 @smallexample
14517    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14518 @end smallexample
14519
14520 with the last @option{^-O^-O^}
14521 ^switch^switch^ having precedence over the earlier ones;
14522 several other ^switches^switches^
14523 (such as @option{^-c^-c^}) are added implicitly.
14524
14525 The ^switches^switches^
14526 @option{^-g^-g^}
14527 and @option{^-O1^-O1^} are contributed by package
14528 @code{Builder},  @option{^-O2^-O2^} is contributed
14529 by the package @code{Compiler}
14530 and @option{^-O0^-O0^} comes from the command line.
14531
14532 The @option{^-g^-g^}
14533 ^switch^switch^ will also be passed in the invocation of
14534 @command{Gnatlink.}
14535
14536 A final example illustrates switch contributions from packages in different
14537 project files:
14538
14539 @smallexample @c projectfile
14540 @group
14541 project Proj3 is
14542    for Source_Files use ("pack.ads", "pack.adb");
14543    package Compiler is
14544       for ^Default_Switches^Default_Switches^ ("Ada")
14545           use ("^-gnata^-gnata^");
14546    end Compiler;
14547 end Proj3;
14548 @end group
14549
14550 @group
14551 with "Proj3";
14552 project Proj4 is
14553    for Source_Files use ("foo_main.adb", "bar_main.adb");
14554    package Builder is
14555       for ^Switches^Switches^ ("foo_main.adb")
14556           use ("^-s^-s^",
14557                "^-g^-g^");
14558    end Builder;
14559 end Proj4;
14560 @end group
14561
14562 @group
14563 -- Ada source file:
14564 with Pack;
14565 procedure Foo_Main is
14566    @dots{}
14567 end Foo_Main;
14568 @end group
14569 @end smallexample
14570
14571 If the command is
14572 @smallexample
14573 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14574 @end smallexample
14575
14576 @noindent
14577 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14578 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14579 @option{^-gnato^-gnato^} (passed on the command line).
14580 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14581 are @option{^-g^-g^} from @code{Proj4.Builder},
14582 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14583 and @option{^-gnato^-gnato^} from the command line.
14584
14585 @noindent
14586 When using @command{gnatmake} with project files, some ^switches^switches^ or
14587 arguments may be expressed as relative paths. As the working directory where
14588 compilation occurs may change, these relative paths are converted to absolute
14589 paths. For the ^switches^switches^ found in a project file, the relative paths
14590 are relative to the project file directory, for the switches on the command
14591 line, they are relative to the directory where @command{gnatmake} is invoked.
14592 The ^switches^switches^ for which this occurs are:
14593 ^-I^-I^,
14594 ^-A^-A^,
14595 ^-L^-L^,
14596 ^-aO^-aO^,
14597 ^-aL^-aL^,
14598 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14599 ^switch^switch^
14600 ^-o^-o^, object files specified in package @code{Linker} or after
14601 -largs on the command line). The exception to this rule is the ^switch^switch^
14602 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14603
14604 @node Specifying Configuration Pragmas
14605 @subsubsection Specifying Configuration Pragmas
14606
14607 When using @command{gnatmake} with project files, if there exists a file
14608 @file{gnat.adc} that contains configuration pragmas, this file will be
14609 ignored.
14610
14611 Configuration pragmas can be defined by means of the following attributes in
14612 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14613 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14614
14615 Both these attributes are single string attributes. Their values is the path
14616 name of a file containing configuration pragmas. If a path name is relative,
14617 then it is relative to the project directory of the project file where the
14618 attribute is defined.
14619
14620 When compiling a source, the configuration pragmas used are, in order,
14621 those listed in the file designated by attribute
14622 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14623 project file, if it is specified, and those listed in the file designated by
14624 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14625 the project file of the source, if it exists.
14626
14627 @node Project Files and Main Subprograms
14628 @subsubsection Project Files and Main Subprograms
14629
14630 @noindent
14631 When using a project file, you can invoke @command{gnatmake}
14632 with one or several main subprograms, by specifying their source files on the
14633 command line.
14634
14635 @smallexample
14636     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14637 @end smallexample
14638
14639 @noindent
14640 Each of these needs to be a source file of the same project, except
14641 when the switch ^-u^/UNIQUE^ is used.
14642
14643 @noindent
14644 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14645 same project, one of the project in the tree rooted at the project specified
14646 on the command line. The package @code{Builder} of this common project, the
14647 "main project" is the one that is considered by @command{gnatmake}.
14648
14649 @noindent
14650 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14651 imported directly or indirectly by the project specified on the command line.
14652 Note that if such a source file is not part of the project specified on the
14653 command line, the ^switches^switches^ found in package @code{Builder} of the
14654 project specified on the command line, if any, that are transmitted
14655 to the compiler will still be used, not those found in the project file of
14656 the source file.
14657
14658 @noindent
14659 When using a project file, you can also invoke @command{gnatmake} without
14660 explicitly specifying any main, and the effect depends on whether you have
14661 defined the @code{Main} attribute.  This attribute has a string list value,
14662 where each element in the list is the name of a source file (the file
14663 extension is optional) that contains a unit that can be a main subprogram.
14664
14665 If the @code{Main} attribute is defined in a project file as a non-empty
14666 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14667 line, then invoking @command{gnatmake} with this project file but without any
14668 main on the command line is equivalent to invoking @command{gnatmake} with all
14669 the file names in the @code{Main} attribute on the command line.
14670
14671 Example:
14672 @smallexample @c projectfile
14673 @group
14674    project Prj is
14675       for Main use ("main1", "main2", "main3");
14676    end Prj;
14677 @end group
14678 @end smallexample
14679
14680 @noindent
14681 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14682 is equivalent to
14683 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14684
14685 When the project attribute @code{Main} is not specified, or is specified
14686 as an empty string list, or when the switch @option{-u} is used on the command
14687 line, then invoking @command{gnatmake} with no main on the command line will
14688 result in all immediate sources of the project file being checked, and
14689 potentially recompiled. Depending on the presence of the switch @option{-u},
14690 sources from other project files on which the immediate sources of the main
14691 project file depend are also checked and potentially recompiled. In other
14692 words, the @option{-u} switch is applied to all of the immediate sources of the
14693 main project file.
14694
14695 When no main is specified on the command line and attribute @code{Main} exists
14696 and includes several mains, or when several mains are specified on the
14697 command line, the default ^switches^switches^ in package @code{Builder} will
14698 be used for all mains, even if there are specific ^switches^switches^
14699 specified for one or several mains.
14700
14701 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14702 the specific ^switches^switches^ for each main, if they are specified.
14703
14704 @node Library Project Files
14705 @subsubsection Library Project Files
14706
14707 @noindent
14708 When @command{gnatmake} is invoked with a main project file that is a library
14709 project file, it is not allowed to specify one or more mains on the command
14710 line.
14711
14712 @noindent
14713 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14714 ^-l^/ACTION=LINK^ have special meanings.
14715
14716 @itemize @bullet
14717 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14718 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14719 library.
14720
14721 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14722 to @command{gnatmake} that the binder generated file should be compiled
14723 (in the case of a stand-alone library) and that the library should be built.
14724
14725 @end itemize
14726
14727 @node The GNAT Driver and Project Files
14728 @subsection The GNAT Driver and Project Files
14729
14730 @noindent
14731 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14732 can benefit from project files:
14733 @command{^gnatbind^gnatbind^},
14734 @command{^gnatcheck^gnatcheck^}),
14735 @command{^gnatclean^gnatclean^}),
14736 @command{^gnatelim^gnatelim^},
14737 @command{^gnatfind^gnatfind^},
14738 @command{^gnatlink^gnatlink^},
14739 @command{^gnatls^gnatls^},
14740 @command{^gnatmetric^gnatmetric^},
14741 @command{^gnatpp^gnatpp^},
14742 @command{^gnatstub^gnatstub^},
14743 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
14744 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14745 They must be invoked through the @command{gnat} driver.
14746
14747 The @command{gnat} driver is a wrapper that accepts a number of commands and
14748 calls the corresponding tool. It was designed initially for VMS platforms (to
14749 convert VMS qualifiers to Unix-style switches), but it is now available on all
14750 GNAT platforms.
14751
14752 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14753 (case insensitive):
14754
14755 @itemize @bullet
14756 @item
14757 BIND to invoke @command{^gnatbind^gnatbind^}
14758 @item
14759 CHOP to invoke @command{^gnatchop^gnatchop^}
14760 @item
14761 CLEAN to invoke @command{^gnatclean^gnatclean^}
14762 @item
14763 COMP or COMPILE to invoke the compiler
14764 @item
14765 ELIM to invoke @command{^gnatelim^gnatelim^}
14766 @item
14767 FIND to invoke @command{^gnatfind^gnatfind^}
14768 @item
14769 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14770 @item
14771 LINK to invoke @command{^gnatlink^gnatlink^}
14772 @item
14773 LS or LIST to invoke @command{^gnatls^gnatls^}
14774 @item
14775 MAKE to invoke @command{^gnatmake^gnatmake^}
14776 @item
14777 NAME to invoke @command{^gnatname^gnatname^}
14778 @item
14779 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14780 @item
14781 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14782 @item
14783 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14784 @item
14785 STUB to invoke @command{^gnatstub^gnatstub^}
14786 @item
14787 XREF to invoke @command{^gnatxref^gnatxref^}
14788 @end itemize
14789
14790 @noindent
14791 (note that the compiler is invoked using the command
14792 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14793
14794 @noindent
14795 On non-VMS platforms, between @command{gnat} and the command, two
14796 special switches may be used:
14797
14798 @itemize @bullet
14799 @item
14800 @command{-v} to display the invocation of the tool.
14801 @item
14802 @command{-dn} to prevent the @command{gnat} driver from removing
14803 the temporary files it has created. These temporary files are
14804 configuration files and temporary file list files.
14805 @end itemize
14806
14807 @noindent
14808 The command may be followed by switches and arguments for the invoked
14809 tool.
14810
14811 @smallexample
14812   gnat bind -C main.ali
14813   gnat ls -a main
14814   gnat chop foo.txt
14815 @end smallexample
14816
14817 @noindent
14818 Switches may also be put in text files, one switch per line, and the text
14819 files may be specified with their path name preceded by '@@'.
14820
14821 @smallexample
14822    gnat bind @@args.txt main.ali
14823 @end smallexample
14824
14825 @noindent
14826 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14827 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14828 (@option{^-P^/PROJECT_FILE^},
14829 @option{^-X^/EXTERNAL_REFERENCE^} and
14830 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14831 the switches of the invoking tool.
14832
14833 @noindent
14834 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14835 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14836 the immediate sources of the specified project file.
14837
14838 @noindent
14839 When GNAT METRIC is used with a project file, but with no source
14840 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14841 with all the immediate sources of the specified project file and with
14842 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14843 of the project.
14844
14845 @noindent
14846 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14847 a project file, no source is specified on the command line and
14848 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14849 the underlying tool (^gnatpp^gnatpp^ or
14850 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14851 not only for the immediate sources of the main project.
14852 @ifclear vms
14853 (-U stands for Universal or Union of the project files of the project tree)
14854 @end ifclear
14855
14856 @noindent
14857 For each of the following commands, there is optionally a corresponding
14858 package in the main project.
14859
14860 @itemize @bullet
14861 @item
14862 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14863
14864 @item
14865 package @code{Check} for command CHECK (invoking
14866 @code{^gnatcheck^gnatcheck^})
14867
14868 @item
14869 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14870
14871 @item
14872 package @code{Cross_Reference} for command XREF (invoking
14873 @code{^gnatxref^gnatxref^})
14874
14875 @item
14876 package @code{Eliminate} for command ELIM (invoking
14877 @code{^gnatelim^gnatelim^})
14878
14879 @item
14880 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14881
14882 @item
14883 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14884
14885 @item
14886 package @code{Gnatstub} for command STUB
14887 (invoking @code{^gnatstub^gnatstub^})
14888
14889 @item
14890 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14891
14892 @item
14893 package @code{Metrics} for command METRIC
14894 (invoking @code{^gnatmetric^gnatmetric^})
14895
14896 @item
14897 package @code{Pretty_Printer} for command PP or PRETTY
14898 (invoking @code{^gnatpp^gnatpp^})
14899
14900 @end itemize
14901
14902 @noindent
14903 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14904 a simple variable with a string list value. It contains ^switches^switches^
14905 for the invocation of @code{^gnatls^gnatls^}.
14906
14907 @smallexample @c projectfile
14908 @group
14909 project Proj1 is
14910    package gnatls is
14911       for ^Switches^Switches^
14912           use ("^-a^-a^",
14913                "^-v^-v^");
14914    end gnatls;
14915 end Proj1;
14916 @end group
14917 @end smallexample
14918
14919 @noindent
14920 All other packages have two attribute @code{^Switches^Switches^} and
14921 @code{^Default_Switches^Default_Switches^}.
14922
14923 @noindent
14924 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14925 source file name, that has a string list value: the ^switches^switches^ to be
14926 used when the tool corresponding to the package is invoked for the specific
14927 source file.
14928
14929 @noindent
14930 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14931 indexed by  the programming language that has a string list value.
14932 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14933 ^switches^switches^ for the invocation of the tool corresponding
14934 to the package, except if a specific @code{^Switches^Switches^} attribute
14935 is specified for the source file.
14936
14937 @smallexample @c projectfile
14938 @group
14939 project Proj is
14940
14941    for Source_Dirs use ("./**");
14942
14943    package gnatls is
14944       for ^Switches^Switches^ use
14945           ("^-a^-a^",
14946            "^-v^-v^");
14947    end gnatls;
14948 @end group
14949 @group
14950
14951    package Compiler is
14952       for ^Default_Switches^Default_Switches^ ("Ada")
14953           use ("^-gnatv^-gnatv^",
14954                "^-gnatwa^-gnatwa^");
14955    end Binder;
14956 @end group
14957 @group
14958
14959    package Binder is
14960       for ^Default_Switches^Default_Switches^ ("Ada")
14961           use ("^-C^-C^",
14962                "^-e^-e^");
14963    end Binder;
14964 @end group
14965 @group
14966
14967    package Linker is
14968       for ^Default_Switches^Default_Switches^ ("Ada")
14969           use ("^-C^-C^");
14970       for ^Switches^Switches^ ("main.adb")
14971           use ("^-C^-C^",
14972                "^-v^-v^",
14973                "^-v^-v^");
14974    end Linker;
14975 @end group
14976 @group
14977
14978    package Finder is
14979       for ^Default_Switches^Default_Switches^ ("Ada")
14980            use ("^-a^-a^",
14981                 "^-f^-f^");
14982    end Finder;
14983 @end group
14984 @group
14985
14986    package Cross_Reference is
14987       for ^Default_Switches^Default_Switches^ ("Ada")
14988           use ("^-a^-a^",
14989                "^-f^-f^",
14990                "^-d^-d^",
14991                "^-u^-u^");
14992    end Cross_Reference;
14993 end Proj;
14994 @end group
14995 @end smallexample
14996
14997 @noindent
14998 With the above project file, commands such as
14999
15000 @smallexample
15001    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
15002    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
15003    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
15004    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
15005    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
15006 @end smallexample
15007
15008 @noindent
15009 will set up the environment properly and invoke the tool with the switches
15010 found in the package corresponding to the tool:
15011 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
15012 except @code{^Switches^Switches^ ("main.adb")}
15013 for @code{^gnatlink^gnatlink^}.
15014 It is also possible to invoke some of the tools,
15015 @code{^gnatcheck^gnatcheck^}),
15016 @code{^gnatmetric^gnatmetric^}),
15017 and @code{^gnatpp^gnatpp^})
15018 on a set of project units thanks to the combination of the switches
15019 @option{-P}, @option{-U} and possibly the main unit when one is interested
15020 in its closure. For instance,
15021 @smallexample
15022 gnat metric -Pproj
15023 @end smallexample
15024 will compute the metrics for all the immediate units of project
15025 @code{proj}.
15026 @smallexample
15027 gnat metric -Pproj -U
15028 @end smallexample
15029 will compute the metrics for all the units of the closure of projects
15030 rooted at @code{proj}.
15031 @smallexample
15032 gnat metric -Pproj -U main_unit
15033 @end smallexample
15034 will compute the metrics for the closure of units rooted at
15035 @code{main_unit}. This last possibility relies implicitly
15036 on @command{gnatbind}'s option @option{-R}.
15037
15038 @c **********************
15039 @node An Extended Example
15040 @section An Extended Example
15041
15042 @noindent
15043 Suppose that we have two programs, @var{prog1} and @var{prog2},
15044 whose sources are in corresponding directories. We would like
15045 to build them with a single @command{gnatmake} command, and we want to place
15046 their object files into @file{build} subdirectories of the source directories.
15047 Furthermore, we want to have to have two separate subdirectories
15048 in @file{build}  -- @file{release} and @file{debug} -- which will contain
15049 the object files compiled with different set of compilation flags.
15050
15051 In other words, we have the following structure:
15052
15053 @smallexample
15054 @group
15055    main
15056      |- prog1
15057      |    |- build
15058      |         | debug
15059      |         | release
15060      |- prog2
15061           |- build
15062                | debug
15063                | release
15064 @end group
15065 @end smallexample
15066
15067 @noindent
15068 Here are the project files that we must place in a directory @file{main}
15069 to maintain this structure:
15070
15071 @enumerate
15072
15073 @item We create a @code{Common} project with a package @code{Compiler} that
15074 specifies the compilation ^switches^switches^:
15075
15076 @smallexample
15077 File "common.gpr":
15078 @group
15079 @b{project} Common @b{is}
15080
15081    @b{for} Source_Dirs @b{use} (); -- No source files
15082 @end group
15083
15084 @group
15085    @b{type} Build_Type @b{is} ("release", "debug");
15086    Build : Build_Type := External ("BUILD", "debug");
15087 @end group
15088 @group
15089    @b{package} Compiler @b{is}
15090       @b{case} Build @b{is}
15091          @b{when} "release" =>
15092            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15093                    @b{use} ("^-O2^-O2^");
15094          @b{when} "debug"   =>
15095            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15096                    @b{use} ("^-g^-g^");
15097       @b{end case};
15098    @b{end} Compiler;
15099
15100 @b{end} Common;
15101 @end group
15102 @end smallexample
15103
15104 @item We create separate projects for the two programs:
15105
15106 @smallexample
15107 @group
15108 File "prog1.gpr":
15109
15110 @b{with} "common";
15111 @b{project} Prog1 @b{is}
15112
15113     @b{for} Source_Dirs @b{use} ("prog1");
15114     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
15115
15116     @b{package} Compiler @b{renames} Common.Compiler;
15117
15118 @b{end} Prog1;
15119 @end group
15120 @end smallexample
15121
15122 @smallexample
15123 @group
15124 File "prog2.gpr":
15125
15126 @b{with} "common";
15127 @b{project} Prog2 @b{is}
15128
15129     @b{for} Source_Dirs @b{use} ("prog2");
15130     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
15131
15132     @b{package} Compiler @b{renames} Common.Compiler;
15133
15134 @end group
15135 @b{end} Prog2;
15136 @end smallexample
15137
15138 @item We create a wrapping project @code{Main}:
15139
15140 @smallexample
15141 @group
15142 File "main.gpr":
15143
15144 @b{with} "common";
15145 @b{with} "prog1";
15146 @b{with} "prog2";
15147 @b{project} Main @b{is}
15148
15149    @b{package} Compiler @b{renames} Common.Compiler;
15150
15151 @b{end} Main;
15152 @end group
15153 @end smallexample
15154
15155 @item Finally we need to create a dummy procedure that @code{with}s (either
15156 explicitly or implicitly) all the sources of our two programs.
15157
15158 @end enumerate
15159
15160 @noindent
15161 Now we can build the programs using the command
15162
15163 @smallexample
15164    gnatmake ^-P^/PROJECT_FILE=^main dummy
15165 @end smallexample
15166
15167 @noindent
15168 for the Debug mode, or
15169
15170 @ifclear vms
15171 @smallexample
15172    gnatmake -Pmain -XBUILD=release
15173 @end smallexample
15174 @end ifclear
15175
15176 @ifset vms
15177 @smallexample
15178    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
15179 @end smallexample
15180 @end ifset
15181
15182 @noindent
15183 for the Release mode.
15184
15185 @c ********************************
15186 @c * Project File Complete Syntax *
15187 @c ********************************
15188
15189 @node Project File Complete Syntax
15190 @section Project File Complete Syntax
15191
15192 @smallexample
15193 project ::=
15194   context_clause project_declaration
15195
15196 context_clause ::=
15197   @{with_clause@}
15198
15199 with_clause ::=
15200   @b{with} path_name @{ , path_name @} ;
15201
15202 path_name ::=
15203    string_literal
15204
15205 project_declaration ::=
15206   simple_project_declaration | project_extension
15207
15208 simple_project_declaration ::=
15209   @b{project} <project_>simple_name @b{is}
15210     @{declarative_item@}
15211   @b{end} <project_>simple_name;
15212
15213 project_extension ::=
15214   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
15215     @{declarative_item@}
15216   @b{end} <project_>simple_name;
15217
15218 declarative_item ::=
15219   package_declaration |
15220   typed_string_declaration |
15221   other_declarative_item
15222
15223 package_declaration ::=
15224   package_spec | package_renaming
15225
15226 package_spec ::=
15227   @b{package} package_identifier @b{is}
15228     @{simple_declarative_item@}
15229   @b{end} package_identifier ;
15230
15231 package_identifier ::=
15232   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
15233   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
15234   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
15235
15236 package_renaming ::==
15237   @b{package} package_identifier @b{renames}
15238        <project_>simple_name.package_identifier ;
15239
15240 typed_string_declaration ::=
15241   @b{type} <typed_string_>_simple_name @b{is}
15242    ( string_literal @{, string_literal@} );
15243
15244 other_declarative_item ::=
15245   attribute_declaration |
15246   typed_variable_declaration |
15247   variable_declaration |
15248   case_construction
15249
15250 attribute_declaration ::=
15251   full_associative_array_declaration |
15252   @b{for} attribute_designator @b{use} expression ;
15253
15254 full_associative_array_declaration ::=
15255   @b{for} <associative_array_attribute_>simple_name @b{use}
15256   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
15257
15258 attribute_designator ::=
15259   <simple_attribute_>simple_name |
15260   <associative_array_attribute_>simple_name ( string_literal )
15261
15262 typed_variable_declaration ::=
15263   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
15264
15265 variable_declaration ::=
15266   <variable_>simple_name := expression;
15267
15268 expression ::=
15269   term @{& term@}
15270
15271 term ::=
15272   literal_string |
15273   string_list |
15274   <variable_>name |
15275   external_value |
15276   attribute_reference
15277
15278 string_literal ::=
15279   (same as Ada)
15280
15281 string_list ::=
15282   ( <string_>expression @{ , <string_>expression @} )
15283
15284 external_value ::=
15285   @b{external} ( string_literal [, string_literal] )
15286
15287 attribute_reference ::=
15288   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
15289
15290 attribute_prefix ::=
15291   @b{project} |
15292   <project_>simple_name | package_identifier |
15293   <project_>simple_name . package_identifier
15294
15295 case_construction ::=
15296   @b{case} <typed_variable_>name @b{is}
15297     @{case_item@}
15298   @b{end case} ;
15299
15300 case_item ::=
15301   @b{when} discrete_choice_list =>
15302       @{case_construction | attribute_declaration@}
15303
15304 discrete_choice_list ::=
15305   string_literal @{| string_literal@} |
15306   @b{others}
15307
15308 name ::=
15309   simple_name @{. simple_name@}
15310
15311 simple_name ::=
15312   identifier (same as Ada)
15313
15314 @end smallexample
15315
15316 @node The Cross-Referencing Tools gnatxref and gnatfind
15317 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
15318 @findex gnatxref
15319 @findex gnatfind
15320
15321 @noindent
15322 The compiler generates cross-referencing information (unless
15323 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
15324 This information indicates where in the source each entity is declared and
15325 referenced. Note that entities in package Standard are not included, but
15326 entities in all other predefined units are included in the output.
15327
15328 Before using any of these two tools, you need to compile successfully your
15329 application, so that GNAT gets a chance to generate the cross-referencing
15330 information.
15331
15332 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
15333 information to provide the user with the capability to easily locate the
15334 declaration and references to an entity. These tools are quite similar,
15335 the difference being that @code{gnatfind} is intended for locating
15336 definitions and/or references to a specified entity or entities, whereas
15337 @code{gnatxref} is oriented to generating a full report of all
15338 cross-references.
15339
15340 To use these tools, you must not compile your application using the
15341 @option{-gnatx} switch on the @command{gnatmake} command line
15342 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
15343 information will not be generated.
15344
15345 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
15346 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15347
15348 @menu
15349 * gnatxref Switches::
15350 * gnatfind Switches::
15351 * Project Files for gnatxref and gnatfind::
15352 * Regular Expressions in gnatfind and gnatxref::
15353 * Examples of gnatxref Usage::
15354 * Examples of gnatfind Usage::
15355 @end menu
15356
15357 @node gnatxref Switches
15358 @section @code{gnatxref} Switches
15359
15360 @noindent
15361 The command invocation for @code{gnatxref} is:
15362 @smallexample
15363 $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15364 @end smallexample
15365
15366 @noindent
15367 where
15368
15369 @table @var
15370 @item sourcefile1
15371 @itemx sourcefile2
15372 identifies the source files for which a report is to be generated. The
15373 ``with''ed units will be processed too. You must provide at least one file.
15374
15375 These file names are considered to be regular expressions, so for instance
15376 specifying @file{source*.adb} is the same as giving every file in the current
15377 directory whose name starts with @file{source} and whose extension is
15378 @file{adb}.
15379
15380 You shouldn't specify any directory name, just base names. @command{gnatxref}
15381 and @command{gnatfind} will be able to locate these files by themselves using
15382 the source path. If you specify directories, no result is produced.
15383
15384 @end table
15385
15386 @noindent
15387 The switches can be:
15388 @table @option
15389 @c !sort!
15390 @item --version
15391 @cindex @option{--version} @command{gnatxref}
15392 Display Copyright and version, then exit disregarding all other options.
15393
15394 @item --help
15395 @cindex @option{--help} @command{gnatxref}
15396 If @option{--version} was not used, display usage, then exit disregarding
15397 all other options.
15398
15399 @item ^-a^/ALL_FILES^
15400 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15401 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15402 the read-only files found in the library search path. Otherwise, these files
15403 will be ignored. This option can be used to protect Gnat sources or your own
15404 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15405 much faster, and their output much smaller. Read-only here refers to access
15406 or permissions status in the file system for the current user.
15407
15408 @item -aIDIR
15409 @cindex @option{-aIDIR} (@command{gnatxref})
15410 When looking for source files also look in directory DIR. The order in which
15411 source file search is undertaken is the same as for @command{gnatmake}.
15412
15413 @item -aODIR
15414 @cindex @option{-aODIR} (@command{gnatxref})
15415 When searching for library and object files, look in directory
15416 DIR. The order in which library files are searched is the same as for
15417 @command{gnatmake}.
15418
15419 @item -nostdinc
15420 @cindex @option{-nostdinc} (@command{gnatxref})
15421 Do not look for sources in the system default directory.
15422
15423 @item -nostdlib
15424 @cindex @option{-nostdlib} (@command{gnatxref})
15425 Do not look for library files in the system default directory.
15426
15427 @item --RTS=@var{rts-path}
15428 @cindex @option{--RTS} (@command{gnatxref})
15429 Specifies the default location of the runtime library. Same meaning as the
15430 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15431
15432 @item ^-d^/DERIVED_TYPES^
15433 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15434 If this switch is set @code{gnatxref} will output the parent type
15435 reference for each matching derived types.
15436
15437 @item ^-f^/FULL_PATHNAME^
15438 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15439 If this switch is set, the output file names will be preceded by their
15440 directory (if the file was found in the search path). If this switch is
15441 not set, the directory will not be printed.
15442
15443 @item ^-g^/IGNORE_LOCALS^
15444 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15445 If this switch is set, information is output only for library-level
15446 entities, ignoring local entities. The use of this switch may accelerate
15447 @code{gnatfind} and @code{gnatxref}.
15448
15449 @item -IDIR
15450 @cindex @option{-IDIR} (@command{gnatxref})
15451 Equivalent to @samp{-aODIR -aIDIR}.
15452
15453 @item -pFILE
15454 @cindex @option{-pFILE} (@command{gnatxref})
15455 Specify a project file to use @xref{Project Files}.
15456 If you need to use the @file{.gpr}
15457 project files, you should use gnatxref through the GNAT driver
15458 (@command{gnat xref -Pproject}).
15459
15460 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15461 project file in the current directory.
15462
15463 If a project file is either specified or found by the tools, then the content
15464 of the source directory and object directory lines are added as if they
15465 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15466 and @samp{^-aO^OBJECT_SEARCH^}.
15467 @item ^-u^/UNUSED^
15468 Output only unused symbols. This may be really useful if you give your
15469 main compilation unit on the command line, as @code{gnatxref} will then
15470 display every unused entity and 'with'ed package.
15471
15472 @ifclear vms
15473 @item -v
15474 Instead of producing the default output, @code{gnatxref} will generate a
15475 @file{tags} file that can be used by vi. For examples how to use this
15476 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15477 to the standard output, thus you will have to redirect it to a file.
15478 @end ifclear
15479
15480 @end table
15481
15482 @noindent
15483 All these switches may be in any order on the command line, and may even
15484 appear after the file names. They need not be separated by spaces, thus
15485 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15486 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15487
15488 @node gnatfind Switches
15489 @section @code{gnatfind} Switches
15490
15491 @noindent
15492 The command line for @code{gnatfind} is:
15493
15494 @smallexample
15495 $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15496       @r{[}@var{file1} @var{file2} @dots{}]
15497 @end smallexample
15498
15499 @noindent
15500 where
15501
15502 @table @var
15503 @item pattern
15504 An entity will be output only if it matches the regular expression found
15505 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15506
15507 Omitting the pattern is equivalent to specifying @samp{*}, which
15508 will match any entity. Note that if you do not provide a pattern, you
15509 have to provide both a sourcefile and a line.
15510
15511 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15512 for matching purposes. At the current time there is no support for
15513 8-bit codes other than Latin-1, or for wide characters in identifiers.
15514
15515 @item sourcefile
15516 @code{gnatfind} will look for references, bodies or declarations
15517 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15518 and column @var{column}. See @ref{Examples of gnatfind Usage}
15519 for syntax examples.
15520
15521 @item line
15522 is a decimal integer identifying the line number containing
15523 the reference to the entity (or entities) to be located.
15524
15525 @item column
15526 is a decimal integer identifying the exact location on the
15527 line of the first character of the identifier for the
15528 entity reference. Columns are numbered from 1.
15529
15530 @item file1 file2 @dots{}
15531 The search will be restricted to these source files. If none are given, then
15532 the search will be done for every library file in the search path.
15533 These file must appear only after the pattern or sourcefile.
15534
15535 These file names are considered to be regular expressions, so for instance
15536 specifying @file{source*.adb} is the same as giving every file in the current
15537 directory whose name starts with @file{source} and whose extension is
15538 @file{adb}.
15539
15540 The location of the spec of the entity will always be displayed, even if it
15541 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
15542 occurrences of the entity in the separate units of the ones given on the
15543 command line will also be displayed.
15544
15545 Note that if you specify at least one file in this part, @code{gnatfind} may
15546 sometimes not be able to find the body of the subprograms.
15547
15548 @end table
15549
15550 @noindent
15551 At least one of 'sourcefile' or 'pattern' has to be present on
15552 the command line.
15553
15554 The following switches are available:
15555 @table @option
15556 @c !sort!
15557
15558 @cindex @option{--version} @command{gnatfind}
15559 Display Copyright and version, then exit disregarding all other options.
15560
15561 @item --help
15562 @cindex @option{--help} @command{gnatfind}
15563 If @option{--version} was not used, display usage, then exit disregarding
15564 all other options.
15565
15566 @item ^-a^/ALL_FILES^
15567 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15568 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15569 the read-only files found in the library search path. Otherwise, these files
15570 will be ignored. This option can be used to protect Gnat sources or your own
15571 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15572 much faster, and their output much smaller. Read-only here refers to access
15573 or permission status in the file system for the current user.
15574
15575 @item -aIDIR
15576 @cindex @option{-aIDIR} (@command{gnatfind})
15577 When looking for source files also look in directory DIR. The order in which
15578 source file search is undertaken is the same as for @command{gnatmake}.
15579
15580 @item -aODIR
15581 @cindex @option{-aODIR} (@command{gnatfind})
15582 When searching for library and object files, look in directory
15583 DIR. The order in which library files are searched is the same as for
15584 @command{gnatmake}.
15585
15586 @item -nostdinc
15587 @cindex @option{-nostdinc} (@command{gnatfind})
15588 Do not look for sources in the system default directory.
15589
15590 @item -nostdlib
15591 @cindex @option{-nostdlib} (@command{gnatfind})
15592 Do not look for library files in the system default directory.
15593
15594 @item --ext=@var{extension}
15595 @cindex @option{--ext} (@command{gnatfind})
15596 Specify an alternate ali file extension. The default is @code{ali} and other
15597 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
15598 switch. Note that if this switch overrides the default, which means that only
15599 the new extension will be considered.
15600
15601 @item --RTS=@var{rts-path}
15602 @cindex @option{--RTS} (@command{gnatfind})
15603 Specifies the default location of the runtime library. Same meaning as the
15604 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15605
15606 @item ^-d^/DERIVED_TYPE_INFORMATION^
15607 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15608 If this switch is set, then @code{gnatfind} will output the parent type
15609 reference for each matching derived types.
15610
15611 @item ^-e^/EXPRESSIONS^
15612 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15613 By default, @code{gnatfind} accept the simple regular expression set for
15614 @samp{pattern}. If this switch is set, then the pattern will be
15615 considered as full Unix-style regular expression.
15616
15617 @item ^-f^/FULL_PATHNAME^
15618 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15619 If this switch is set, the output file names will be preceded by their
15620 directory (if the file was found in the search path). If this switch is
15621 not set, the directory will not be printed.
15622
15623 @item ^-g^/IGNORE_LOCALS^
15624 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15625 If this switch is set, information is output only for library-level
15626 entities, ignoring local entities. The use of this switch may accelerate
15627 @code{gnatfind} and @code{gnatxref}.
15628
15629 @item -IDIR
15630 @cindex @option{-IDIR} (@command{gnatfind})
15631 Equivalent to @samp{-aODIR -aIDIR}.
15632
15633 @item -pFILE
15634 @cindex @option{-pFILE} (@command{gnatfind})
15635 Specify a project file (@pxref{Project Files}) to use.
15636 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15637 project file in the current directory.
15638
15639 If a project file is either specified or found by the tools, then the content
15640 of the source directory and object directory lines are added as if they
15641 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15642 @samp{^-aO^/OBJECT_SEARCH^}.
15643
15644 @item ^-r^/REFERENCES^
15645 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15646 By default, @code{gnatfind} will output only the information about the
15647 declaration, body or type completion of the entities. If this switch is
15648 set, the @code{gnatfind} will locate every reference to the entities in
15649 the files specified on the command line (or in every file in the search
15650 path if no file is given on the command line).
15651
15652 @item ^-s^/PRINT_LINES^
15653 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15654 If this switch is set, then @code{gnatfind} will output the content
15655 of the Ada source file lines were the entity was found.
15656
15657 @item ^-t^/TYPE_HIERARCHY^
15658 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15659 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15660 the specified type. It act like -d option but recursively from parent
15661 type to parent type. When this switch is set it is not possible to
15662 specify more than one file.
15663
15664 @end table
15665
15666 @noindent
15667 All these switches may be in any order on the command line, and may even
15668 appear after the file names. They need not be separated by spaces, thus
15669 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15670 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15671
15672 As stated previously, gnatfind will search in every directory in the
15673 search path. You can force it to look only in the current directory if
15674 you specify @code{*} at the end of the command line.
15675
15676 @node Project Files for gnatxref and gnatfind
15677 @section Project Files for @command{gnatxref} and @command{gnatfind}
15678
15679 @noindent
15680 Project files allow a programmer to specify how to compile its
15681 application, where to find sources, etc.  These files are used
15682 @ifclear vms
15683 primarily by GPS, but they can also be used
15684 @end ifclear
15685 by the two tools
15686 @code{gnatxref} and @code{gnatfind}.
15687
15688 A project file name must end with @file{.gpr}. If a single one is
15689 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15690 extract the information from it. If multiple project files are found, none of
15691 them is read, and you have to use the @samp{-p} switch to specify the one
15692 you want to use.
15693
15694 The following lines can be included, even though most of them have default
15695 values which can be used in most cases.
15696 The lines can be entered in any order in the file.
15697 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15698 each line. If you have multiple instances, only the last one is taken into
15699 account.
15700
15701 @table @code
15702 @item src_dir=DIR
15703 [default: @code{"^./^[]^"}]
15704 specifies a directory where to look for source files. Multiple @code{src_dir}
15705 lines can be specified and they will be searched in the order they
15706 are specified.
15707
15708 @item obj_dir=DIR
15709 [default: @code{"^./^[]^"}]
15710 specifies a directory where to look for object and library files. Multiple
15711 @code{obj_dir} lines can be specified, and they will be searched in the order
15712 they are specified
15713
15714 @item comp_opt=SWITCHES
15715 [default: @code{""}]
15716 creates a variable which can be referred to subsequently by using
15717 the @code{$@{comp_opt@}} notation. This is intended to store the default
15718 switches given to @command{gnatmake} and @command{gcc}.
15719
15720 @item bind_opt=SWITCHES
15721 [default: @code{""}]
15722 creates a variable which can be referred to subsequently by using
15723 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15724 switches given to @command{gnatbind}.
15725
15726 @item link_opt=SWITCHES
15727 [default: @code{""}]
15728 creates a variable which can be referred to subsequently by using
15729 the @samp{$@{link_opt@}} notation. This is intended to store the default
15730 switches given to @command{gnatlink}.
15731
15732 @item main=EXECUTABLE
15733 [default: @code{""}]
15734 specifies the name of the executable for the application. This variable can
15735 be referred to in the following lines by using the @samp{$@{main@}} notation.
15736
15737 @ifset vms
15738 @item comp_cmd=COMMAND
15739 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15740 @end ifset
15741 @ifclear vms
15742 @item comp_cmd=COMMAND
15743 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15744 @end ifclear
15745 specifies the command used to compile a single file in the application.
15746
15747 @ifset vms
15748 @item make_cmd=COMMAND
15749 [default: @code{"GNAT MAKE $@{main@}
15750 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15751 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15752 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15753 @end ifset
15754 @ifclear vms
15755 @item make_cmd=COMMAND
15756 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15757 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15758 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15759 @end ifclear
15760 specifies the command used to recompile the whole application.
15761
15762 @item run_cmd=COMMAND
15763 [default: @code{"$@{main@}"}]
15764 specifies the command used to run the application.
15765
15766 @item debug_cmd=COMMAND
15767 [default: @code{"gdb $@{main@}"}]
15768 specifies the command used to debug the application
15769
15770 @end table
15771
15772 @noindent
15773 @command{gnatxref} and @command{gnatfind} only take into account the
15774 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15775
15776 @node Regular Expressions in gnatfind and gnatxref
15777 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15778
15779 @noindent
15780 As specified in the section about @command{gnatfind}, the pattern can be a
15781 regular expression. Actually, there are to set of regular expressions
15782 which are recognized by the program:
15783
15784 @table @code
15785 @item globbing patterns
15786 These are the most usual regular expression. They are the same that you
15787 generally used in a Unix shell command line, or in a DOS session.
15788
15789 Here is a more formal grammar:
15790 @smallexample
15791 @group
15792 @iftex
15793 @leftskip=.5cm
15794 @end iftex
15795 regexp ::= term
15796 term   ::= elmt            -- matches elmt
15797 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15798 term   ::= *               -- any string of 0 or more characters
15799 term   ::= ?               -- matches any character
15800 term   ::= [char @{char@}]   -- matches any character listed
15801 term   ::= [char - char]   -- matches any character in range
15802 @end group
15803 @end smallexample
15804
15805 @item full regular expression
15806 The second set of regular expressions is much more powerful. This is the
15807 type of regular expressions recognized by utilities such a @file{grep}.
15808
15809 The following is the form of a regular expression, expressed in Ada
15810 reference manual style BNF is as follows
15811
15812 @smallexample
15813 @iftex
15814 @leftskip=.5cm
15815 @end iftex
15816 @group
15817 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
15818
15819 term ::= item @{item@}       -- concatenation (item then item)
15820
15821 item ::= elmt              -- match elmt
15822 item ::= elmt *            -- zero or more elmt's
15823 item ::= elmt +            -- one or more elmt's
15824 item ::= elmt ?            -- matches elmt or nothing
15825 @end group
15826 @group
15827 elmt ::= nschar            -- matches given character
15828 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15829 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15830 elmt ::= [char - char]     -- matches chars in given range
15831 elmt ::= \ char            -- matches given character
15832 elmt ::= .                 -- matches any single character
15833 elmt ::= ( regexp )        -- parens used for grouping
15834
15835 char ::= any character, including special characters
15836 nschar ::= any character except ()[].*+?^^^
15837 @end group
15838 @end smallexample
15839
15840 Following are a few examples:
15841
15842 @table @samp
15843 @item abcde|fghi
15844 will match any of the two strings @samp{abcde} and @samp{fghi},
15845
15846 @item abc*d
15847 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15848 @samp{abcccd}, and so on,
15849
15850 @item [a-z]+
15851 will match any string which has only lowercase characters in it (and at
15852 least one character.
15853
15854 @end table
15855 @end table
15856
15857 @node Examples of gnatxref Usage
15858 @section Examples of @code{gnatxref} Usage
15859
15860 @subsection General Usage
15861
15862 @noindent
15863 For the following examples, we will consider the following units:
15864
15865 @smallexample @c ada
15866 @group
15867 @cartouche
15868 main.ads:
15869 1: with Bar;
15870 2: package Main is
15871 3:     procedure Foo (B : in Integer);
15872 4:     C : Integer;
15873 5: private
15874 6:     D : Integer;
15875 7: end Main;
15876
15877 main.adb:
15878 1: package body Main is
15879 2:     procedure Foo (B : in Integer) is
15880 3:     begin
15881 4:        C := B;
15882 5:        D := B;
15883 6:        Bar.Print (B);
15884 7:        Bar.Print (C);
15885 8:     end Foo;
15886 9: end Main;
15887
15888 bar.ads:
15889 1: package Bar is
15890 2:     procedure Print (B : Integer);
15891 3: end bar;
15892 @end cartouche
15893 @end group
15894 @end smallexample
15895
15896 @table @code
15897
15898 @noindent
15899 The first thing to do is to recompile your application (for instance, in
15900 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15901 the cross-referencing information.
15902 You can then issue any of the following commands:
15903
15904 @item gnatxref main.adb
15905 @code{gnatxref} generates cross-reference information for main.adb
15906 and every unit 'with'ed by main.adb.
15907
15908 The output would be:
15909 @smallexample
15910 @iftex
15911 @leftskip=0cm
15912 @end iftex
15913 B                                                      Type: Integer
15914   Decl: bar.ads           2:22
15915 B                                                      Type: Integer
15916   Decl: main.ads          3:20
15917   Body: main.adb          2:20
15918   Ref:  main.adb          4:13     5:13     6:19
15919 Bar                                                    Type: Unit
15920   Decl: bar.ads           1:9
15921   Ref:  main.adb          6:8      7:8
15922        main.ads           1:6
15923 C                                                      Type: Integer
15924   Decl: main.ads          4:5
15925   Modi: main.adb          4:8
15926   Ref:  main.adb          7:19
15927 D                                                      Type: Integer
15928   Decl: main.ads          6:5
15929   Modi: main.adb          5:8
15930 Foo                                                    Type: Unit
15931   Decl: main.ads          3:15
15932   Body: main.adb          2:15
15933 Main                                                    Type: Unit
15934   Decl: main.ads          2:9
15935   Body: main.adb          1:14
15936 Print                                                   Type: Unit
15937   Decl: bar.ads           2:15
15938   Ref:  main.adb          6:12     7:12
15939 @end smallexample
15940
15941 @noindent
15942 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15943 its body is in main.adb, line 1, column 14 and is not referenced any where.
15944
15945 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15946 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15947
15948 @item gnatxref package1.adb package2.ads
15949 @code{gnatxref} will generates cross-reference information for
15950 package1.adb, package2.ads and any other package 'with'ed by any
15951 of these.
15952
15953 @end table
15954
15955 @ifclear vms
15956 @subsection Using gnatxref with vi
15957
15958 @code{gnatxref} can generate a tags file output, which can be used
15959 directly from @command{vi}. Note that the standard version of @command{vi}
15960 will not work properly with overloaded symbols. Consider using another
15961 free implementation of @command{vi}, such as @command{vim}.
15962
15963 @smallexample
15964 $ gnatxref -v gnatfind.adb > tags
15965 @end smallexample
15966
15967 @noindent
15968 will generate the tags file for @code{gnatfind} itself (if the sources
15969 are in the search path!).
15970
15971 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
15972 (replacing @var{entity} by whatever you are looking for), and vi will
15973 display a new file with the corresponding declaration of entity.
15974 @end ifclear
15975
15976 @node Examples of gnatfind Usage
15977 @section Examples of @code{gnatfind} Usage
15978
15979 @table @code
15980
15981 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15982 Find declarations for all entities xyz referenced at least once in
15983 main.adb. The references are search in every library file in the search
15984 path.
15985
15986 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15987 switch is set)
15988
15989 The output will look like:
15990 @smallexample
15991 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15992 ^directory/^[directory]^main.adb:24:10: xyz <= body
15993 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15994 @end smallexample
15995
15996 @noindent
15997 that is to say, one of the entities xyz found in main.adb is declared at
15998 line 12 of main.ads (and its body is in main.adb), and another one is
15999 declared at line 45 of foo.ads
16000
16001 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
16002 This is the same command as the previous one, instead @code{gnatfind} will
16003 display the content of the Ada source file lines.
16004
16005 The output will look like:
16006
16007 @smallexample
16008 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
16009    procedure xyz;
16010 ^directory/^[directory]^main.adb:24:10: xyz <= body
16011    procedure xyz is
16012 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
16013    xyz : Integer;
16014 @end smallexample
16015
16016 @noindent
16017 This can make it easier to find exactly the location your are looking
16018 for.
16019
16020 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
16021 Find references to all entities containing an x that are
16022 referenced on line 123 of main.ads.
16023 The references will be searched only in main.ads and foo.adb.
16024
16025 @item gnatfind main.ads:123
16026 Find declarations and bodies for all entities that are referenced on
16027 line 123 of main.ads.
16028
16029 This is the same as @code{gnatfind "*":main.adb:123}.
16030
16031 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
16032 Find the declaration for the entity referenced at column 45 in
16033 line 123 of file main.adb in directory mydir. Note that it
16034 is usual to omit the identifier name when the column is given,
16035 since the column position identifies a unique reference.
16036
16037 The column has to be the beginning of the identifier, and should not
16038 point to any character in the middle of the identifier.
16039
16040 @end table
16041
16042 @c *********************************
16043 @node The GNAT Pretty-Printer gnatpp
16044 @chapter The GNAT Pretty-Printer @command{gnatpp}
16045 @findex gnatpp
16046 @cindex Pretty-Printer
16047
16048 @noindent
16049 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
16050 for source reformatting / pretty-printing.
16051 It takes an Ada source file as input and generates a reformatted
16052 version as output.
16053 You can specify various style directives via switches; e.g.,
16054 identifier case conventions, rules of indentation, and comment layout.
16055
16056 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
16057 tree for the input source and thus requires the input to be syntactically and
16058 semantically legal.
16059 If this condition is not met, @command{gnatpp} will terminate with an
16060 error message; no output file will be generated.
16061
16062 If the source files presented to @command{gnatpp} contain
16063 preprocessing directives, then the output file will
16064 correspond to the generated source after all
16065 preprocessing is carried out. There is no way
16066 using @command{gnatpp} to obtain pretty printed files that
16067 include the preprocessing directives.
16068
16069 If the compilation unit
16070 contained in the input source depends semantically upon units located
16071 outside the current directory, you have to provide the source search path
16072 when invoking @command{gnatpp}, if these units are contained in files with
16073 names that do not follow the GNAT file naming rules, you have to provide
16074 the configuration file describing the corresponding naming scheme;
16075 see the description of the @command{gnatpp}
16076 switches below. Another possibility is to use a project file and to
16077 call @command{gnatpp} through the @command{gnat} driver
16078
16079 The @command{gnatpp} command has the form
16080
16081 @smallexample
16082 $ gnatpp @ovar{switches} @var{filename}
16083 @end smallexample
16084
16085 @noindent
16086 where
16087 @itemize @bullet
16088 @item
16089 @var{switches} is an optional sequence of switches defining such properties as
16090 the formatting rules, the source search path, and the destination for the
16091 output source file
16092
16093 @item
16094 @var{filename} is the name (including the extension) of the source file to
16095 reformat; ``wildcards'' or several file names on the same gnatpp command are
16096 allowed.  The file name may contain path information; it does not have to
16097 follow the GNAT file naming rules
16098 @end itemize
16099
16100 @menu
16101 * Switches for gnatpp::
16102 * Formatting Rules::
16103 @end menu
16104
16105 @node Switches for gnatpp
16106 @section Switches for @command{gnatpp}
16107
16108 @noindent
16109 The following subsections describe the various switches accepted by
16110 @command{gnatpp}, organized by category.
16111
16112 @ifclear vms
16113 You specify a switch by supplying a name and generally also a value.
16114 In many cases the values for a switch with a given name are incompatible with
16115 each other
16116 (for example the switch that controls the casing of a reserved word may have
16117 exactly one value: upper case, lower case, or
16118 mixed case) and thus exactly one such switch can be in effect for an
16119 invocation of @command{gnatpp}.
16120 If more than one is supplied, the last one is used.
16121 However, some values for the same switch are mutually compatible.
16122 You may supply several such switches to @command{gnatpp}, but then
16123 each must be specified in full, with both the name and the value.
16124 Abbreviated forms (the name appearing once, followed by each value) are
16125 not permitted.
16126 For example, to set
16127 the alignment of the assignment delimiter both in declarations and in
16128 assignment statements, you must write @option{-A2A3}
16129 (or @option{-A2 -A3}), but not @option{-A23}.
16130 @end ifclear
16131
16132 @ifset vms
16133 In many cases the set of options for a given qualifier are incompatible with
16134 each other (for example the qualifier that controls the casing of a reserved
16135 word may have exactly one option, which specifies either upper case, lower
16136 case, or mixed case), and thus exactly one such option can be in effect for
16137 an invocation of @command{gnatpp}.
16138 If more than one is supplied, the last one is used.
16139 However, some qualifiers have options that are mutually compatible,
16140 and then you may then supply several such options when invoking
16141 @command{gnatpp}.
16142 @end ifset
16143
16144 In most cases, it is obvious whether or not the
16145 ^values for a switch with a given name^options for a given qualifier^
16146 are compatible with each other.
16147 When the semantics might not be evident, the summaries below explicitly
16148 indicate the effect.
16149
16150 @menu
16151 * Alignment Control::
16152 * Casing Control::
16153 * Construct Layout Control::
16154 * General Text Layout Control::
16155 * Other Formatting Options::
16156 * Setting the Source Search Path::
16157 * Output File Control::
16158 * Other gnatpp Switches::
16159 @end menu
16160
16161 @node Alignment Control
16162 @subsection Alignment Control
16163 @cindex Alignment control in @command{gnatpp}
16164
16165 @noindent
16166 Programs can be easier to read if certain constructs are vertically aligned.
16167 By default all alignments are set ON.
16168 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
16169 OFF, and then use one or more of the other
16170 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
16171 to activate alignment for specific constructs.
16172
16173 @table @option
16174 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
16175
16176 @ifset vms
16177 @item /ALIGN=ON
16178 Set all alignments to ON
16179 @end ifset
16180
16181 @item ^-A0^/ALIGN=OFF^
16182 Set all alignments to OFF
16183
16184 @item ^-A1^/ALIGN=COLONS^
16185 Align @code{:} in declarations
16186
16187 @item ^-A2^/ALIGN=DECLARATIONS^
16188 Align @code{:=} in initializations in declarations
16189
16190 @item ^-A3^/ALIGN=STATEMENTS^
16191 Align @code{:=} in assignment statements
16192
16193 @item ^-A4^/ALIGN=ARROWS^
16194 Align @code{=>} in associations
16195
16196 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
16197 Align @code{at} keywords in the component clauses in record
16198 representation clauses
16199 @end table
16200
16201 @noindent
16202 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
16203 is allowed.
16204
16205 @node Casing Control
16206 @subsection Casing Control
16207 @cindex Casing control in @command{gnatpp}
16208
16209 @noindent
16210 @command{gnatpp} allows you to specify the casing for reserved words,
16211 pragma names, attribute designators and identifiers.
16212 For identifiers you may define a
16213 general rule for name casing but also override this rule
16214 via a set of dictionary files.
16215
16216 Three types of casing are supported: lower case, upper case, and mixed case.
16217 Lower and upper case are self-explanatory (but since some letters in
16218 Latin1 and other GNAT-supported character sets
16219 exist only in lower-case form, an upper case conversion will have no
16220 effect on them.)
16221 ``Mixed case'' means that the first letter, and also each letter immediately
16222 following an underscore, are converted to their uppercase forms;
16223 all the other letters are converted to their lowercase forms.
16224
16225 @table @option
16226 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
16227 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
16228 Attribute designators are lower case
16229
16230 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
16231 Attribute designators are upper case
16232
16233 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
16234 Attribute designators are mixed case (this is the default)
16235
16236 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
16237 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
16238 Keywords (technically, these are known in Ada as @emph{reserved words}) are
16239 lower case (this is the default)
16240
16241 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
16242 Keywords are upper case
16243
16244 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
16245 @item ^-nD^/NAME_CASING=AS_DECLARED^
16246 Name casing for defining occurrences are as they appear in the source file
16247 (this is the default)
16248
16249 @item ^-nU^/NAME_CASING=UPPER_CASE^
16250 Names are in upper case
16251
16252 @item ^-nL^/NAME_CASING=LOWER_CASE^
16253 Names are in lower case
16254
16255 @item ^-nM^/NAME_CASING=MIXED_CASE^
16256 Names are in mixed case
16257
16258 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
16259 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
16260 Pragma names are lower case
16261
16262 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
16263 Pragma names are upper case
16264
16265 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
16266 Pragma names are mixed case (this is the default)
16267
16268 @item ^-D@var{file}^/DICTIONARY=@var{file}^
16269 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
16270 Use @var{file} as a @emph{dictionary file} that defines
16271 the casing for a set of specified names,
16272 thereby overriding the effect on these names by
16273 any explicit or implicit
16274 ^-n^/NAME_CASING^ switch.
16275 To supply more than one dictionary file,
16276 use ^several @option{-D} switches^a list of files as options^.
16277
16278 @noindent
16279 @option{gnatpp} implicitly uses a @emph{default dictionary file}
16280 to define the casing for the Ada predefined names and
16281 the names declared in the GNAT libraries.
16282
16283 @item ^-D-^/SPECIFIC_CASING^
16284 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
16285 Do not use the default dictionary file;
16286 instead, use the casing
16287 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
16288 dictionary file(s)
16289 @end table
16290
16291 @noindent
16292 The structure of a dictionary file, and details on the conventions
16293 used in the default dictionary file, are defined in @ref{Name Casing}.
16294
16295 The @option{^-D-^/SPECIFIC_CASING^} and
16296 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
16297 compatible.
16298
16299 @node Construct Layout Control
16300 @subsection Construct Layout Control
16301 @cindex Layout control in @command{gnatpp}
16302
16303 @noindent
16304 This group of @command{gnatpp} switches controls the layout of comments and
16305 complex syntactic constructs.  See @ref{Formatting Comments} for details
16306 on their effect.
16307
16308 @table @option
16309 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
16310 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
16311 All the comments remain unchanged
16312
16313 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
16314 GNAT-style comment line indentation (this is the default).
16315
16316 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
16317 Reference-manual comment line indentation.
16318
16319 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
16320 GNAT-style comment beginning
16321
16322 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
16323 Reformat comment blocks
16324
16325 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
16326 Keep unchanged special form comments
16327
16328 Reformat comment blocks
16329
16330 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
16331 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
16332 GNAT-style layout (this is the default)
16333
16334 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
16335 Compact layout
16336
16337 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
16338 Uncompact layout
16339
16340 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
16341 @item ^-N^/NOTABS^
16342 All the VT characters are removed from the comment text. All the HT characters
16343 are expanded with the sequences of space characters to get to the next tab
16344 stops.
16345
16346 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
16347 @item ^--no-separate-is^/NO_SEPARATE_IS^
16348 Do not place the keyword @code{is} on a separate line in a subprogram body in
16349 case if the spec occupies more then one line.
16350
16351 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
16352 @item ^--separate-label^/SEPARATE_LABEL^
16353 Place statement label(s) on a separate line, with the following statement
16354 on the next line.
16355
16356 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
16357 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
16358 Place the keyword @code{loop} in FOR and WHILE loop statements and the
16359 keyword @code{then} in IF statements on a separate line.
16360
16361 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
16362 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
16363 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
16364 keyword @code{then} in IF statements on a separate line. This option is
16365 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16366
16367 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16368 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16369 Start each USE clause in a context clause from a separate line.
16370
16371 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16372 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16373 Use a separate line for a loop or block statement name, but do not use an extra
16374 indentation level for the statement itself.
16375
16376 @end table
16377
16378 @ifclear vms
16379 @noindent
16380 The @option{-c1} and @option{-c2} switches are incompatible.
16381 The @option{-c3} and @option{-c4} switches are compatible with each other and
16382 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16383 the other comment formatting switches.
16384
16385 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16386 @end ifclear
16387
16388 @ifset vms
16389 @noindent
16390 For the @option{/COMMENTS_LAYOUT} qualifier:
16391 @itemize @bullet
16392 @item
16393 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16394 @item
16395 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16396 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16397 @end itemize
16398
16399 @noindent
16400 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16401 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16402 @end ifset
16403
16404 @node General Text Layout Control
16405 @subsection General Text Layout Control
16406
16407 @noindent
16408 These switches allow control over line length and indentation.
16409
16410 @table @option
16411 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16412 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16413 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16414
16415 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16416 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16417 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16418
16419 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16420 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16421 Indentation level for continuation lines (relative to the line being
16422 continued), @var{nnn} from 1@dots{}9.
16423 The default
16424 value is one less then the (normal) indentation level, unless the
16425 indentation is set to 1 (in which case the default value for continuation
16426 line indentation is also 1)
16427 @end table
16428
16429 @node Other Formatting Options
16430 @subsection Other Formatting Options
16431
16432 @noindent
16433 These switches control the inclusion of missing end/exit labels, and
16434 the indentation level in @b{case} statements.
16435
16436 @table @option
16437 @item ^-e^/NO_MISSED_LABELS^
16438 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16439 Do not insert missing end/exit labels. An end label is the name of
16440 a construct that may optionally be repeated at the end of the
16441 construct's declaration;
16442 e.g., the names of packages, subprograms, and tasks.
16443 An exit label is the name of a loop that may appear as target
16444 of an exit statement within the loop.
16445 By default, @command{gnatpp} inserts these end/exit labels when
16446 they are absent from the original source. This option suppresses such
16447 insertion, so that the formatted source reflects the original.
16448
16449 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16450 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16451 Insert a Form Feed character after a pragma Page.
16452
16453 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16454 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16455 Do not use an additional indentation level for @b{case} alternatives
16456 and variants if there are @var{nnn} or more (the default
16457 value is 10).
16458 If @var{nnn} is 0, an additional indentation level is
16459 used for @b{case} alternatives and variants regardless of their number.
16460 @end table
16461
16462 @node Setting the Source Search Path
16463 @subsection Setting the Source Search Path
16464
16465 @noindent
16466 To define the search path for the input source file, @command{gnatpp}
16467 uses the same switches as the GNAT compiler, with the same effects.
16468
16469 @table @option
16470 @item ^-I^/SEARCH=^@var{dir}
16471 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16472 The same as the corresponding gcc switch
16473
16474 @item ^-I-^/NOCURRENT_DIRECTORY^
16475 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16476 The same as the corresponding gcc switch
16477
16478 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16479 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16480 The same as the corresponding gcc switch
16481
16482 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16483 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16484 The same as the corresponding gcc switch
16485
16486 @end table
16487
16488 @node Output File Control
16489 @subsection Output File Control
16490
16491 @noindent
16492 By default the output is sent to the file whose name is obtained by appending
16493 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16494 (if the file with this name already exists, it is unconditionally overwritten).
16495 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16496 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16497 as output file.
16498 The output may be redirected by the following switches:
16499
16500 @table @option
16501 @item ^-pipe^/STANDARD_OUTPUT^
16502 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16503 Send the output to @code{Standard_Output}
16504
16505 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16506 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16507 Write the output into @var{output_file}.
16508 If @var{output_file} already exists, @command{gnatpp} terminates without
16509 reading or processing the input file.
16510
16511 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16512 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16513 Write the output into @var{output_file}, overwriting the existing file
16514 (if one is present).
16515
16516 @item ^-r^/REPLACE^
16517 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16518 Replace the input source file with the reformatted output, and copy the
16519 original input source into the file whose name is obtained by appending the
16520 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16521 If a file with this name already exists, @command{gnatpp} terminates without
16522 reading or processing the input file.
16523
16524 @item ^-rf^/OVERRIDING_REPLACE^
16525 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16526 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16527 already exists, it is overwritten.
16528
16529 @item ^-rnb^/REPLACE_NO_BACKUP^
16530 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16531 Replace the input source file with the reformatted output without
16532 creating any backup copy of the input source.
16533
16534 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16535 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16536 Specifies the format of the reformatted output file. The @var{xxx}
16537 ^string specified with the switch^option^ may be either
16538 @itemize @bullet
16539 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16540 @item ``@option{^crlf^CRLF^}''
16541 the same as @option{^crlf^CRLF^}
16542 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16543 @item ``@option{^lf^LF^}''
16544 the same as @option{^unix^UNIX^}
16545 @end itemize
16546
16547 @item ^-W^/RESULT_ENCODING=^@var{e}
16548 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16549 Specify the wide character encoding method used to write the code in the
16550 result file
16551 @var{e} is one of the following:
16552
16553 @itemize @bullet
16554
16555 @item ^h^HEX^
16556 Hex encoding
16557
16558 @item ^u^UPPER^
16559 Upper half encoding
16560
16561 @item ^s^SHIFT_JIS^
16562 Shift/JIS encoding
16563
16564 @item ^e^EUC^
16565 EUC encoding
16566
16567 @item ^8^UTF8^
16568 UTF-8 encoding
16569
16570 @item ^b^BRACKETS^
16571 Brackets encoding (default value)
16572 @end itemize
16573
16574 @end table
16575
16576 @noindent
16577 Options @option{^-pipe^/STANDARD_OUTPUT^},
16578 @option{^-o^/OUTPUT^} and
16579 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16580 contains only one file to reformat.
16581 Option
16582 @option{^--eol^/END_OF_LINE^}
16583 and
16584 @option{^-W^/RESULT_ENCODING^}
16585 cannot be used together
16586 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16587
16588 @node Other gnatpp Switches
16589 @subsection Other @code{gnatpp} Switches
16590
16591 @noindent
16592 The additional @command{gnatpp} switches are defined in this subsection.
16593
16594 @table @option
16595 @item ^-files @var{filename}^/FILES=@var{output_file}^
16596 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16597 Take the argument source files from the specified file. This file should be an
16598 ordinary textual file containing file names separated by spaces or
16599 line breaks. You can use this switch more then once in the same call to
16600 @command{gnatpp}. You also can combine this switch with explicit list of
16601 files.
16602
16603 @item ^-v^/VERBOSE^
16604 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16605 Verbose mode;
16606 @command{gnatpp} generates version information and then
16607 a trace of the actions it takes to produce or obtain the ASIS tree.
16608
16609 @item ^-w^/WARNINGS^
16610 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16611 Warning mode;
16612 @command{gnatpp} generates a warning whenever it cannot provide
16613 a required layout in the result source.
16614 @end table
16615
16616 @node Formatting Rules
16617 @section Formatting Rules
16618
16619 @noindent
16620 The following subsections show how @command{gnatpp} treats ``white space'',
16621 comments, program layout, and name casing.
16622 They provide the detailed descriptions of the switches shown above.
16623
16624 @menu
16625 * White Space and Empty Lines::
16626 * Formatting Comments::
16627 * Construct Layout::
16628 * Name Casing::
16629 @end menu
16630
16631 @node White Space and Empty Lines
16632 @subsection White Space and Empty Lines
16633
16634 @noindent
16635 @command{gnatpp} does not have an option to control space characters.
16636 It will add or remove spaces according to the style illustrated by the
16637 examples in the @cite{Ada Reference Manual}.
16638
16639 The only format effectors
16640 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16641 that will appear in the output file are platform-specific line breaks,
16642 and also format effectors within (but not at the end of) comments.
16643 In particular, each horizontal tab character that is not inside
16644 a comment will be treated as a space and thus will appear in the
16645 output file as zero or more spaces depending on
16646 the reformatting of the line in which it appears.
16647 The only exception is a Form Feed character, which is inserted after a
16648 pragma @code{Page} when @option{-ff} is set.
16649
16650 The output file will contain no lines with trailing ``white space'' (spaces,
16651 format effectors).
16652
16653 Empty lines in the original source are preserved
16654 only if they separate declarations or statements.
16655 In such contexts, a
16656 sequence of two or more empty lines is replaced by exactly one empty line.
16657 Note that a blank line will be removed if it separates two ``comment blocks''
16658 (a comment block is a sequence of whole-line comments).
16659 In order to preserve a visual separation between comment blocks, use an
16660 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16661 Likewise, if for some reason you wish to have a sequence of empty lines,
16662 use a sequence of empty comments instead.
16663
16664 @node Formatting Comments
16665 @subsection Formatting Comments
16666
16667 @noindent
16668 Comments in Ada code are of two kinds:
16669 @itemize @bullet
16670 @item
16671 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16672 ``white space'') on a line
16673
16674 @item
16675 an @emph{end-of-line comment}, which follows some other Ada lexical element
16676 on the same line.
16677 @end itemize
16678
16679 @noindent
16680 The indentation of a whole-line comment is that of either
16681 the preceding or following line in
16682 the formatted source, depending on switch settings as will be described below.
16683
16684 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16685 between the end of the preceding Ada lexical element and the beginning
16686 of the comment as appear in the original source,
16687 unless either the comment has to be split to
16688 satisfy the line length limitation, or else the next line contains a
16689 whole line comment that is considered a continuation of this end-of-line
16690 comment (because it starts at the same position).
16691 In the latter two
16692 cases, the start of the end-of-line comment is moved right to the nearest
16693 multiple of the indentation level.
16694 This may result in a ``line overflow'' (the right-shifted comment extending
16695 beyond the maximum line length), in which case the comment is split as
16696 described below.
16697
16698 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16699 (GNAT-style comment line indentation)
16700 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16701 (reference-manual comment line indentation).
16702 With reference-manual style, a whole-line comment is indented as if it
16703 were a declaration or statement at the same place
16704 (i.e., according to the indentation of the preceding line(s)).
16705 With GNAT style, a whole-line comment that is immediately followed by an
16706 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16707 word @b{begin}, is indented based on the construct that follows it.
16708
16709 For example:
16710 @smallexample @c ada
16711 @cartouche
16712 if A then
16713     null;
16714        -- some comment
16715 else
16716    null;
16717 end if;
16718 @end cartouche
16719 @end smallexample
16720
16721 @noindent
16722 Reference-manual indentation produces:
16723
16724 @smallexample @c ada
16725 @cartouche
16726 if A then
16727    null;
16728    --  some comment
16729 else
16730    null;
16731 end if;
16732 @end cartouche
16733 @end smallexample
16734
16735 @noindent
16736 while GNAT-style indentation produces:
16737
16738 @smallexample @c ada
16739 @cartouche
16740 if A then
16741    null;
16742 --  some comment
16743 else
16744    null;
16745 end if;
16746 @end cartouche
16747 @end smallexample
16748
16749 @noindent
16750 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16751 (GNAT style comment beginning) has the following
16752 effect:
16753
16754 @itemize @bullet
16755 @item
16756 For each whole-line comment that does not end with two hyphens,
16757 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16758 to ensure that there are at least two spaces between these hyphens and the
16759 first non-blank character of the comment.
16760 @end itemize
16761
16762 @noindent
16763 For an end-of-line comment, if in the original source the next line is a
16764 whole-line comment that starts at the same position
16765 as the end-of-line comment,
16766 then the whole-line comment (and all whole-line comments
16767 that follow it and that start at the same position)
16768 will start at this position in the output file.
16769
16770 @noindent
16771 That is, if in the original source we have:
16772
16773 @smallexample @c ada
16774 @cartouche
16775 begin
16776 A := B + C;            --  B must be in the range Low1..High1
16777                        --  C must be in the range Low2..High2
16778              --B+C will be in the range Low1+Low2..High1+High2
16779 X := X + 1;
16780 @end cartouche
16781 @end smallexample
16782
16783 @noindent
16784 Then in the formatted source we get
16785
16786 @smallexample @c ada
16787 @cartouche
16788 begin
16789    A := B + C;            --  B must be in the range Low1..High1
16790                           --  C must be in the range Low2..High2
16791    --  B+C will be in the range Low1+Low2..High1+High2
16792    X := X + 1;
16793 @end cartouche
16794 @end smallexample
16795
16796 @noindent
16797 A comment that exceeds the line length limit will be split.
16798 Unless switch
16799 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16800 the line belongs to a reformattable block, splitting the line generates a
16801 @command{gnatpp} warning.
16802 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16803 comments may be reformatted in typical
16804 word processor style (that is, moving words between lines and putting as
16805 many words in a line as possible).
16806
16807 @noindent
16808 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16809 that has a special format (that is, a character that is neither a letter nor digit
16810 not white space nor line break immediately following the leading @code{--} of
16811 the comment) should be without any change moved from the argument source
16812 into reformatted source. This switch allows to preserve comments that are used
16813 as a special marks in the code (e.g.@: SPARK annotation).
16814
16815 @node Construct Layout
16816 @subsection Construct Layout
16817
16818 @noindent
16819 In several cases the suggested layout in the Ada Reference Manual includes
16820 an extra level of indentation that many programmers prefer to avoid. The
16821 affected cases include:
16822
16823 @itemize @bullet
16824
16825 @item Record type declaration (RM 3.8)
16826
16827 @item Record representation clause (RM 13.5.1)
16828
16829 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16830
16831 @item Block statement in case if a block has a statement identifier (RM 5.6)
16832 @end itemize
16833
16834 @noindent
16835 In compact mode (when GNAT style layout or compact layout is set),
16836 the pretty printer uses one level of indentation instead
16837 of two. This is achieved in the record definition and record representation
16838 clause cases by putting the @code{record} keyword on the same line as the
16839 start of the declaration or representation clause, and in the block and loop
16840 case by putting the block or loop header on the same line as the statement
16841 identifier.
16842
16843 @noindent
16844 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16845 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16846 layout on the one hand, and uncompact layout
16847 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16848 can be illustrated by the following examples:
16849
16850 @iftex
16851 @cartouche
16852 @multitable @columnfractions .5 .5
16853 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16854
16855 @item
16856 @smallexample @c ada
16857 type q is record
16858    a : integer;
16859    b : integer;
16860 end record;
16861 @end smallexample
16862 @tab
16863 @smallexample @c ada
16864 type q is
16865    record
16866       a : integer;
16867       b : integer;
16868    end record;
16869 @end smallexample
16870
16871 @item
16872 @smallexample @c ada
16873 for q use record
16874    a at 0 range  0 .. 31;
16875    b at 4 range  0 .. 31;
16876 end record;
16877 @end smallexample
16878 @tab
16879 @smallexample @c ada
16880 for q use
16881    record
16882       a at 0 range  0 .. 31;
16883       b at 4 range  0 .. 31;
16884    end record;
16885 @end smallexample
16886
16887 @item
16888 @smallexample @c ada
16889 Block : declare
16890    A : Integer := 3;
16891 begin
16892    Proc (A, A);
16893 end Block;
16894 @end smallexample
16895 @tab
16896 @smallexample @c ada
16897 Block :
16898    declare
16899       A : Integer := 3;
16900    begin
16901       Proc (A, A);
16902    end Block;
16903 @end smallexample
16904
16905 @item
16906 @smallexample @c ada
16907 Clear : for J in 1 .. 10 loop
16908    A (J) := 0;
16909 end loop Clear;
16910 @end smallexample
16911 @tab
16912 @smallexample @c ada
16913 Clear :
16914    for J in 1 .. 10 loop
16915       A (J) := 0;
16916    end loop Clear;
16917 @end smallexample
16918 @end multitable
16919 @end cartouche
16920 @end iftex
16921
16922 @ifnottex
16923 @smallexample
16924 @cartouche
16925 GNAT style, compact layout              Uncompact layout
16926
16927 type q is record                        type q is
16928    a : integer;                            record
16929    b : integer;                               a : integer;
16930 end record;                                   b : integer;
16931                                            end record;
16932
16933 for q use record                        for q use
16934    a at 0 range  0 .. 31;                  record
16935    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16936 end record;                                   b at 4 range  0 .. 31;
16937                                            end record;
16938
16939 Block : declare                         Block :
16940    A : Integer := 3;                       declare
16941 begin                                         A : Integer := 3;
16942    Proc (A, A);                            begin
16943 end Block;                                    Proc (A, A);
16944                                            end Block;
16945
16946 Clear : for J in 1 .. 10 loop           Clear :
16947    A (J) := 0;                             for J in 1 .. 10 loop
16948 end loop Clear;                               A (J) := 0;
16949                                            end loop Clear;
16950 @end cartouche
16951 @end smallexample
16952 @end ifnottex
16953
16954 @noindent
16955 A further difference between GNAT style layout and compact layout is that
16956 GNAT style layout inserts empty lines as separation for
16957 compound statements, return statements and bodies.
16958
16959 Note that the layout specified by
16960 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16961 for named block and loop statements overrides the layout defined by these
16962 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16963 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16964 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16965
16966 @node Name Casing
16967 @subsection Name Casing
16968
16969 @noindent
16970 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16971 the same casing as the corresponding defining identifier.
16972
16973 You control the casing for defining occurrences via the
16974 @option{^-n^/NAME_CASING^} switch.
16975 @ifclear vms
16976 With @option{-nD} (``as declared'', which is the default),
16977 @end ifclear
16978 @ifset vms
16979 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16980 @end ifset
16981 defining occurrences appear exactly as in the source file
16982 where they are declared.
16983 The other ^values for this switch^options for this qualifier^ ---
16984 @option{^-nU^UPPER_CASE^},
16985 @option{^-nL^LOWER_CASE^},
16986 @option{^-nM^MIXED_CASE^} ---
16987 result in
16988 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16989 If @command{gnatpp} changes the casing of a defining
16990 occurrence, it analogously changes the casing of all the
16991 usage occurrences of this name.
16992
16993 If the defining occurrence of a name is not in the source compilation unit
16994 currently being processed by @command{gnatpp}, the casing of each reference to
16995 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16996 switch (subject to the dictionary file mechanism described below).
16997 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
16998 had affected the
16999 casing for the defining occurrence of the name.
17000
17001 Some names may need to be spelled with casing conventions that are not
17002 covered by the upper-, lower-, and mixed-case transformations.
17003 You can arrange correct casing by placing such names in a
17004 @emph{dictionary file},
17005 and then supplying a @option{^-D^/DICTIONARY^} switch.
17006 The casing of names from dictionary files overrides
17007 any @option{^-n^/NAME_CASING^} switch.
17008
17009 To handle the casing of Ada predefined names and the names from GNAT libraries,
17010 @command{gnatpp} assumes a default dictionary file.
17011 The name of each predefined entity is spelled with the same casing as is used
17012 for the entity in the @cite{Ada Reference Manual}.
17013 The name of each entity in the GNAT libraries is spelled with the same casing
17014 as is used in the declaration of that entity.
17015
17016 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
17017 default dictionary file.
17018 Instead, the casing for predefined and GNAT-defined names will be established
17019 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
17020 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
17021 will appear as just shown,
17022 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
17023 To ensure that even such names are rendered in uppercase,
17024 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
17025 (or else, less conveniently, place these names in upper case in a dictionary
17026 file).
17027
17028 A dictionary file is
17029 a plain text file; each line in this file can be either a blank line
17030 (containing only space characters and ASCII.HT characters), an Ada comment
17031 line, or the specification of exactly one @emph{casing schema}.
17032
17033 A casing schema is a string that has the following syntax:
17034
17035 @smallexample
17036 @cartouche
17037   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
17038
17039   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
17040 @end cartouche
17041 @end smallexample
17042
17043 @noindent
17044 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
17045 @var{identifier} lexical element and the @var{letter_or_digit} category.)
17046
17047 The casing schema string can be followed by white space and/or an Ada-style
17048 comment; any amount of white space is allowed before the string.
17049
17050 If a dictionary file is passed as
17051 @ifclear vms
17052 the value of a @option{-D@var{file}} switch
17053 @end ifclear
17054 @ifset vms
17055 an option to the @option{/DICTIONARY} qualifier
17056 @end ifset
17057 then for every
17058 simple name and every identifier, @command{gnatpp} checks if the dictionary
17059 defines the casing for the name or for some of its parts (the term ``subword''
17060 is used below to denote the part of a name which is delimited by ``_'' or by
17061 the beginning or end of the word and which does not contain any ``_'' inside):
17062
17063 @itemize @bullet
17064 @item
17065 if the whole name is in the dictionary, @command{gnatpp} uses for this name
17066 the casing defined by the dictionary; no subwords are checked for this word
17067
17068 @item
17069 for every subword @command{gnatpp} checks if the dictionary contains the
17070 corresponding string of the form @code{*@var{simple_identifier}*},
17071 and if it does, the casing of this @var{simple_identifier} is used
17072 for this subword
17073
17074 @item
17075 if the whole name does not contain any ``_'' inside, and if for this name
17076 the dictionary contains two entries - one of the form @var{identifier},
17077 and another - of the form *@var{simple_identifier}*, then the first one
17078 is applied to define the casing of this name
17079
17080 @item
17081 if more than one dictionary file is passed as @command{gnatpp} switches, each
17082 dictionary adds new casing exceptions and overrides all the existing casing
17083 exceptions set by the previous dictionaries
17084
17085 @item
17086 when @command{gnatpp} checks if the word or subword is in the dictionary,
17087 this check is not case sensitive
17088 @end itemize
17089
17090 @noindent
17091 For example, suppose we have the following source to reformat:
17092
17093 @smallexample @c ada
17094 @cartouche
17095 procedure test is
17096    name1 : integer := 1;
17097    name4_name3_name2 : integer := 2;
17098    name2_name3_name4 : Boolean;
17099    name1_var : Float;
17100 begin
17101    name2_name3_name4 := name4_name3_name2 > name1;
17102 end;
17103 @end cartouche
17104 @end smallexample
17105
17106 @noindent
17107 And suppose we have two dictionaries:
17108
17109 @smallexample
17110 @cartouche
17111 @i{dict1:}
17112    NAME1
17113    *NaMe3*
17114    *Name1*
17115 @end cartouche
17116
17117 @cartouche
17118 @i{dict2:}
17119   *NAME3*
17120 @end cartouche
17121 @end smallexample
17122
17123 @noindent
17124 If @command{gnatpp} is called with the following switches:
17125
17126 @smallexample
17127 @ifclear vms
17128 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
17129 @end ifclear
17130 @ifset vms
17131 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
17132 @end ifset
17133 @end smallexample
17134
17135 @noindent
17136 then we will get the following name casing in the @command{gnatpp} output:
17137
17138 @smallexample @c ada
17139 @cartouche
17140 procedure Test is
17141    NAME1             : Integer := 1;
17142    Name4_NAME3_Name2 : Integer := 2;
17143    Name2_NAME3_Name4 : Boolean;
17144    Name1_Var         : Float;
17145 begin
17146    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
17147 end Test;
17148 @end cartouche
17149 @end smallexample
17150
17151 @c *********************************
17152 @node The GNAT Metric Tool gnatmetric
17153 @chapter The GNAT Metric Tool @command{gnatmetric}
17154 @findex gnatmetric
17155 @cindex Metric tool
17156
17157 @noindent
17158 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
17159 for computing various program metrics.
17160 It takes an Ada source file as input and generates a file containing the
17161 metrics data as output. Various switches control which
17162 metrics are computed and output.
17163
17164 @command{gnatmetric} generates and uses the ASIS
17165 tree for the input source and thus requires the input to be syntactically and
17166 semantically legal.
17167 If this condition is not met, @command{gnatmetric} will generate
17168 an error message; no metric information for this file will be
17169 computed and reported.
17170
17171 If the compilation unit contained in the input source depends semantically
17172 upon units in files located outside the current directory, you have to provide
17173 the source search path when invoking @command{gnatmetric}.
17174 If it depends semantically upon units that are contained
17175 in files with names that do not follow the GNAT file naming rules, you have to
17176 provide the configuration file describing the corresponding naming scheme (see
17177 the description of the @command{gnatmetric} switches below.)
17178 Alternatively, you may use a project file and invoke @command{gnatmetric}
17179 through the @command{gnat} driver.
17180
17181 The @command{gnatmetric} command has the form
17182
17183 @smallexample
17184 $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17185 @end smallexample
17186
17187 @noindent
17188 where
17189 @itemize @bullet
17190 @item
17191 @var{switches} specify the metrics to compute and define the destination for
17192 the output
17193
17194 @item
17195 Each @var{filename} is the name (including the extension) of a source
17196 file to process. ``Wildcards'' are allowed, and
17197 the file name may contain path information.
17198 If no @var{filename} is supplied, then the @var{switches} list must contain
17199 at least one
17200 @option{-files} switch (@pxref{Other gnatmetric Switches}).
17201 Including both a @option{-files} switch and one or more
17202 @var{filename} arguments is permitted.
17203
17204 @item
17205 @samp{-cargs @var{gcc_switches}} is a list of switches for
17206 @command{gcc}. They will be passed on to all compiler invocations made by
17207 @command{gnatmetric} to generate the ASIS trees. Here you can provide
17208 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17209 and use the @option{-gnatec} switch to set the configuration file.
17210 @end itemize
17211
17212 @menu
17213 * Switches for gnatmetric::
17214 @end menu
17215
17216 @node Switches for gnatmetric
17217 @section Switches for @command{gnatmetric}
17218
17219 @noindent
17220 The following subsections describe the various switches accepted by
17221 @command{gnatmetric}, organized by category.
17222
17223 @menu
17224 * Output Files Control::
17225 * Disable Metrics For Local Units::
17226 * Specifying a set of metrics to compute::
17227 * Other gnatmetric Switches::
17228 * Generate project-wide metrics::
17229 @end menu
17230
17231 @node Output Files Control
17232 @subsection Output File Control
17233 @cindex Output file control in @command{gnatmetric}
17234
17235 @noindent
17236 @command{gnatmetric} has two output formats. It can generate a
17237 textual (human-readable) form, and also XML. By default only textual
17238 output is generated.
17239
17240 When generating the output in textual form, @command{gnatmetric} creates
17241 for each Ada source file a corresponding text file
17242 containing the computed metrics, except for the case when the set of metrics
17243 specified by gnatmetric parameters consists only of metrics that are computed
17244 for the whole set of analyzed sources, but not for each Ada source.
17245 By default, this file is placed in the same directory as where the source
17246 file is located, and its name is obtained
17247 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
17248 input file.
17249
17250 All the output information generated in XML format is placed in a single
17251 file. By default this file is placed in the current directory and has the
17252 name ^@file{metrix.xml}^@file{METRIX$XML}^.
17253
17254 Some of the computed metrics are summed over the units passed to
17255 @command{gnatmetric}; for example, the total number of lines of code.
17256 By default this information is sent to @file{stdout}, but a file
17257 can be specified with the @option{-og} switch.
17258
17259 The following switches control the @command{gnatmetric} output:
17260
17261 @table @option
17262 @cindex @option{^-x^/XML^} (@command{gnatmetric})
17263 @item ^-x^/XML^
17264 Generate the XML output
17265
17266 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
17267 @item ^-xs^/XSD^
17268 Generate the XML output and the XML schema file that describes the structure
17269 of the XML metric report, this schema is assigned to the XML file. The schema
17270 file has the same name as the XML output file with @file{.xml} suffix replaced
17271 with @file{.xsd}
17272
17273 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
17274 @item ^-nt^/NO_TEXT^
17275 Do not generate the output in text form (implies @option{^-x^/XML^})
17276
17277 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
17278 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
17279 Put textual files with detailed metrics into @var{output_dir}
17280
17281 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
17282 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
17283 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
17284 in the name of the output file.
17285
17286 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
17287 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
17288 Put global metrics into @var{file_name}
17289
17290 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
17291 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
17292 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
17293
17294 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
17295 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
17296 Use ``short'' source file names in the output.  (The @command{gnatmetric}
17297 output includes the name(s) of the Ada source file(s) from which the metrics
17298 are computed.  By default each name includes the absolute path. The
17299 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
17300 to exclude all directory information from the file names that are output.)
17301
17302 @end table
17303
17304 @node Disable Metrics For Local Units
17305 @subsection Disable Metrics For Local Units
17306 @cindex Disable Metrics For Local Units in @command{gnatmetric}
17307
17308 @noindent
17309 @command{gnatmetric} relies on the GNAT compilation model @minus{}
17310 one compilation
17311 unit per one source file. It computes line metrics for the whole source
17312 file, and it also computes syntax
17313 and complexity metrics for the file's outermost unit.
17314
17315 By default, @command{gnatmetric} will also compute all metrics for certain
17316 kinds of locally declared program units:
17317
17318 @itemize @bullet
17319 @item
17320 subprogram (and generic subprogram) bodies;
17321
17322 @item
17323 package (and generic package) specs and bodies;
17324
17325 @item
17326 task object and type specifications and bodies;
17327
17328 @item
17329 protected object and type specifications and bodies.
17330 @end itemize
17331
17332 @noindent
17333 These kinds of entities will be referred to as
17334 @emph{eligible local program units}, or simply @emph{eligible local units},
17335 @cindex Eligible local unit (for @command{gnatmetric})
17336 in the discussion below.
17337
17338 Note that a subprogram declaration, generic instantiation,
17339 or renaming declaration only receives metrics
17340 computation when it appear as the outermost entity
17341 in a source file.
17342
17343 Suppression of metrics computation for eligible local units can be
17344 obtained via the following switch:
17345
17346 @table @option
17347 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
17348 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
17349 Do not compute detailed metrics for eligible local program units
17350
17351 @end table
17352
17353 @node Specifying a set of metrics to compute
17354 @subsection Specifying a set of metrics to compute
17355
17356 @noindent
17357 By default all the metrics are computed and reported. The switches
17358 described in this subsection allow you to control, on an individual
17359 basis, whether metrics are computed and
17360 reported. If at least one positive metric
17361 switch is specified (that is, a switch that defines that a given
17362 metric or set of metrics is to be computed), then only
17363 explicitly specified metrics are reported.
17364
17365 @menu
17366 * Line Metrics Control::
17367 * Syntax Metrics Control::
17368 * Complexity Metrics Control::
17369 * Object-Oriented Metrics Control::
17370 @end menu
17371
17372 @node Line Metrics Control
17373 @subsubsection Line Metrics Control
17374 @cindex Line metrics control in @command{gnatmetric}
17375
17376 @noindent
17377 For any (legal) source file, and for each of its
17378 eligible local program units, @command{gnatmetric} computes the following
17379 metrics:
17380
17381 @itemize @bullet
17382 @item
17383 the total number of lines;
17384
17385 @item
17386 the total number of code lines (i.e., non-blank lines that are not comments)
17387
17388 @item
17389 the number of comment lines
17390
17391 @item
17392 the number of code lines containing end-of-line comments;
17393
17394 @item
17395 the comment percentage: the ratio between the number of lines that contain
17396 comments and the number of all non-blank lines, expressed as a percentage;
17397
17398 @item
17399 the number of empty lines and lines containing only space characters and/or
17400 format effectors (blank lines)
17401
17402 @item
17403 the average number of code lines in subprogram bodies, task bodies, entry
17404 bodies and statement sequences in package bodies (this metric is only computed
17405 across the whole set of the analyzed units)
17406
17407 @end itemize
17408
17409 @noindent
17410 @command{gnatmetric} sums the values of the line metrics for all the
17411 files being processed and then generates the cumulative results. The tool
17412 also computes for all the files being processed the average number of code
17413 lines in bodies.
17414
17415 You can use the following switches to select the specific line metrics
17416 to be computed and reported.
17417
17418 @table @option
17419 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17420
17421 @ifclear vms
17422 @cindex @option{--no-lines@var{x}}
17423 @end ifclear
17424
17425 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
17426 Report all the line metrics
17427
17428 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
17429 Do not report any of line metrics
17430
17431 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
17432 Report the number of all lines
17433
17434 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
17435 Do not report the number of all lines
17436
17437 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
17438 Report the number of code lines
17439
17440 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
17441 Do not report the number of code lines
17442
17443 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
17444 Report the number of comment lines
17445
17446 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
17447 Do not report the number of comment lines
17448
17449 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
17450 Report the number of code lines containing
17451 end-of-line comments
17452
17453 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
17454 Do not report the number of code lines containing
17455 end-of-line comments
17456
17457 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
17458 Report the comment percentage in the program text
17459
17460 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
17461 Do not report the comment percentage in the program text
17462
17463 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
17464 Report the number of blank lines
17465
17466 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
17467 Do not report the number of blank lines
17468
17469 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
17470 Report the average number of code lines in subprogram bodies, task bodies,
17471 entry bodies and statement sequences in package bodies. The metric is computed
17472 and reported for the whole set of processed Ada sources only.
17473
17474 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
17475 Do not report the average number of code lines in subprogram bodies,
17476 task bodies, entry bodies and statement sequences in package bodies.
17477
17478 @end table
17479
17480 @node Syntax Metrics Control
17481 @subsubsection Syntax Metrics Control
17482 @cindex Syntax metrics control in @command{gnatmetric}
17483
17484 @noindent
17485 @command{gnatmetric} computes various syntactic metrics for the
17486 outermost unit and for each eligible local unit:
17487
17488 @table @emph
17489 @item LSLOC (``Logical Source Lines Of Code'')
17490 The total number of declarations and the total number of statements
17491
17492 @item Maximal static nesting level of inner program units
17493 According to
17494 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17495 package, a task unit, a protected unit, a
17496 protected entry, a generic unit, or an explicitly declared subprogram other
17497 than an enumeration literal.''
17498
17499 @item Maximal nesting level of composite syntactic constructs
17500 This corresponds to the notion of the
17501 maximum nesting level in the GNAT built-in style checks
17502 (@pxref{Style Checking})
17503 @end table
17504
17505 @noindent
17506 For the outermost unit in the file, @command{gnatmetric} additionally computes
17507 the following metrics:
17508
17509 @table @emph
17510 @item Public subprograms
17511 This metric is computed for package specs. It is the
17512 number of subprograms and generic subprograms declared in the visible
17513 part (including the visible part of nested packages, protected objects, and
17514 protected types).
17515
17516 @item All subprograms
17517 This metric is computed for bodies and subunits. The
17518 metric is equal to a total number of subprogram bodies in the compilation
17519 unit.
17520 Neither generic instantiations nor renamings-as-a-body nor body stubs
17521 are counted. Any subprogram body is counted, independently of its nesting
17522 level and enclosing constructs. Generic bodies and bodies of protected
17523 subprograms are counted in the same way as ``usual'' subprogram bodies.
17524
17525 @item Public types
17526 This metric is computed for package specs and
17527 generic package declarations. It is the total number of types
17528 that can be referenced from outside this compilation unit, plus the
17529 number of types from all the visible parts of all the visible generic
17530 packages. Generic formal types are not counted.  Only types, not subtypes,
17531 are included.
17532
17533 @noindent
17534 Along with the total number of public types, the following
17535 types are counted and reported separately:
17536
17537 @itemize @bullet
17538 @item
17539 Abstract types
17540
17541 @item
17542 Root tagged types (abstract, non-abstract, private, non-private). Type
17543 extensions are @emph{not} counted
17544
17545 @item
17546 Private types (including private extensions)
17547
17548 @item
17549 Task types
17550
17551 @item
17552 Protected types
17553
17554 @end itemize
17555
17556 @item All types
17557 This metric is computed for any compilation unit. It is equal to the total
17558 number of the declarations of different types given in the compilation unit.
17559 The private and the corresponding full type declaration are counted as one
17560 type declaration. Incomplete type declarations and generic formal types
17561 are not counted.
17562 No distinction is made among different kinds of types (abstract,
17563 private etc.); the total number of types is computed and reported.
17564
17565 @end table
17566
17567 @noindent
17568 By default, all the syntax metrics are computed and reported. You can use the
17569 following switches to select specific syntax metrics.
17570
17571 @table @option
17572
17573 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17574
17575 @ifclear vms
17576 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17577 @end ifclear
17578
17579 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
17580 Report all the syntax metrics
17581
17582 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
17583 Do not report any of syntax metrics
17584
17585 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
17586 Report the total number of declarations
17587
17588 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
17589 Do not report the total number of declarations
17590
17591 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
17592 Report the total number of statements
17593
17594 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
17595 Do not report the total number of statements
17596
17597 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
17598 Report the number of public subprograms in a compilation unit
17599
17600 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
17601 Do not report the number of public subprograms in a compilation unit
17602
17603 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
17604 Report the number of all the subprograms in a compilation unit
17605
17606 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
17607 Do not report the number of all the subprograms in a compilation unit
17608
17609 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
17610 Report the number of public types in a compilation unit
17611
17612 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
17613 Do not report the number of public types in a compilation unit
17614
17615 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
17616 Report the number of all the types in a compilation unit
17617
17618 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
17619 Do not report the number of all the types in a compilation unit
17620
17621 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
17622 Report the maximal program unit nesting level
17623
17624 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17625 Do not report the maximal program unit nesting level
17626
17627 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
17628 Report the maximal construct nesting level
17629
17630 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
17631 Do not report the maximal construct nesting level
17632
17633 @end table
17634
17635 @node Complexity Metrics Control
17636 @subsubsection Complexity Metrics Control
17637 @cindex Complexity metrics control in @command{gnatmetric}
17638
17639 @noindent
17640 For a program unit that is an executable body (a subprogram body (including
17641 generic bodies), task body, entry body or a package body containing
17642 its own statement sequence) @command{gnatmetric} computes the following
17643 complexity metrics:
17644
17645 @itemize @bullet
17646 @item
17647 McCabe cyclomatic complexity;
17648
17649 @item
17650 McCabe essential complexity;
17651
17652 @item
17653 maximal loop nesting level
17654
17655 @end itemize
17656
17657 @noindent
17658 The McCabe complexity metrics are defined
17659 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17660
17661 According to McCabe, both control statements and short-circuit control forms
17662 should be taken into account when computing cyclomatic complexity. For each
17663 body, we compute three metric values:
17664
17665 @itemize @bullet
17666 @item
17667 the complexity introduced by control
17668 statements only, without taking into account short-circuit forms,
17669
17670 @item
17671 the complexity introduced by short-circuit control forms only, and
17672
17673 @item
17674 the total
17675 cyclomatic complexity, which is the sum of these two values.
17676 @end itemize
17677
17678 @noindent
17679 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17680 the code in the exception handlers and in all the nested program units.
17681
17682 By default, all the complexity metrics are computed and reported.
17683 For more fine-grained control you can use
17684 the following switches:
17685
17686 @table @option
17687 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17688
17689 @ifclear vms
17690 @cindex @option{--no-complexity@var{x}}
17691 @end ifclear
17692
17693 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
17694 Report all the complexity metrics
17695
17696 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
17697 Do not report any of complexity metrics
17698
17699 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
17700 Report the McCabe Cyclomatic Complexity
17701
17702 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
17703 Do not report the McCabe Cyclomatic Complexity
17704
17705 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
17706 Report the Essential Complexity
17707
17708 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
17709 Do not report the Essential Complexity
17710
17711 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17712 Report maximal loop nesting level
17713
17714 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
17715 Do not report maximal loop nesting level
17716
17717 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
17718 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17719 task bodies, entry bodies and statement sequences in package bodies.
17720 The metric is computed and reported for whole set of processed Ada sources
17721 only.
17722
17723 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
17724 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17725 bodies, task bodies, entry bodies and statement sequences in package bodies
17726
17727 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17728 @item ^-ne^/NO_EXITS_AS_GOTOS^
17729 Do not consider @code{exit} statements as @code{goto}s when
17730 computing Essential Complexity
17731
17732 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
17733 Report the extra exit points for subprogram bodies. As an exit point, this
17734 metric counts @code{return} statements and raise statements in case when the
17735 raised exception is not handled in the same body. In case of a function this
17736 metric subtracts 1 from the number of exit points, because a function body
17737 must contain at least one @code{return} statement.
17738
17739 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
17740 Do not report the extra exit points for subprogram bodies
17741 @end table
17742
17743
17744 @node Object-Oriented Metrics Control
17745 @subsubsection Object-Oriented Metrics Control
17746 @cindex Object-Oriented metrics control in @command{gnatmetric}
17747
17748 @noindent
17749 @cindex Coupling metrics (in in @command{gnatmetric})
17750 Coupling metrics are object-oriented metrics that measure the
17751 dependencies between a given class (or a group of classes) and the
17752 ``external world'' (that is, the other classes in the program). In this
17753 subsection the term ``class'' is used in its
17754 traditional object-oriented programming sense
17755 (an instantiable module that contains data and/or method members).
17756 A @emph{category} (of classes)
17757 is a group of closely related classes that are reused and/or
17758 modified together.
17759
17760 A class @code{K}'s @emph{efferent coupling} is the number of classes
17761 that @code{K} depends upon.
17762 A category's efferent coupling is the number of classes outside the
17763 category that the classes inside the category depend upon.
17764
17765 A class @code{K}'s @emph{afferent coupling} is the number of classes
17766 that depend upon @code{K}.
17767 A category's afferent coupling is the number of classes outside the
17768 category that depend on classes belonging to the category.
17769
17770 Ada's implementation of the object-oriented paradigm does not use the
17771 traditional class notion, so the definition of the coupling
17772 metrics for Ada maps the class and class category notions
17773 onto Ada constructs.
17774
17775 For the coupling metrics, several kinds of modules -- a library package,
17776 a library generic package, and a library generic package instantiation --
17777 that define a tagged type or an interface type are
17778 considered to be a class. A category consists of a library package (or
17779 a library generic package) that defines a tagged or an interface type,
17780 together with all its descendant (generic) packages that define tagged
17781 or interface types. For any package counted as a class,
17782 its body and subunits (if any) are considered
17783 together with its spec when counting the dependencies, and coupling
17784 metrics are reported for spec units only. For dependencies
17785 between classes, the Ada semantic dependencies are considered.
17786 For coupling metrics, only dependencies on units that are considered as
17787 classes, are considered.
17788
17789 When computing coupling metrics, @command{gnatmetric} counts only
17790 dependencies between units that are arguments of the gnatmetric call.
17791 Coupling metrics are program-wide (or project-wide) metrics, so to
17792 get a valid result, you should call @command{gnatmetric} for
17793 the whole set of sources that make up your program. It can be done
17794 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17795 option (see See @ref{The GNAT Driver and Project Files} for details.
17796
17797 By default, all the coupling metrics are disabled. You can use the following
17798 switches to specify the coupling metrics to be computed and reported:
17799
17800 @table @option
17801
17802 @ifclear vms
17803 @cindex @option{--package@var{x}} (@command{gnatmetric})
17804 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17805 @cindex @option{--category@var{x}} (@command{gnatmetric})
17806 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17807 @end ifclear
17808
17809 @ifset vms
17810 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17811 @end ifset
17812
17813 @item ^--coupling-all^/COUPLING_METRICS=ALL^
17814 Report all the coupling metrics
17815
17816 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
17817 Do not report any of  metrics
17818
17819 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
17820 Report package efferent coupling
17821
17822 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
17823 Do not report package efferent coupling
17824
17825 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
17826 Report package afferent coupling
17827
17828 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
17829 Do not report package afferent coupling
17830
17831 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
17832 Report category efferent coupling
17833
17834 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
17835 Do not report category efferent coupling
17836
17837 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
17838 Report category afferent coupling
17839
17840 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
17841 Do not report category afferent coupling
17842
17843 @end table
17844
17845 @node Other gnatmetric Switches
17846 @subsection Other @code{gnatmetric} Switches
17847
17848 @noindent
17849 Additional @command{gnatmetric} switches are as follows:
17850
17851 @table @option
17852 @item ^-files @var{filename}^/FILES=@var{filename}^
17853 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17854 Take the argument source files from the specified file. This file should be an
17855 ordinary text file containing file names separated by spaces or
17856 line breaks. You can use this switch more then once in the same call to
17857 @command{gnatmetric}. You also can combine this switch with
17858 an explicit list of files.
17859
17860 @item ^-v^/VERBOSE^
17861 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17862 Verbose mode;
17863 @command{gnatmetric} generates version information and then
17864 a trace of sources being processed.
17865
17866 @item ^-dv^/DEBUG_OUTPUT^
17867 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17868 Debug mode;
17869 @command{gnatmetric} generates various messages useful to understand what
17870 happens during the metrics computation
17871
17872 @item ^-q^/QUIET^
17873 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17874 Quiet mode.
17875 @end table
17876
17877 @node Generate project-wide metrics
17878 @subsection Generate project-wide metrics
17879
17880 In order to compute metrics on all units of a given project, you can use
17881 the @command{gnat} driver along with the @option{-P} option:
17882 @smallexample
17883    gnat metric -Pproj
17884 @end smallexample
17885
17886 @noindent
17887 If the project @code{proj} depends upon other projects, you can compute
17888 the metrics on the project closure using the @option{-U} option:
17889 @smallexample
17890    gnat metric -Pproj -U
17891 @end smallexample
17892
17893 @noindent
17894 Finally, if not all the units are relevant to a particular main
17895 program in the project closure, you can generate metrics for the set
17896 of units needed to create a given main program (unit closure) using
17897 the @option{-U} option followed by the name of the main unit:
17898 @smallexample
17899    gnat metric -Pproj -U main
17900 @end smallexample
17901
17902
17903 @c ***********************************
17904 @node File Name Krunching Using gnatkr
17905 @chapter File Name Krunching Using @code{gnatkr}
17906 @findex gnatkr
17907
17908 @noindent
17909 This chapter discusses the method used by the compiler to shorten
17910 the default file names chosen for Ada units so that they do not
17911 exceed the maximum length permitted. It also describes the
17912 @code{gnatkr} utility that can be used to determine the result of
17913 applying this shortening.
17914 @menu
17915 * About gnatkr::
17916 * Using gnatkr::
17917 * Krunching Method::
17918 * Examples of gnatkr Usage::
17919 @end menu
17920
17921 @node About gnatkr
17922 @section About @code{gnatkr}
17923
17924 @noindent
17925 The default file naming rule in GNAT
17926 is that the file name must be derived from
17927 the unit name. The exact default rule is as follows:
17928 @itemize @bullet
17929 @item
17930 Take the unit name and replace all dots by hyphens.
17931 @item
17932 If such a replacement occurs in the
17933 second character position of a name, and the first character is
17934 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17935 then replace the dot by the character
17936 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17937 instead of a minus.
17938 @end itemize
17939 The reason for this exception is to avoid clashes
17940 with the standard names for children of System, Ada, Interfaces,
17941 and GNAT, which use the prefixes
17942 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17943 respectively.
17944
17945 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17946 switch of the compiler activates a ``krunching''
17947 circuit that limits file names to nn characters (where nn is a decimal
17948 integer). For example, using OpenVMS,
17949 where the maximum file name length is
17950 39, the value of nn is usually set to 39, but if you want to generate
17951 a set of files that would be usable if ported to a system with some
17952 different maximum file length, then a different value can be specified.
17953 The default value of 39 for OpenVMS need not be specified.
17954
17955 The @code{gnatkr} utility can be used to determine the krunched name for
17956 a given file, when krunched to a specified maximum length.
17957
17958 @node Using gnatkr
17959 @section Using @code{gnatkr}
17960
17961 @noindent
17962 The @code{gnatkr} command has the form
17963
17964 @ifclear vms
17965 @smallexample
17966 $ gnatkr @var{name} @ovar{length}
17967 @end smallexample
17968 @end ifclear
17969
17970 @ifset vms
17971 @smallexample
17972 $ gnatkr @var{name} /COUNT=nn
17973 @end smallexample
17974 @end ifset
17975
17976 @noindent
17977 @var{name} is the uncrunched file name, derived from the name of the unit
17978 in the standard manner described in the previous section (i.e., in particular
17979 all dots are replaced by hyphens). The file name may or may not have an
17980 extension (defined as a suffix of the form period followed by arbitrary
17981 characters other than period). If an extension is present then it will
17982 be preserved in the output. For example, when krunching @file{hellofile.ads}
17983 to eight characters, the result will be hellofil.ads.
17984
17985 Note: for compatibility with previous versions of @code{gnatkr} dots may
17986 appear in the name instead of hyphens, but the last dot will always be
17987 taken as the start of an extension. So if @code{gnatkr} is given an argument
17988 such as @file{Hello.World.adb} it will be treated exactly as if the first
17989 period had been a hyphen, and for example krunching to eight characters
17990 gives the result @file{hellworl.adb}.
17991
17992 Note that the result is always all lower case (except on OpenVMS where it is
17993 all upper case). Characters of the other case are folded as required.
17994
17995 @var{length} represents the length of the krunched name. The default
17996 when no argument is given is ^8^39^ characters. A length of zero stands for
17997 unlimited, in other words do not chop except for system files where the
17998 implied crunching length is always eight characters.
17999
18000 @noindent
18001 The output is the krunched name. The output has an extension only if the
18002 original argument was a file name with an extension.
18003
18004 @node Krunching Method
18005 @section Krunching Method
18006
18007 @noindent
18008 The initial file name is determined by the name of the unit that the file
18009 contains. The name is formed by taking the full expanded name of the
18010 unit and replacing the separating dots with hyphens and
18011 using ^lowercase^uppercase^
18012 for all letters, except that a hyphen in the second character position is
18013 replaced by a ^tilde^dollar sign^ if the first character is
18014 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
18015 The extension is @code{.ads} for a
18016 spec and @code{.adb} for a body.
18017 Krunching does not affect the extension, but the file name is shortened to
18018 the specified length by following these rules:
18019
18020 @itemize @bullet
18021 @item
18022 The name is divided into segments separated by hyphens, tildes or
18023 underscores and all hyphens, tildes, and underscores are
18024 eliminated. If this leaves the name short enough, we are done.
18025
18026 @item
18027 If the name is too long, the longest segment is located (left-most
18028 if there are two of equal length), and shortened by dropping
18029 its last character. This is repeated until the name is short enough.
18030
18031 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
18032 to fit the name into 8 characters as required by some operating systems.
18033
18034 @smallexample
18035 our-strings-wide_fixed 22
18036 our strings wide fixed 19
18037 our string  wide fixed 18
18038 our strin   wide fixed 17
18039 our stri    wide fixed 16
18040 our stri    wide fixe  15
18041 our str     wide fixe  14
18042 our str     wid  fixe  13
18043 our str     wid  fix   12
18044 ou  str     wid  fix   11
18045 ou  st      wid  fix   10
18046 ou  st      wi   fix   9
18047 ou  st      wi   fi    8
18048 Final file name: oustwifi.adb
18049 @end smallexample
18050
18051 @item
18052 The file names for all predefined units are always krunched to eight
18053 characters. The krunching of these predefined units uses the following
18054 special prefix replacements:
18055
18056 @table @file
18057 @item ada-
18058 replaced by @file{^a^A^-}
18059
18060 @item gnat-
18061 replaced by @file{^g^G^-}
18062
18063 @item interfaces-
18064 replaced by @file{^i^I^-}
18065
18066 @item system-
18067 replaced by @file{^s^S^-}
18068 @end table
18069
18070 These system files have a hyphen in the second character position. That
18071 is why normal user files replace such a character with a
18072 ^tilde^dollar sign^, to
18073 avoid confusion with system file names.
18074
18075 As an example of this special rule, consider
18076 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
18077
18078 @smallexample
18079 ada-strings-wide_fixed 22
18080 a-  strings wide fixed 18
18081 a-  string  wide fixed 17
18082 a-  strin   wide fixed 16
18083 a-  stri    wide fixed 15
18084 a-  stri    wide fixe  14
18085 a-  str     wide fixe  13
18086 a-  str     wid  fixe  12
18087 a-  str     wid  fix   11
18088 a-  st      wid  fix   10
18089 a-  st      wi   fix   9
18090 a-  st      wi   fi    8
18091 Final file name: a-stwifi.adb
18092 @end smallexample
18093 @end itemize
18094
18095 Of course no file shortening algorithm can guarantee uniqueness over all
18096 possible unit names, and if file name krunching is used then it is your
18097 responsibility to ensure that no name clashes occur. The utility
18098 program @code{gnatkr} is supplied for conveniently determining the
18099 krunched name of a file.
18100
18101 @node Examples of gnatkr Usage
18102 @section Examples of @code{gnatkr} Usage
18103
18104 @smallexample
18105 @iftex
18106 @leftskip=0cm
18107 @end iftex
18108 @ifclear vms
18109 $ gnatkr very_long_unit_name.ads      --> velounna.ads
18110 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
18111 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
18112 $ gnatkr grandparent-parent-child     --> grparchi
18113 @end ifclear
18114 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
18115 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
18116 @end smallexample
18117
18118 @node Preprocessing Using gnatprep
18119 @chapter Preprocessing Using @code{gnatprep}
18120 @findex gnatprep
18121
18122 @noindent
18123 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
18124 preprocessing.
18125 Although designed for use with GNAT, @code{gnatprep} does not depend on any
18126 special GNAT features.
18127 For further discussion of conditional compilation in general, see
18128 @ref{Conditional Compilation}.
18129
18130 @menu
18131 * Preprocessing Symbols::
18132 * Using gnatprep::
18133 * Switches for gnatprep::
18134 * Form of Definitions File::
18135 * Form of Input Text for gnatprep::
18136 @end menu
18137
18138 @node Preprocessing Symbols
18139 @section Preprocessing Symbols
18140
18141 @noindent
18142 Preprocessing symbols are defined in definition files and referred to in
18143 sources to be preprocessed. A Preprocessing symbol is an identifier, following
18144 normal Ada (case-insensitive) rules for its syntax, with the restriction that
18145 all characters need to be in the ASCII set (no accented letters).
18146
18147 @node Using gnatprep
18148 @section Using @code{gnatprep}
18149
18150 @noindent
18151 To call @code{gnatprep} use
18152
18153 @smallexample
18154 $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
18155 @end smallexample
18156
18157 @noindent
18158 where
18159 @table @var
18160 @item switches
18161 is an optional sequence of switches as described in the next section.
18162
18163 @item infile
18164 is the full name of the input file, which is an Ada source
18165 file containing preprocessor directives.
18166
18167 @item outfile
18168 is the full name of the output file, which is an Ada source
18169 in standard Ada form. When used with GNAT, this file name will
18170 normally have an ads or adb suffix.
18171
18172 @item deffile
18173 is the full name of a text file containing definitions of
18174 preprocessing symbols to be referenced by the preprocessor. This argument is
18175 optional, and can be replaced by the use of the @option{-D} switch.
18176
18177 @end table
18178
18179 @node Switches for gnatprep
18180 @section Switches for @code{gnatprep}
18181
18182 @table @option
18183 @c !sort!
18184
18185 @item ^-b^/BLANK_LINES^
18186 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
18187 Causes both preprocessor lines and the lines deleted by
18188 preprocessing to be replaced by blank lines in the output source file,
18189 preserving line numbers in the output file.
18190
18191 @item ^-c^/COMMENTS^
18192 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
18193 Causes both preprocessor lines and the lines deleted
18194 by preprocessing to be retained in the output source as comments marked
18195 with the special string @code{"--! "}. This option will result in line numbers
18196 being preserved in the output file.
18197
18198 @item ^-C^/REPLACE_IN_COMMENTS^
18199 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
18200 Causes comments to be scanned. Normally comments are ignored by gnatprep.
18201 If this option is specified, then comments are scanned and any $symbol
18202 substitutions performed as in program text. This is particularly useful
18203 when structured comments are used (e.g., when writing programs in the
18204 SPARK dialect of Ada). Note that this switch is not available when
18205 doing integrated preprocessing (it would be useless in this context
18206 since comments are ignored by the compiler in any case).
18207
18208 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
18209 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
18210 Defines a new preprocessing symbol, associated with value. If no value is given
18211 on the command line, then symbol is considered to be @code{True}. This switch
18212 can be used in place of a definition file.
18213
18214 @ifset vms
18215 @item /REMOVE
18216 @cindex @option{/REMOVE} (@command{gnatprep})
18217 This is the default setting which causes lines deleted by preprocessing
18218 to be entirely removed from the output file.
18219 @end ifset
18220
18221 @item ^-r^/REFERENCE^
18222 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
18223 Causes a @code{Source_Reference} pragma to be generated that
18224 references the original input file, so that error messages will use
18225 the file name of this original file. The use of this switch implies
18226 that preprocessor lines are not to be removed from the file, so its
18227 use will force @option{^-b^/BLANK_LINES^} mode if
18228 @option{^-c^/COMMENTS^}
18229 has not been specified explicitly.
18230
18231 Note that if the file to be preprocessed contains multiple units, then
18232 it will be necessary to @code{gnatchop} the output file from
18233 @code{gnatprep}. If a @code{Source_Reference} pragma is present
18234 in the preprocessed file, it will be respected by
18235 @code{gnatchop ^-r^/REFERENCE^}
18236 so that the final chopped files will correctly refer to the original
18237 input source file for @code{gnatprep}.
18238
18239 @item ^-s^/SYMBOLS^
18240 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
18241 Causes a sorted list of symbol names and values to be
18242 listed on the standard output file.
18243
18244 @item ^-u^/UNDEFINED^
18245 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
18246 Causes undefined symbols to be treated as having the value FALSE in the context
18247 of a preprocessor test. In the absence of this option, an undefined symbol in
18248 a @code{#if} or @code{#elsif} test will be treated as an error.
18249
18250 @end table
18251
18252 @ifclear vms
18253 @noindent
18254 Note: if neither @option{-b} nor @option{-c} is present,
18255 then preprocessor lines and
18256 deleted lines are completely removed from the output, unless -r is
18257 specified, in which case -b is assumed.
18258 @end ifclear
18259
18260 @node Form of Definitions File
18261 @section Form of Definitions File
18262
18263 @noindent
18264 The definitions file contains lines of the form
18265
18266 @smallexample
18267 symbol := value
18268 @end smallexample
18269
18270 @noindent
18271 where symbol is a preprocessing symbol, and value is one of the following:
18272
18273 @itemize @bullet
18274 @item
18275 Empty, corresponding to a null substitution
18276 @item
18277 A string literal using normal Ada syntax
18278 @item
18279 Any sequence of characters from the set
18280 (letters, digits, period, underline).
18281 @end itemize
18282
18283 @noindent
18284 Comment lines may also appear in the definitions file, starting with
18285 the usual @code{--},
18286 and comments may be added to the definitions lines.
18287
18288 @node Form of Input Text for gnatprep
18289 @section Form of Input Text for @code{gnatprep}
18290
18291 @noindent
18292 The input text may contain preprocessor conditional inclusion lines,
18293 as well as general symbol substitution sequences.
18294
18295 The preprocessor conditional inclusion commands have the form
18296
18297 @smallexample
18298 @group
18299 @cartouche
18300 #if @i{expression} @r{[}then@r{]}
18301    lines
18302 #elsif @i{expression} @r{[}then@r{]}
18303    lines
18304 #elsif @i{expression} @r{[}then@r{]}
18305    lines
18306 @dots{}
18307 #else
18308    lines
18309 #end if;
18310 @end cartouche
18311 @end group
18312 @end smallexample
18313
18314 @noindent
18315 In this example, @i{expression} is defined by the following grammar:
18316 @smallexample
18317 @i{expression} ::=  <symbol>
18318 @i{expression} ::=  <symbol> = "<value>"
18319 @i{expression} ::=  <symbol> = <symbol>
18320 @i{expression} ::=  <symbol> 'Defined
18321 @i{expression} ::=  not @i{expression}
18322 @i{expression} ::=  @i{expression} and @i{expression}
18323 @i{expression} ::=  @i{expression} or @i{expression}
18324 @i{expression} ::=  @i{expression} and then @i{expression}
18325 @i{expression} ::=  @i{expression} or else @i{expression}
18326 @i{expression} ::=  ( @i{expression} )
18327 @end smallexample
18328
18329 The following restriction exists: it is not allowed to have "and" or "or"
18330 following "not" in the same expression without parentheses. For example, this
18331 is not allowed:
18332
18333 @smallexample
18334    not X or Y
18335 @end smallexample
18336
18337 This should be one of the following:
18338
18339 @smallexample
18340    (not X) or Y
18341    not (X or Y)
18342 @end smallexample
18343
18344 @noindent
18345 For the first test (@i{expression} ::= <symbol>) the symbol must have
18346 either the value true or false, that is to say the right-hand of the
18347 symbol definition must be one of the (case-insensitive) literals
18348 @code{True} or @code{False}. If the value is true, then the
18349 corresponding lines are included, and if the value is false, they are
18350 excluded.
18351
18352 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
18353 the symbol has been defined in the definition file or by a @option{-D}
18354 switch on the command line. Otherwise, the test is false.
18355
18356 The equality tests are case insensitive, as are all the preprocessor lines.
18357
18358 If the symbol referenced is not defined in the symbol definitions file,
18359 then the effect depends on whether or not switch @option{-u}
18360 is specified. If so, then the symbol is treated as if it had the value
18361 false and the test fails. If this switch is not specified, then
18362 it is an error to reference an undefined symbol. It is also an error to
18363 reference a symbol that is defined with a value other than @code{True}
18364 or @code{False}.
18365
18366 The use of the @code{not} operator inverts the sense of this logical test.
18367 The @code{not} operator cannot be combined with the @code{or} or @code{and}
18368 operators, without parentheses. For example, "if not X or Y then" is not
18369 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
18370
18371 The @code{then} keyword is optional as shown
18372
18373 The @code{#} must be the first non-blank character on a line, but
18374 otherwise the format is free form. Spaces or tabs may appear between
18375 the @code{#} and the keyword. The keywords and the symbols are case
18376 insensitive as in normal Ada code. Comments may be used on a
18377 preprocessor line, but other than that, no other tokens may appear on a
18378 preprocessor line. Any number of @code{elsif} clauses can be present,
18379 including none at all. The @code{else} is optional, as in Ada.
18380
18381 The @code{#} marking the start of a preprocessor line must be the first
18382 non-blank character on the line, i.e., it must be preceded only by
18383 spaces or horizontal tabs.
18384
18385 Symbol substitution outside of preprocessor lines is obtained by using
18386 the sequence
18387
18388 @smallexample
18389 $symbol
18390 @end smallexample
18391
18392 @noindent
18393 anywhere within a source line, except in a comment or within a
18394 string literal. The identifier
18395 following the @code{$} must match one of the symbols defined in the symbol
18396 definition file, and the result is to substitute the value of the
18397 symbol in place of @code{$symbol} in the output file.
18398
18399 Note that although the substitution of strings within a string literal
18400 is not possible, it is possible to have a symbol whose defined value is
18401 a string literal. So instead of setting XYZ to @code{hello} and writing:
18402
18403 @smallexample
18404 Header : String := "$XYZ";
18405 @end smallexample
18406
18407 @noindent
18408 you should set XYZ to @code{"hello"} and write:
18409
18410 @smallexample
18411 Header : String := $XYZ;
18412 @end smallexample
18413
18414 @noindent
18415 and then the substitution will occur as desired.
18416
18417 @ifset vms
18418 @node The GNAT Run-Time Library Builder gnatlbr
18419 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18420 @findex gnatlbr
18421 @cindex Library builder
18422
18423 @noindent
18424 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18425 supplied configuration pragmas.
18426
18427 @menu
18428 * Running gnatlbr::
18429 * Switches for gnatlbr::
18430 * Examples of gnatlbr Usage::
18431 @end menu
18432
18433 @node Running gnatlbr
18434 @section Running @code{gnatlbr}
18435
18436 @noindent
18437 The @code{gnatlbr} command has the form
18438
18439 @smallexample
18440 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18441 @end smallexample
18442
18443 @node Switches for gnatlbr
18444 @section Switches for @code{gnatlbr}
18445
18446 @noindent
18447 @code{gnatlbr} recognizes the following switches:
18448
18449 @table @option
18450 @c !sort!
18451 @item /CREATE=directory
18452 @cindex @code{/CREATE} (@code{gnatlbr})
18453 Create the new run-time library in the specified directory.
18454
18455 @item /SET=directory
18456 @cindex @code{/SET} (@code{gnatlbr})
18457 Make the library in the specified directory the current run-time library.
18458
18459 @item /DELETE=directory
18460 @cindex @code{/DELETE} (@code{gnatlbr})
18461 Delete the run-time library in the specified directory.
18462
18463 @item /CONFIG=file
18464 @cindex @code{/CONFIG} (@code{gnatlbr})
18465 With /CREATE: Use the configuration pragmas in the specified file when
18466 building the library.
18467
18468 With /SET: Use the configuration pragmas in the specified file when
18469 compiling.
18470
18471 @end table
18472
18473 @node Examples of gnatlbr Usage
18474 @section Example of @code{gnatlbr} Usage
18475
18476 @smallexample
18477 Contents of VAXFLOAT.ADC:
18478 pragma Float_Representation (VAX_Float);
18479
18480 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18481
18482 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18483
18484 @end smallexample
18485 @end ifset
18486
18487 @node The GNAT Library Browser gnatls
18488 @chapter The GNAT Library Browser @code{gnatls}
18489 @findex gnatls
18490 @cindex Library browser
18491
18492 @noindent
18493 @code{gnatls} is a tool that outputs information about compiled
18494 units. It gives the relationship between objects, unit names and source
18495 files. It can also be used to check the source dependencies of a unit
18496 as well as various characteristics.
18497
18498 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18499 driver (see @ref{The GNAT Driver and Project Files}).
18500
18501 @menu
18502 * Running gnatls::
18503 * Switches for gnatls::
18504 * Examples of gnatls Usage::
18505 @end menu
18506
18507 @node Running gnatls
18508 @section Running @code{gnatls}
18509
18510 @noindent
18511 The @code{gnatls} command has the form
18512
18513 @smallexample
18514 $ gnatls switches @var{object_or_ali_file}
18515 @end smallexample
18516
18517 @noindent
18518 The main argument is the list of object or @file{ali} files
18519 (@pxref{The Ada Library Information Files})
18520 for which information is requested.
18521
18522 In normal mode, without additional option, @code{gnatls} produces a
18523 four-column listing. Each line represents information for a specific
18524 object. The first column gives the full path of the object, the second
18525 column gives the name of the principal unit in this object, the third
18526 column gives the status of the source and the fourth column gives the
18527 full path of the source representing this unit.
18528 Here is a simple example of use:
18529
18530 @smallexample
18531 $ gnatls *.o
18532 ^./^[]^demo1.o            demo1            DIF demo1.adb
18533 ^./^[]^demo2.o            demo2             OK demo2.adb
18534 ^./^[]^hello.o            h1                OK hello.adb
18535 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
18536 ^./^[]^instr.o            instr             OK instr.adb
18537 ^./^[]^tef.o              tef              DIF tef.adb
18538 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
18539 ^./^[]^tgef.o             tgef             DIF tgef.adb
18540 @end smallexample
18541
18542 @noindent
18543 The first line can be interpreted as follows: the main unit which is
18544 contained in
18545 object file @file{demo1.o} is demo1, whose main source is in
18546 @file{demo1.adb}. Furthermore, the version of the source used for the
18547 compilation of demo1 has been modified (DIF). Each source file has a status
18548 qualifier which can be:
18549
18550 @table @code
18551 @item OK (unchanged)
18552 The version of the source file used for the compilation of the
18553 specified unit corresponds exactly to the actual source file.
18554
18555 @item MOK (slightly modified)
18556 The version of the source file used for the compilation of the
18557 specified unit differs from the actual source file but not enough to
18558 require recompilation. If you use gnatmake with the qualifier
18559 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18560 MOK will not be recompiled.
18561
18562 @item DIF (modified)
18563 No version of the source found on the path corresponds to the source
18564 used to build this object.
18565
18566 @item ??? (file not found)
18567 No source file was found for this unit.
18568
18569 @item HID (hidden,  unchanged version not first on PATH)
18570 The version of the source that corresponds exactly to the source used
18571 for compilation has been found on the path but it is hidden by another
18572 version of the same source that has been modified.
18573
18574 @end table
18575
18576 @node Switches for gnatls
18577 @section Switches for @code{gnatls}
18578
18579 @noindent
18580 @code{gnatls} recognizes the following switches:
18581
18582 @table @option
18583 @c !sort!
18584 @cindex @option{--version} @command{gnatls}
18585 Display Copyright and version, then exit disregarding all other options.
18586
18587 @item --help
18588 @cindex @option{--help} @command{gnatls}
18589 If @option{--version} was not used, display usage, then exit disregarding
18590 all other options.
18591
18592 @item ^-a^/ALL_UNITS^
18593 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18594 Consider all units, including those of the predefined Ada library.
18595 Especially useful with @option{^-d^/DEPENDENCIES^}.
18596
18597 @item ^-d^/DEPENDENCIES^
18598 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18599 List sources from which specified units depend on.
18600
18601 @item ^-h^/OUTPUT=OPTIONS^
18602 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18603 Output the list of options.
18604
18605 @item ^-o^/OUTPUT=OBJECTS^
18606 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18607 Only output information about object files.
18608
18609 @item ^-s^/OUTPUT=SOURCES^
18610 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18611 Only output information about source files.
18612
18613 @item ^-u^/OUTPUT=UNITS^
18614 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18615 Only output information about compilation units.
18616
18617 @item ^-files^/FILES^=@var{file}
18618 @cindex @option{^-files^/FILES^} (@code{gnatls})
18619 Take as arguments the files listed in text file @var{file}.
18620 Text file @var{file} may contain empty lines that are ignored.
18621 Each nonempty line should contain the name of an existing file.
18622 Several such switches may be specified simultaneously.
18623
18624 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18625 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18626 @itemx ^-I^/SEARCH=^@var{dir}
18627 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
18628 @itemx -nostdinc
18629 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18630 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18631 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18632 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18633 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18634 flags (@pxref{Switches for gnatmake}).
18635
18636 @item --RTS=@var{rts-path}
18637 @cindex @option{--RTS} (@code{gnatls})
18638 Specifies the default location of the runtime library. Same meaning as the
18639 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18640
18641 @item ^-v^/OUTPUT=VERBOSE^
18642 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18643 Verbose mode. Output the complete source, object and project paths. Do not use
18644 the default column layout but instead use long format giving as much as
18645 information possible on each requested units, including special
18646 characteristics such as:
18647
18648 @table @code
18649 @item  Preelaborable
18650 The unit is preelaborable in the Ada sense.
18651
18652 @item No_Elab_Code
18653 No elaboration code has been produced by the compiler for this unit.
18654
18655 @item Pure
18656 The unit is pure in the Ada sense.
18657
18658 @item Elaborate_Body
18659 The unit contains a pragma Elaborate_Body.
18660
18661 @item Remote_Types
18662 The unit contains a pragma Remote_Types.
18663
18664 @item Shared_Passive
18665 The unit contains a pragma Shared_Passive.
18666
18667 @item Predefined
18668 This unit is part of the predefined environment and cannot be modified
18669 by the user.
18670
18671 @item Remote_Call_Interface
18672 The unit contains a pragma Remote_Call_Interface.
18673
18674 @end table
18675
18676 @end table
18677
18678 @node Examples of gnatls Usage
18679 @section Example of @code{gnatls} Usage
18680 @ifclear vms
18681
18682 @noindent
18683 Example of using the verbose switch. Note how the source and
18684 object paths are affected by the -I switch.
18685
18686 @smallexample
18687 $ gnatls -v -I.. demo1.o
18688
18689 GNATLS 5.03w (20041123-34)
18690 Copyright 1997-2004 Free Software Foundation, Inc.
18691
18692 Source Search Path:
18693    <Current_Directory>
18694    ../
18695    /home/comar/local/adainclude/
18696
18697 Object Search Path:
18698    <Current_Directory>
18699    ../
18700    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18701
18702 Project Search Path:
18703    <Current_Directory>
18704    /home/comar/local/lib/gnat/
18705
18706 ./demo1.o
18707    Unit =>
18708      Name   => demo1
18709      Kind   => subprogram body
18710      Flags  => No_Elab_Code
18711      Source => demo1.adb    modified
18712 @end smallexample
18713
18714 @noindent
18715 The following is an example of use of the dependency list.
18716 Note the use of the -s switch
18717 which gives a straight list of source files. This can be useful for
18718 building specialized scripts.
18719
18720 @smallexample
18721 $ gnatls -d demo2.o
18722 ./demo2.o   demo2        OK demo2.adb
18723                          OK gen_list.ads
18724                          OK gen_list.adb
18725                          OK instr.ads
18726                          OK instr-child.ads
18727
18728 $ gnatls -d -s -a demo1.o
18729 demo1.adb
18730 /home/comar/local/adainclude/ada.ads
18731 /home/comar/local/adainclude/a-finali.ads
18732 /home/comar/local/adainclude/a-filico.ads
18733 /home/comar/local/adainclude/a-stream.ads
18734 /home/comar/local/adainclude/a-tags.ads
18735 gen_list.ads
18736 gen_list.adb
18737 /home/comar/local/adainclude/gnat.ads
18738 /home/comar/local/adainclude/g-io.ads
18739 instr.ads
18740 /home/comar/local/adainclude/system.ads
18741 /home/comar/local/adainclude/s-exctab.ads
18742 /home/comar/local/adainclude/s-finimp.ads
18743 /home/comar/local/adainclude/s-finroo.ads
18744 /home/comar/local/adainclude/s-secsta.ads
18745 /home/comar/local/adainclude/s-stalib.ads
18746 /home/comar/local/adainclude/s-stoele.ads
18747 /home/comar/local/adainclude/s-stratt.ads
18748 /home/comar/local/adainclude/s-tasoli.ads
18749 /home/comar/local/adainclude/s-unstyp.ads
18750 /home/comar/local/adainclude/unchconv.ads
18751 @end smallexample
18752 @end ifclear
18753
18754 @ifset vms
18755 @smallexample
18756 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18757
18758 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18759 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18760 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18761 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18762 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18763 demo1.adb
18764 gen_list.ads
18765 gen_list.adb
18766 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18767 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18768 instr.ads
18769 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18770 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18771 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18772 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18773 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18774 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18775 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18776 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18777 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18778 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18779 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18780 @end smallexample
18781 @end ifset
18782
18783 @node Cleaning Up Using gnatclean
18784 @chapter Cleaning Up Using @code{gnatclean}
18785 @findex gnatclean
18786 @cindex Cleaning tool
18787
18788 @noindent
18789 @code{gnatclean} is a tool that allows the deletion of files produced by the
18790 compiler, binder and linker, including ALI files, object files, tree files,
18791 expanded source files, library files, interface copy source files, binder
18792 generated files and executable files.
18793
18794 @menu
18795 * Running gnatclean::
18796 * Switches for gnatclean::
18797 @c * Examples of gnatclean Usage::
18798 @end menu
18799
18800 @node Running gnatclean
18801 @section Running @code{gnatclean}
18802
18803 @noindent
18804 The @code{gnatclean} command has the form:
18805
18806 @smallexample
18807 $ gnatclean switches @var{names}
18808 @end smallexample
18809
18810 @noindent
18811 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18812 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18813 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18814
18815 @noindent
18816 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18817 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18818 the linker. In informative-only mode, specified by switch
18819 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18820 normal mode is listed, but no file is actually deleted.
18821
18822 @node Switches for gnatclean
18823 @section Switches for @code{gnatclean}
18824
18825 @noindent
18826 @code{gnatclean} recognizes the following switches:
18827
18828 @table @option
18829 @c !sort!
18830 @cindex @option{--version} @command{gnatclean}
18831 Display Copyright and version, then exit disregarding all other options.
18832
18833 @item --help
18834 @cindex @option{--help} @command{gnatclean}
18835 If @option{--version} was not used, display usage, then exit disregarding
18836 all other options.
18837
18838 @item ^-c^/COMPILER_FILES_ONLY^
18839 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18840 Only attempt to delete the files produced by the compiler, not those produced
18841 by the binder or the linker. The files that are not to be deleted are library
18842 files, interface copy files, binder generated files and executable files.
18843
18844 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18845 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18846 Indicate that ALI and object files should normally be found in directory
18847 @var{dir}.
18848
18849 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18850 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18851 When using project files, if some errors or warnings are detected during
18852 parsing and verbose mode is not in effect (no use of switch
18853 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18854 file, rather than its simple file name.
18855
18856 @item ^-h^/HELP^
18857 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18858 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18859
18860 @item ^-n^/NODELETE^
18861 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18862 Informative-only mode. Do not delete any files. Output the list of the files
18863 that would have been deleted if this switch was not specified.
18864
18865 @item ^-P^/PROJECT_FILE=^@var{project}
18866 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18867 Use project file @var{project}. Only one such switch can be used.
18868 When cleaning a project file, the files produced by the compilation of the
18869 immediate sources or inherited sources of the project files are to be
18870 deleted. This is not depending on the presence or not of executable names
18871 on the command line.
18872
18873 @item ^-q^/QUIET^
18874 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18875 Quiet output. If there are no errors, do not output anything, except in
18876 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18877 (switch ^-n^/NODELETE^).
18878
18879 @item ^-r^/RECURSIVE^
18880 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18881 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18882 clean all imported and extended project files, recursively. If this switch
18883 is not specified, only the files related to the main project file are to be
18884 deleted. This switch has no effect if no project file is specified.
18885
18886 @item ^-v^/VERBOSE^
18887 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18888 Verbose mode.
18889
18890 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18891 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18892 Indicates the verbosity of the parsing of GNAT project files.
18893 @xref{Switches Related to Project Files}.
18894
18895 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18896 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18897 Indicates that external variable @var{name} has the value @var{value}.
18898 The Project Manager will use this value for occurrences of
18899 @code{external(name)} when parsing the project file.
18900 @xref{Switches Related to Project Files}.
18901
18902 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18903 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18904 When searching for ALI and object files, look in directory
18905 @var{dir}.
18906
18907 @item ^-I^/SEARCH=^@var{dir}
18908 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18909 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18910
18911 @item ^-I-^/NOCURRENT_DIRECTORY^
18912 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18913 @cindex Source files, suppressing search
18914 Do not look for ALI or object files in the directory
18915 where @code{gnatclean} was invoked.
18916
18917 @end table
18918
18919 @c @node Examples of gnatclean Usage
18920 @c @section Examples of @code{gnatclean} Usage
18921
18922 @ifclear vms
18923 @node GNAT and Libraries
18924 @chapter GNAT and Libraries
18925 @cindex Library, building, installing, using
18926
18927 @noindent
18928 This chapter describes how to build and use libraries with GNAT, and also shows
18929 how to recompile the GNAT run-time library. You should be familiar with the
18930 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18931 chapter.
18932
18933 @menu
18934 * Introduction to Libraries in GNAT::
18935 * General Ada Libraries::
18936 * Stand-alone Ada Libraries::
18937 * Rebuilding the GNAT Run-Time Library::
18938 @end menu
18939
18940 @node Introduction to Libraries in GNAT
18941 @section Introduction to Libraries in GNAT
18942
18943 @noindent
18944 A library is, conceptually, a collection of objects which does not have its
18945 own main thread of execution, but rather provides certain services to the
18946 applications that use it. A library can be either statically linked with the
18947 application, in which case its code is directly included in the application,
18948 or, on platforms that support it, be dynamically linked, in which case
18949 its code is shared by all applications making use of this library.
18950
18951 GNAT supports both types of libraries.
18952 In the static case, the compiled code can be provided in different ways. The
18953 simplest approach is to provide directly the set of objects resulting from
18954 compilation of the library source files. Alternatively, you can group the
18955 objects into an archive using whatever commands are provided by the operating
18956 system. For the latter case, the objects are grouped into a shared library.
18957
18958 In the GNAT environment, a library has three types of components:
18959 @itemize @bullet
18960 @item
18961 Source files.
18962 @item
18963 @file{ALI} files.
18964 @xref{The Ada Library Information Files}.
18965 @item
18966 Object files, an archive or a shared library.
18967 @end itemize
18968
18969 @noindent
18970 A GNAT library may expose all its source files, which is useful for
18971 documentation purposes. Alternatively, it may expose only the units needed by
18972 an external user to make use of the library. That is to say, the specs
18973 reflecting the library services along with all the units needed to compile
18974 those specs, which can include generic bodies or any body implementing an
18975 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18976 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18977
18978 All compilation units comprising an application, including those in a library,
18979 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18980 computes the elaboration order from the @file{ALI} files and this is why they
18981 constitute a mandatory part of GNAT libraries.
18982 @emph{Stand-alone libraries} are the exception to this rule because a specific
18983 library elaboration routine is produced independently of the application(s)
18984 using the library.
18985
18986 @node General Ada Libraries
18987 @section General Ada Libraries
18988
18989 @menu
18990 * Building a library::
18991 * Installing a library::
18992 * Using a library::
18993 @end menu
18994
18995 @node Building a library
18996 @subsection Building a library
18997
18998 @noindent
18999 The easiest way to build a library is to use the Project Manager,
19000 which supports a special type of project called a @emph{Library Project}
19001 (@pxref{Library Projects}).
19002
19003 A project is considered a library project, when two project-level attributes
19004 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
19005 control different aspects of library configuration, additional optional
19006 project-level attributes can be specified:
19007 @table @code
19008 @item Library_Kind
19009 This attribute controls whether the library is to be static or dynamic
19010
19011 @item Library_Version
19012 This attribute specifies the library version; this value is used
19013 during dynamic linking of shared libraries to determine if the currently
19014 installed versions of the binaries are compatible.
19015
19016 @item Library_Options
19017 @item Library_GCC
19018 These attributes specify additional low-level options to be used during
19019 library generation, and redefine the actual application used to generate
19020 library.
19021 @end table
19022
19023 @noindent
19024 The GNAT Project Manager takes full care of the library maintenance task,
19025 including recompilation of the source files for which objects do not exist
19026 or are not up to date, assembly of the library archive, and installation of
19027 the library (i.e., copying associated source, object and @file{ALI} files
19028 to the specified location).
19029
19030 Here is a simple library project file:
19031 @smallexample @c ada
19032 project My_Lib is
19033    for Source_Dirs use ("src1", "src2");
19034    for Object_Dir use "obj";
19035    for Library_Name use "mylib";
19036    for Library_Dir use "lib";
19037    for Library_Kind use "dynamic";
19038 end My_lib;
19039 @end smallexample
19040
19041 @noindent
19042 and the compilation command to build and install the library:
19043
19044 @smallexample @c ada
19045   $ gnatmake -Pmy_lib
19046 @end smallexample
19047
19048 @noindent
19049 It is not entirely trivial to perform manually all the steps required to
19050 produce a library. We recommend that you use the GNAT Project Manager
19051 for this task. In special cases where this is not desired, the necessary
19052 steps are discussed below.
19053
19054 There are various possibilities for compiling the units that make up the
19055 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
19056 with a conventional script. For simple libraries, it is also possible to create
19057 a dummy main program which depends upon all the packages that comprise the
19058 interface of the library. This dummy main program can then be given to
19059 @command{gnatmake}, which will ensure that all necessary objects are built.
19060
19061 After this task is accomplished, you should follow the standard procedure
19062 of the underlying operating system to produce the static or shared library.
19063
19064 Here is an example of such a dummy program:
19065 @smallexample @c ada
19066 @group
19067 with My_Lib.Service1;
19068 with My_Lib.Service2;
19069 with My_Lib.Service3;
19070 procedure My_Lib_Dummy is
19071 begin
19072    null;
19073 end;
19074 @end group
19075 @end smallexample
19076
19077 @noindent
19078 Here are the generic commands that will build an archive or a shared library.
19079
19080 @smallexample
19081 # compiling the library
19082 $ gnatmake -c my_lib_dummy.adb
19083
19084 # we don't need the dummy object itself
19085 $ rm my_lib_dummy.o my_lib_dummy.ali
19086
19087 # create an archive with the remaining objects
19088 $ ar rc libmy_lib.a *.o
19089 # some systems may require "ranlib" to be run as well
19090
19091 # or create a shared library
19092 $ gcc -shared -o libmy_lib.so *.o
19093 # some systems may require the code to have been compiled with -fPIC
19094
19095 # remove the object files that are now in the library
19096 $ rm *.o
19097
19098 # Make the ALI files read-only so that gnatmake will not try to
19099 # regenerate the objects that are in the library
19100 $ chmod -w *.ali
19101 @end smallexample
19102
19103 @noindent
19104 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
19105 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
19106 be accessed by the directive @option{-l@var{xxx}} at link time.
19107
19108 @node Installing a library
19109 @subsection Installing a library
19110 @cindex @code{ADA_PROJECT_PATH}
19111 @cindex @code{GPR_PROJECT_PATH}
19112
19113 @noindent
19114 If you use project files, library installation is part of the library build
19115 process. Thus no further action is needed in order to make use of the
19116 libraries that are built as part of the general application build. A usable
19117 version of the library is installed in the directory specified by the
19118 @code{Library_Dir} attribute of the library project file.
19119
19120 You may want to install a library in a context different from where the library
19121 is built. This situation arises with third party suppliers, who may want
19122 to distribute a library in binary form where the user is not expected to be
19123 able to recompile the library. The simplest option in this case is to provide
19124 a project file slightly different from the one used to build the library, by
19125 using the @code{externally_built} attribute. For instance, the project
19126 file used to build the library in the previous section can be changed into the
19127 following one when the library is installed:
19128
19129 @smallexample @c projectfile
19130 project My_Lib is
19131    for Source_Dirs use ("src1", "src2");
19132    for Library_Name use "mylib";
19133    for Library_Dir use "lib";
19134    for Library_Kind use "dynamic";
19135    for Externally_Built use "true";
19136 end My_lib;
19137 @end smallexample
19138
19139 @noindent
19140 This project file assumes that the directories @file{src1},
19141 @file{src2}, and @file{lib} exist in
19142 the directory containing the project file. The @code{externally_built}
19143 attribute makes it clear to the GNAT builder that it should not attempt to
19144 recompile any of the units from this library. It allows the library provider to
19145 restrict the source set to the minimum necessary for clients to make use of the
19146 library as described in the first section of this chapter. It is the
19147 responsibility of the library provider to install the necessary sources, ALI
19148 files and libraries in the directories mentioned in the project file. For
19149 convenience, the user's library project file should be installed in a location
19150 that will be searched automatically by the GNAT
19151 builder. These are the directories referenced in the @env{GPR_PROJECT_PATH}
19152 environment variable (@pxref{Importing Projects}), and also the default GNAT
19153 library location that can be queried with @command{gnatls -v} and is usually of
19154 the form $gnat_install_root/lib/gnat.
19155
19156 When project files are not an option, it is also possible, but not recommended,
19157 to install the library so that the sources needed to use the library are on the
19158 Ada source path and the ALI files & libraries be on the Ada Object path (see
19159 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
19160 administrator can place general-purpose libraries in the default compiler
19161 paths, by specifying the libraries' location in the configuration files
19162 @file{ada_source_path} and @file{ada_object_path}. These configuration files
19163 must be located in the GNAT installation tree at the same place as the gcc spec
19164 file. The location of the gcc spec file can be determined as follows:
19165 @smallexample
19166 $ gcc -v
19167 @end smallexample
19168
19169 @noindent
19170 The configuration files mentioned above have a simple format: each line
19171 must contain one unique directory name.
19172 Those names are added to the corresponding path
19173 in their order of appearance in the file. The names can be either absolute
19174 or relative; in the latter case, they are relative to where theses files
19175 are located.
19176
19177 The files @file{ada_source_path} and @file{ada_object_path} might not be
19178 present in a
19179 GNAT installation, in which case, GNAT will look for its run-time library in
19180 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
19181 objects and @file{ALI} files). When the files exist, the compiler does not
19182 look in @file{adainclude} and @file{adalib}, and thus the
19183 @file{ada_source_path} file
19184 must contain the location for the GNAT run-time sources (which can simply
19185 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
19186 contain the location for the GNAT run-time objects (which can simply
19187 be @file{adalib}).
19188
19189 You can also specify a new default path to the run-time library at compilation
19190 time with the switch @option{--RTS=rts-path}. You can thus choose / change
19191 the run-time library you want your program to be compiled with. This switch is
19192 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
19193 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
19194
19195 It is possible to install a library before or after the standard GNAT
19196 library, by reordering the lines in the configuration files. In general, a
19197 library must be installed before the GNAT library if it redefines
19198 any part of it.
19199
19200 @node Using a library
19201 @subsection Using a library
19202
19203 @noindent Once again, the project facility greatly simplifies the use of
19204 libraries. In this context, using a library is just a matter of adding a
19205 @code{with} clause in the user project. For instance, to make use of the
19206 library @code{My_Lib} shown in examples in earlier sections, you can
19207 write:
19208
19209 @smallexample @c projectfile
19210 with "my_lib";
19211 project My_Proj is
19212   @dots{}
19213 end My_Proj;
19214 @end smallexample
19215
19216 Even if you have a third-party, non-Ada library, you can still use GNAT's
19217 Project Manager facility to provide a wrapper for it. For example, the
19218 following project, when @code{with}ed by your main project, will link with the
19219 third-party library @file{liba.a}:
19220
19221 @smallexample @c projectfile
19222 @group
19223 project Liba is
19224    for Externally_Built use "true";
19225    for Source_Files use ();
19226    for Library_Dir use "lib";
19227    for Library_Name use "a";
19228    for Library_Kind use "static";
19229 end Liba;
19230 @end group
19231 @end smallexample
19232 This is an alternative to the use of @code{pragma Linker_Options}. It is
19233 especially interesting in the context of systems with several interdependent
19234 static libraries where finding a proper linker order is not easy and best be
19235 left to the tools having visibility over project dependence information.
19236
19237 @noindent
19238 In order to use an Ada library manually, you need to make sure that this
19239 library is on both your source and object path
19240 (see @ref{Search Paths and the Run-Time Library (RTL)}
19241 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
19242 in an archive or a shared library, you need to specify the desired
19243 library at link time.
19244
19245 For example, you can use the library @file{mylib} installed in
19246 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
19247
19248 @smallexample
19249 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
19250   -largs -lmy_lib
19251 @end smallexample
19252
19253 @noindent
19254 This can be expressed more simply:
19255 @smallexample
19256 $ gnatmake my_appl
19257 @end smallexample
19258 @noindent
19259 when the following conditions are met:
19260 @itemize @bullet
19261 @item
19262 @file{/dir/my_lib_src} has been added by the user to the environment
19263 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
19264 @file{ada_source_path}
19265 @item
19266 @file{/dir/my_lib_obj} has been added by the user to the environment
19267 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
19268 @file{ada_object_path}
19269 @item
19270 a pragma @code{Linker_Options} has been added to one of the sources.
19271 For example:
19272
19273 @smallexample @c ada
19274 pragma Linker_Options ("-lmy_lib");
19275 @end smallexample
19276 @end itemize
19277
19278 @node Stand-alone Ada Libraries
19279 @section Stand-alone Ada Libraries
19280 @cindex Stand-alone library, building, using
19281
19282 @menu
19283 * Introduction to Stand-alone Libraries::
19284 * Building a Stand-alone Library::
19285 * Creating a Stand-alone Library to be used in a non-Ada context::
19286 * Restrictions in Stand-alone Libraries::
19287 @end menu
19288
19289 @node Introduction to Stand-alone Libraries
19290 @subsection Introduction to Stand-alone Libraries
19291
19292 @noindent
19293 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
19294 necessary code to
19295 elaborate the Ada units that are included in the library. In contrast with
19296 an ordinary library, which consists of all sources, objects and @file{ALI}
19297 files of the
19298 library, a SAL may specify a restricted subset of compilation units
19299 to serve as a library interface. In this case, the fully
19300 self-sufficient set of files will normally consist of an objects
19301 archive, the sources of interface units' specs, and the @file{ALI}
19302 files of interface units.
19303 If an interface spec contains a generic unit or an inlined subprogram,
19304 the body's
19305 source must also be provided; if the units that must be provided in the source
19306 form depend on other units, the source and @file{ALI} files of those must
19307 also be provided.
19308
19309 The main purpose of a SAL is to minimize the recompilation overhead of client
19310 applications when a new version of the library is installed. Specifically,
19311 if the interface sources have not changed, client applications do not need to
19312 be recompiled. If, furthermore, a SAL is provided in the shared form and its
19313 version, controlled by @code{Library_Version} attribute, is not changed,
19314 then the clients do not need to be relinked.
19315
19316 SALs also allow the library providers to minimize the amount of library source
19317 text exposed to the clients.  Such ``information hiding'' might be useful or
19318 necessary for various reasons.
19319
19320 Stand-alone libraries are also well suited to be used in an executable whose
19321 main routine is not written in Ada.
19322
19323 @node Building a Stand-alone Library
19324 @subsection Building a Stand-alone Library
19325
19326 @noindent
19327 GNAT's Project facility provides a simple way of building and installing
19328 stand-alone libraries; see @ref{Stand-alone Library Projects}.
19329 To be a Stand-alone Library Project, in addition to the two attributes
19330 that make a project a Library Project (@code{Library_Name} and
19331 @code{Library_Dir}; see @ref{Library Projects}), the attribute
19332 @code{Library_Interface} must be defined.  For example:
19333
19334 @smallexample @c projectfile
19335 @group
19336    for Library_Dir use "lib_dir";
19337    for Library_Name use "dummy";
19338    for Library_Interface use ("int1", "int1.child");
19339 @end group
19340 @end smallexample
19341
19342 @noindent
19343 Attribute @code{Library_Interface} has a non-empty string list value,
19344 each string in the list designating a unit contained in an immediate source
19345 of the project file.
19346
19347 When a Stand-alone Library is built, first the binder is invoked to build
19348 a package whose name depends on the library name
19349 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
19350 This binder-generated package includes initialization and
19351 finalization procedures whose
19352 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
19353 in the example
19354 above). The object corresponding to this package is included in the library.
19355
19356 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
19357 calling of these procedures if a static SAL is built, or if a shared SAL
19358 is built
19359 with the project-level attribute @code{Library_Auto_Init} set to
19360 @code{"false"}.
19361
19362 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
19363 (those that are listed in attribute @code{Library_Interface}) are copied to
19364 the Library Directory. As a consequence, only the Interface Units may be
19365 imported from Ada units outside of the library. If other units are imported,
19366 the binding phase will fail.
19367
19368 The attribute @code{Library_Src_Dir} may be specified for a
19369 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
19370 single string value. Its value must be the path (absolute or relative to the
19371 project directory) of an existing directory. This directory cannot be the
19372 object directory or one of the source directories, but it can be the same as
19373 the library directory. The sources of the Interface
19374 Units of the library that are needed by an Ada client of the library will be
19375 copied to the designated directory, called the Interface Copy directory.
19376 These sources include the specs of the Interface Units, but they may also
19377 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
19378 are used, or when there is a generic unit in the spec. Before the sources
19379 are copied to the Interface Copy directory, an attempt is made to delete all
19380 files in the Interface Copy directory.
19381
19382 Building stand-alone libraries by hand is somewhat tedious, but for those
19383 occasions when it is necessary here are the steps that you need to perform:
19384 @itemize @bullet
19385 @item
19386 Compile all library sources.
19387
19388 @item
19389 Invoke the binder with the switch @option{-n} (No Ada main program),
19390 with all the @file{ALI} files of the interfaces, and
19391 with the switch @option{-L} to give specific names to the @code{init}
19392 and @code{final} procedures.  For example:
19393 @smallexample
19394   gnatbind -n int1.ali int2.ali -Lsal1
19395 @end smallexample
19396
19397 @item
19398 Compile the binder generated file:
19399 @smallexample
19400   gcc -c b~int2.adb
19401 @end smallexample
19402
19403 @item
19404 Link the dynamic library with all the necessary object files,
19405 indicating to the linker the names of the @code{init} (and possibly
19406 @code{final}) procedures for automatic initialization (and finalization).
19407 The built library should be placed in a directory different from
19408 the object directory.
19409
19410 @item
19411 Copy the @code{ALI} files of the interface to the library directory,
19412 add in this copy an indication that it is an interface to a SAL
19413 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19414 with letter ``P'') and make the modified copy of the @file{ALI} file
19415 read-only.
19416 @end itemize
19417
19418 @noindent
19419 Using SALs is not different from using other libraries
19420 (see @ref{Using a library}).
19421
19422 @node Creating a Stand-alone Library to be used in a non-Ada context
19423 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19424
19425 @noindent
19426 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19427 a non-Ada context.
19428
19429 The only extra step required is to ensure that library interface subprograms
19430 are compatible with the main program, by means of @code{pragma Export}
19431 or @code{pragma Convention}.
19432
19433 Here is an example of simple library interface for use with C main program:
19434
19435 @smallexample @c ada
19436 package Interface is
19437
19438    procedure Do_Something;
19439    pragma Export (C, Do_Something, "do_something");
19440
19441    procedure Do_Something_Else;
19442    pragma Export (C, Do_Something_Else, "do_something_else");
19443
19444 end Interface;
19445 @end smallexample
19446
19447 @noindent
19448 On the foreign language side, you must provide a ``foreign'' view of the
19449 library interface; remember that it should contain elaboration routines in
19450 addition to interface subprograms.
19451
19452 The example below shows the content of @code{mylib_interface.h} (note
19453 that there is no rule for the naming of this file, any name can be used)
19454 @smallexample
19455 /* the library elaboration procedure */
19456 extern void mylibinit (void);
19457
19458 /* the library finalization procedure */
19459 extern void mylibfinal (void);
19460
19461 /* the interface exported by the library */
19462 extern void do_something (void);
19463 extern void do_something_else (void);
19464 @end smallexample
19465
19466 @noindent
19467 Libraries built as explained above can be used from any program, provided
19468 that the elaboration procedures (named @code{mylibinit} in the previous
19469 example) are called before the library services are used. Any number of
19470 libraries can be used simultaneously, as long as the elaboration
19471 procedure of each library is called.
19472
19473 Below is an example of a C program that uses the @code{mylib} library.
19474
19475 @smallexample
19476 #include "mylib_interface.h"
19477
19478 int
19479 main (void)
19480 @{
19481    /* First, elaborate the library before using it */
19482    mylibinit ();
19483
19484    /* Main program, using the library exported entities */
19485    do_something ();
19486    do_something_else ();
19487
19488    /* Library finalization at the end of the program */
19489    mylibfinal ();
19490    return 0;
19491 @}
19492 @end smallexample
19493
19494 @noindent
19495 Note that invoking any library finalization procedure generated by
19496 @code{gnatbind} shuts down the Ada run-time environment.
19497 Consequently, the
19498 finalization of all Ada libraries must be performed at the end of the program.
19499 No call to these libraries or to the Ada run-time library should be made
19500 after the finalization phase.
19501
19502 @node Restrictions in Stand-alone Libraries
19503 @subsection Restrictions in Stand-alone Libraries
19504
19505 @noindent
19506 The pragmas listed below should be used with caution inside libraries,
19507 as they can create incompatibilities with other Ada libraries:
19508 @itemize @bullet
19509 @item pragma @code{Locking_Policy}
19510 @item pragma @code{Queuing_Policy}
19511 @item pragma @code{Task_Dispatching_Policy}
19512 @item pragma @code{Unreserve_All_Interrupts}
19513 @end itemize
19514
19515 @noindent
19516 When using a library that contains such pragmas, the user must make sure
19517 that all libraries use the same pragmas with the same values. Otherwise,
19518 @code{Program_Error} will
19519 be raised during the elaboration of the conflicting
19520 libraries. The usage of these pragmas and its consequences for the user
19521 should therefore be well documented.
19522
19523 Similarly, the traceback in the exception occurrence mechanism should be
19524 enabled or disabled in a consistent manner across all libraries.
19525 Otherwise, Program_Error will be raised during the elaboration of the
19526 conflicting libraries.
19527
19528 If the @code{Version} or @code{Body_Version}
19529 attributes are used inside a library, then you need to
19530 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19531 libraries, so that version identifiers can be properly computed.
19532 In practice these attributes are rarely used, so this is unlikely
19533 to be a consideration.
19534
19535 @node  Rebuilding the GNAT Run-Time Library
19536 @section Rebuilding the GNAT Run-Time Library
19537 @cindex GNAT Run-Time Library, rebuilding
19538 @cindex Building the GNAT Run-Time Library
19539 @cindex Rebuilding the GNAT Run-Time Library
19540 @cindex Run-Time Library, rebuilding
19541
19542 @noindent
19543 It may be useful to recompile the GNAT library in various contexts, the
19544 most important one being the use of partition-wide configuration pragmas
19545 such as @code{Normalize_Scalars}. A special Makefile called
19546 @code{Makefile.adalib} is provided to that effect and can be found in
19547 the directory containing the GNAT library. The location of this
19548 directory depends on the way the GNAT environment has been installed and can
19549 be determined by means of the command:
19550
19551 @smallexample
19552 $ gnatls -v
19553 @end smallexample
19554
19555 @noindent
19556 The last entry in the object search path usually contains the
19557 gnat library. This Makefile contains its own documentation and in
19558 particular the set of instructions needed to rebuild a new library and
19559 to use it.
19560
19561 @node Using the GNU make Utility
19562 @chapter Using the GNU @code{make} Utility
19563 @findex make
19564
19565 @noindent
19566 This chapter offers some examples of makefiles that solve specific
19567 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19568 make, make, GNU @code{make}}), nor does it try to replace the
19569 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19570
19571 All the examples in this section are specific to the GNU version of
19572 make. Although @command{make} is a standard utility, and the basic language
19573 is the same, these examples use some advanced features found only in
19574 @code{GNU make}.
19575
19576 @menu
19577 * Using gnatmake in a Makefile::
19578 * Automatically Creating a List of Directories::
19579 * Generating the Command Line Switches::
19580 * Overcoming Command Line Length Limits::
19581 @end menu
19582
19583 @node Using gnatmake in a Makefile
19584 @section Using gnatmake in a Makefile
19585 @findex makefile
19586 @cindex GNU make
19587
19588 @noindent
19589 Complex project organizations can be handled in a very powerful way by
19590 using GNU make combined with gnatmake. For instance, here is a Makefile
19591 which allows you to build each subsystem of a big project into a separate
19592 shared library. Such a makefile allows you to significantly reduce the link
19593 time of very big applications while maintaining full coherence at
19594 each step of the build process.
19595
19596 The list of dependencies are handled automatically by
19597 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19598 the appropriate directories.
19599
19600 Note that you should also read the example on how to automatically
19601 create the list of directories
19602 (@pxref{Automatically Creating a List of Directories})
19603 which might help you in case your project has a lot of subdirectories.
19604
19605 @smallexample
19606 @iftex
19607 @leftskip=0cm
19608 @font@heightrm=cmr8
19609 @heightrm
19610 @end iftex
19611 ## This Makefile is intended to be used with the following directory
19612 ## configuration:
19613 ##  - The sources are split into a series of csc (computer software components)
19614 ##    Each of these csc is put in its own directory.
19615 ##    Their name are referenced by the directory names.
19616 ##    They will be compiled into shared library (although this would also work
19617 ##    with static libraries
19618 ##  - The main program (and possibly other packages that do not belong to any
19619 ##    csc is put in the top level directory (where the Makefile is).
19620 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
19621 ##                    \_ second_csc (sources) __ lib (will contain the library)
19622 ##                    \_ @dots{}
19623 ## Although this Makefile is build for shared library, it is easy to modify
19624 ## to build partial link objects instead (modify the lines with -shared and
19625 ## gnatlink below)
19626 ##
19627 ## With this makefile, you can change any file in the system or add any new
19628 ## file, and everything will be recompiled correctly (only the relevant shared
19629 ## objects will be recompiled, and the main program will be re-linked).
19630
19631 # The list of computer software component for your project. This might be
19632 # generated automatically.
19633 CSC_LIST=aa bb cc
19634
19635 # Name of the main program (no extension)
19636 MAIN=main
19637
19638 # If we need to build objects with -fPIC, uncomment the following line
19639 #NEED_FPIC=-fPIC
19640
19641 # The following variable should give the directory containing libgnat.so
19642 # You can get this directory through 'gnatls -v'. This is usually the last
19643 # directory in the Object_Path.
19644 GLIB=@dots{}
19645
19646 # The directories for the libraries
19647 # (This macro expands the list of CSC to the list of shared libraries, you
19648 # could simply use the expanded form:
19649 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19650 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19651
19652 $@{MAIN@}: objects $@{LIB_DIR@}
19653     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19654     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19655
19656 objects::
19657     # recompile the sources
19658     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19659
19660 # Note: In a future version of GNAT, the following commands will be simplified
19661 # by a new tool, gnatmlib
19662 $@{LIB_DIR@}:
19663     mkdir -p $@{dir $@@ @}
19664     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19665     cd $@{dir $@@ @} && cp -f ../*.ali .
19666
19667 # The dependencies for the modules
19668 # Note that we have to force the expansion of *.o, since in some cases
19669 # make won't be able to do it itself.
19670 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19671 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19672 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19673
19674 # Make sure all of the shared libraries are in the path before starting the
19675 # program
19676 run::
19677     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19678
19679 clean::
19680     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19681     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19682     $@{RM@} $@{CSC_LIST:%=%/*.o@}
19683     $@{RM@} *.o *.ali $@{MAIN@}
19684 @end smallexample
19685
19686 @node Automatically Creating a List of Directories
19687 @section Automatically Creating a List of Directories
19688
19689 @noindent
19690 In most makefiles, you will have to specify a list of directories, and
19691 store it in a variable. For small projects, it is often easier to
19692 specify each of them by hand, since you then have full control over what
19693 is the proper order for these directories, which ones should be
19694 included.
19695
19696 However, in larger projects, which might involve hundreds of
19697 subdirectories, it might be more convenient to generate this list
19698 automatically.
19699
19700 The example below presents two methods. The first one, although less
19701 general, gives you more control over the list. It involves wildcard
19702 characters, that are automatically expanded by @command{make}. Its
19703 shortcoming is that you need to explicitly specify some of the
19704 organization of your project, such as for instance the directory tree
19705 depth, whether some directories are found in a separate tree, @enddots{}
19706
19707 The second method is the most general one. It requires an external
19708 program, called @command{find}, which is standard on all Unix systems. All
19709 the directories found under a given root directory will be added to the
19710 list.
19711
19712 @smallexample
19713 @iftex
19714 @leftskip=0cm
19715 @font@heightrm=cmr8
19716 @heightrm
19717 @end iftex
19718 # The examples below are based on the following directory hierarchy:
19719 # All the directories can contain any number of files
19720 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
19721 #                       ->  ab
19722 #                       ->  ac
19723 #                ->  b  ->  ba  ->  baa
19724 #                       ->  bb
19725 #                       ->  bc
19726 # This Makefile creates a variable called DIRS, that can be reused any time
19727 # you need this list (see the other examples in this section)
19728
19729 # The root of your project's directory hierarchy
19730 ROOT_DIRECTORY=.
19731
19732 ####
19733 # First method: specify explicitly the list of directories
19734 # This allows you to specify any subset of all the directories you need.
19735 ####
19736
19737 DIRS := a/aa/ a/ab/ b/ba/
19738
19739 ####
19740 # Second method: use wildcards
19741 # Note that the argument(s) to wildcard below should end with a '/'.
19742 # Since wildcards also return file names, we have to filter them out
19743 # to avoid duplicate directory names.
19744 # We thus use make's @code{dir} and @code{sort} functions.
19745 # It sets DIRs to the following value (note that the directories aaa and baa
19746 # are not given, unless you change the arguments to wildcard).
19747 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19748 ####
19749
19750 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19751                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19752
19753 ####
19754 # Third method: use an external program
19755 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19756 # This is the most complete command: it sets DIRs to the following value:
19757 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19758 ####
19759
19760 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19761
19762 @end smallexample
19763
19764 @node Generating the Command Line Switches
19765 @section Generating the Command Line Switches
19766
19767 @noindent
19768 Once you have created the list of directories as explained in the
19769 previous section (@pxref{Automatically Creating a List of Directories}),
19770 you can easily generate the command line arguments to pass to gnatmake.
19771
19772 For the sake of completeness, this example assumes that the source path
19773 is not the same as the object path, and that you have two separate lists
19774 of directories.
19775
19776 @smallexample
19777 # see "Automatically creating a list of directories" to create
19778 # these variables
19779 SOURCE_DIRS=
19780 OBJECT_DIRS=
19781
19782 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19783 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19784
19785 all:
19786         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19787 @end smallexample
19788
19789 @node Overcoming Command Line Length Limits
19790 @section Overcoming Command Line Length Limits
19791
19792 @noindent
19793 One problem that might be encountered on big projects is that many
19794 operating systems limit the length of the command line. It is thus hard to give
19795 gnatmake the list of source and object directories.
19796
19797 This example shows how you can set up environment variables, which will
19798 make @command{gnatmake} behave exactly as if the directories had been
19799 specified on the command line, but have a much higher length limit (or
19800 even none on most systems).
19801
19802 It assumes that you have created a list of directories in your Makefile,
19803 using one of the methods presented in
19804 @ref{Automatically Creating a List of Directories}.
19805 For the sake of completeness, we assume that the object
19806 path (where the ALI files are found) is different from the sources patch.
19807
19808 Note a small trick in the Makefile below: for efficiency reasons, we
19809 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19810 expanded immediately by @code{make}. This way we overcome the standard
19811 make behavior which is to expand the variables only when they are
19812 actually used.
19813
19814 On Windows, if you are using the standard Windows command shell, you must
19815 replace colons with semicolons in the assignments to these variables.
19816
19817 @smallexample
19818 @iftex
19819 @leftskip=0cm
19820 @font@heightrm=cmr8
19821 @heightrm
19822 @end iftex
19823 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19824 # This is the same thing as putting the -I arguments on the command line.
19825 # (the equivalent of using -aI on the command line would be to define
19826 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19827 # You can of course have different values for these variables.
19828 #
19829 # Note also that we need to keep the previous values of these variables, since
19830 # they might have been set before running 'make' to specify where the GNAT
19831 # library is installed.
19832
19833 # see "Automatically creating a list of directories" to create these
19834 # variables
19835 SOURCE_DIRS=
19836 OBJECT_DIRS=
19837
19838 empty:=
19839 space:=$@{empty@} $@{empty@}
19840 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19841 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19842 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19843 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19844 export ADA_INCLUDE_PATH
19845 export ADA_OBJECT_PATH
19846
19847 all:
19848         gnatmake main_unit
19849 @end smallexample
19850 @end ifclear
19851
19852 @node Memory Management Issues
19853 @chapter Memory Management Issues
19854
19855 @noindent
19856 This chapter describes some useful memory pools provided in the GNAT library
19857 and in particular the GNAT Debug Pool facility, which can be used to detect
19858 incorrect uses of access values (including ``dangling references'').
19859 @ifclear vms
19860 It also describes the @command{gnatmem} tool, which can be used to track down
19861 ``memory leaks''.
19862 @end ifclear
19863
19864 @menu
19865 * Some Useful Memory Pools::
19866 * The GNAT Debug Pool Facility::
19867 @ifclear vms
19868 * The gnatmem Tool::
19869 @end ifclear
19870 @end menu
19871
19872 @node Some Useful Memory Pools
19873 @section Some Useful Memory Pools
19874 @findex Memory Pool
19875 @cindex storage, pool
19876
19877 @noindent
19878 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19879 storage pool. Allocations use the standard system call @code{malloc} while
19880 deallocations use the standard system call @code{free}. No reclamation is
19881 performed when the pool goes out of scope. For performance reasons, the
19882 standard default Ada allocators/deallocators do not use any explicit storage
19883 pools but if they did, they could use this storage pool without any change in
19884 behavior. That is why this storage pool is used  when the user
19885 manages to make the default implicit allocator explicit as in this example:
19886 @smallexample @c ada
19887    type T1 is access Something;
19888     -- no Storage pool is defined for T2
19889    type T2 is access Something_Else;
19890    for T2'Storage_Pool use T1'Storage_Pool;
19891    -- the above is equivalent to
19892    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19893 @end smallexample
19894
19895 @noindent
19896 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19897 pool. The allocation strategy is similar to @code{Pool_Local}'s
19898 except that the all
19899 storage allocated with this pool is reclaimed when the pool object goes out of
19900 scope. This pool provides a explicit mechanism similar to the implicit one
19901 provided by several Ada 83 compilers for allocations performed through a local
19902 access type and whose purpose was to reclaim memory when exiting the
19903 scope of a given local access. As an example, the following program does not
19904 leak memory even though it does not perform explicit deallocation:
19905
19906 @smallexample @c ada
19907 with System.Pool_Local;
19908 procedure Pooloc1 is
19909    procedure Internal is
19910       type A is access Integer;
19911       X : System.Pool_Local.Unbounded_Reclaim_Pool;
19912       for A'Storage_Pool use X;
19913       v : A;
19914    begin
19915       for I in  1 .. 50 loop
19916          v := new Integer;
19917       end loop;
19918    end Internal;
19919 begin
19920    for I in  1 .. 100 loop
19921       Internal;
19922    end loop;
19923 end Pooloc1;
19924 @end smallexample
19925
19926 @noindent
19927 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19928 @code{Storage_Size} is specified for an access type.
19929 The whole storage for the pool is
19930 allocated at once, usually on the stack at the point where the access type is
19931 elaborated. It is automatically reclaimed when exiting the scope where the
19932 access type is defined. This package is not intended to be used directly by the
19933 user and it is implicitly used for each such declaration:
19934
19935 @smallexample @c ada
19936    type T1 is access Something;
19937    for T1'Storage_Size use 10_000;
19938 @end smallexample
19939
19940 @node The GNAT Debug Pool Facility
19941 @section The GNAT Debug Pool Facility
19942 @findex Debug Pool
19943 @cindex storage, pool, memory corruption
19944
19945 @noindent
19946 The use of unchecked deallocation and unchecked conversion can easily
19947 lead to incorrect memory references. The problems generated by such
19948 references are usually difficult to tackle because the symptoms can be
19949 very remote from the origin of the problem. In such cases, it is
19950 very helpful to detect the problem as early as possible. This is the
19951 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19952
19953 In order to use the GNAT specific debugging pool, the user must
19954 associate a debug pool object with each of the access types that may be
19955 related to suspected memory problems. See Ada Reference Manual 13.11.
19956 @smallexample @c ada
19957 type Ptr is access Some_Type;
19958 Pool : GNAT.Debug_Pools.Debug_Pool;
19959 for Ptr'Storage_Pool use Pool;
19960 @end smallexample
19961
19962 @noindent
19963 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19964 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19965 allow the user to redefine allocation and deallocation strategies. They
19966 also provide a checkpoint for each dereference, through the use of
19967 the primitive operation @code{Dereference} which is implicitly called at
19968 each dereference of an access value.
19969
19970 Once an access type has been associated with a debug pool, operations on
19971 values of the type may raise four distinct exceptions,
19972 which correspond to four potential kinds of memory corruption:
19973 @itemize @bullet
19974 @item
19975 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19976 @item
19977 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19978 @item
19979 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19980 @item
19981 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19982 @end itemize
19983
19984 @noindent
19985 For types associated with a Debug_Pool, dynamic allocation is performed using
19986 the standard GNAT allocation routine. References to all allocated chunks of
19987 memory are kept in an internal dictionary. Several deallocation strategies are
19988 provided, whereupon the user can choose to release the memory to the system,
19989 keep it allocated for further invalid access checks, or fill it with an easily
19990 recognizable pattern for debug sessions. The memory pattern is the old IBM
19991 hexadecimal convention: @code{16#DEADBEEF#}.
19992
19993 See the documentation in the file g-debpoo.ads for more information on the
19994 various strategies.
19995
19996 Upon each dereference, a check is made that the access value denotes a
19997 properly allocated memory location. Here is a complete example of use of
19998 @code{Debug_Pools}, that includes typical instances of  memory corruption:
19999 @smallexample @c ada
20000 @iftex
20001 @leftskip=0cm
20002 @end iftex
20003 with Gnat.Io; use Gnat.Io;
20004 with Unchecked_Deallocation;
20005 with Unchecked_Conversion;
20006 with GNAT.Debug_Pools;
20007 with System.Storage_Elements;
20008 with Ada.Exceptions; use Ada.Exceptions;
20009 procedure Debug_Pool_Test is
20010
20011    type T is access Integer;
20012    type U is access all T;
20013
20014    P : GNAT.Debug_Pools.Debug_Pool;
20015    for T'Storage_Pool use P;
20016
20017    procedure Free is new Unchecked_Deallocation (Integer, T);
20018    function UC is new Unchecked_Conversion (U, T);
20019    A, B : aliased T;
20020
20021    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
20022
20023 begin
20024    Info (P);
20025    A := new Integer;
20026    B := new Integer;
20027    B := A;
20028    Info (P);
20029    Free (A);
20030    begin
20031       Put_Line (Integer'Image(B.all));
20032    exception
20033       when E : others => Put_Line ("raised: " & Exception_Name (E));
20034    end;
20035    begin
20036       Free (B);
20037    exception
20038       when E : others => Put_Line ("raised: " & Exception_Name (E));
20039    end;
20040    B := UC(A'Access);
20041    begin
20042       Put_Line (Integer'Image(B.all));
20043    exception
20044       when E : others => Put_Line ("raised: " & Exception_Name (E));
20045    end;
20046    begin
20047       Free (B);
20048    exception
20049       when E : others => Put_Line ("raised: " & Exception_Name (E));
20050    end;
20051    Info (P);
20052 end Debug_Pool_Test;
20053 @end smallexample
20054
20055 @noindent
20056 The debug pool mechanism provides the following precise diagnostics on the
20057 execution of this erroneous program:
20058 @smallexample
20059 Debug Pool info:
20060   Total allocated bytes :  0
20061   Total deallocated bytes :  0
20062   Current Water Mark:  0
20063   High Water Mark:  0
20064
20065 Debug Pool info:
20066   Total allocated bytes :  8
20067   Total deallocated bytes :  0
20068   Current Water Mark:  8
20069   High Water Mark:  8
20070
20071 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
20072 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
20073 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
20074 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
20075 Debug Pool info:
20076   Total allocated bytes :  8
20077   Total deallocated bytes :  4
20078   Current Water Mark:  4
20079   High Water Mark:  8
20080 @end smallexample
20081
20082 @ifclear vms
20083 @node The gnatmem Tool
20084 @section The @command{gnatmem} Tool
20085 @findex gnatmem
20086
20087 @noindent
20088 The @code{gnatmem} utility monitors dynamic allocation and
20089 deallocation activity in a program, and displays information about
20090 incorrect deallocations and possible sources of memory leaks.
20091 It is designed to work in association with a static runtime library
20092 only and in this context provides three types of information:
20093 @itemize @bullet
20094 @item
20095 General information concerning memory management, such as the total
20096 number of allocations and deallocations, the amount of allocated
20097 memory and the high water mark, i.e.@: the largest amount of allocated
20098 memory in the course of program execution.
20099
20100 @item
20101 Backtraces for all incorrect deallocations, that is to say deallocations
20102 which do not correspond to a valid allocation.
20103
20104 @item
20105 Information on each allocation that is potentially the origin of a memory
20106 leak.
20107 @end itemize
20108
20109 @menu
20110 * Running gnatmem::
20111 * Switches for gnatmem::
20112 * Example of gnatmem Usage::
20113 @end menu
20114
20115 @node Running gnatmem
20116 @subsection Running @code{gnatmem}
20117
20118 @noindent
20119 @code{gnatmem} makes use of the output created by the special version of
20120 allocation and deallocation routines that record call information. This
20121 allows to obtain accurate dynamic memory usage history at a minimal cost to
20122 the execution speed. Note however, that @code{gnatmem} is not supported on
20123 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
20124 Solaris and Windows NT/2000/XP (x86).
20125
20126 @noindent
20127 The @code{gnatmem} command has the form
20128
20129 @smallexample
20130    $ gnatmem @ovar{switches} user_program
20131 @end smallexample
20132
20133 @noindent
20134 The program must have been linked with the instrumented version of the
20135 allocation and deallocation routines. This is done by linking with the
20136 @file{libgmem.a} library. For correct symbolic backtrace information,
20137 the user program should be compiled with debugging options
20138 (see @ref{Switches for gcc}). For example to build @file{my_program}:
20139
20140 @smallexample
20141 $ gnatmake -g my_program -largs -lgmem
20142 @end smallexample
20143
20144 @noindent
20145 As library @file{libgmem.a} contains an alternate body for package
20146 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
20147 when an executable is linked with library @file{libgmem.a}. It is then not
20148 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
20149
20150 @noindent
20151 When @file{my_program} is executed, the file @file{gmem.out} is produced.
20152 This file contains information about all allocations and deallocations
20153 performed by the program. It is produced by the instrumented allocations and
20154 deallocations routines and will be used by @code{gnatmem}.
20155
20156 In order to produce symbolic backtrace information for allocations and
20157 deallocations performed by the GNAT run-time library, you need to use a
20158 version of that library that has been compiled with the @option{-g} switch
20159 (see @ref{Rebuilding the GNAT Run-Time Library}).
20160
20161 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
20162 examine. If the location of @file{gmem.out} file was not explicitly supplied by
20163 @option{-i} switch, gnatmem will assume that this file can be found in the
20164 current directory. For example, after you have executed @file{my_program},
20165 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
20166
20167 @smallexample
20168 $ gnatmem my_program
20169 @end smallexample
20170
20171 @noindent
20172 This will produce the output with the following format:
20173
20174 *************** debut cc
20175 @smallexample
20176 $ gnatmem my_program
20177
20178 Global information
20179 ------------------
20180    Total number of allocations        :  45
20181    Total number of deallocations      :   6
20182    Final Water Mark (non freed mem)   :  11.29 Kilobytes
20183    High Water Mark                    :  11.40 Kilobytes
20184
20185 .
20186 .
20187 .
20188 Allocation Root # 2
20189 -------------------
20190  Number of non freed allocations    :  11
20191  Final Water Mark (non freed mem)   :   1.16 Kilobytes
20192  High Water Mark                    :   1.27 Kilobytes
20193  Backtrace                          :
20194    my_program.adb:23 my_program.alloc
20195 .
20196 .
20197 .
20198 @end smallexample
20199
20200 The first block of output gives general information. In this case, the
20201 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
20202 Unchecked_Deallocation routine occurred.
20203
20204 @noindent
20205 Subsequent paragraphs display  information on all allocation roots.
20206 An allocation root is a specific point in the execution of the program
20207 that generates some dynamic allocation, such as a ``@code{@b{new}}''
20208 construct. This root is represented by an execution backtrace (or subprogram
20209 call stack). By default the backtrace depth for allocations roots is 1, so
20210 that a root corresponds exactly to a source location. The backtrace can
20211 be made deeper, to make the root more specific.
20212
20213 @node Switches for gnatmem
20214 @subsection Switches for @code{gnatmem}
20215
20216 @noindent
20217 @code{gnatmem} recognizes the following switches:
20218
20219 @table @option
20220
20221 @item -q
20222 @cindex @option{-q} (@code{gnatmem})
20223 Quiet. Gives the minimum output needed to identify the origin of the
20224 memory leaks. Omits statistical information.
20225
20226 @item @var{N}
20227 @cindex @var{N} (@code{gnatmem})
20228 N is an integer literal (usually between 1 and 10) which controls the
20229 depth of the backtraces defining allocation root. The default value for
20230 N is 1. The deeper the backtrace, the more precise the localization of
20231 the root. Note that the total number of roots can depend on this
20232 parameter. This parameter must be specified @emph{before} the name of the
20233 executable to be analyzed, to avoid ambiguity.
20234
20235 @item -b n
20236 @cindex @option{-b} (@code{gnatmem})
20237 This switch has the same effect as just depth parameter.
20238
20239 @item -i @var{file}
20240 @cindex @option{-i} (@code{gnatmem})
20241 Do the @code{gnatmem} processing starting from @file{file}, rather than
20242 @file{gmem.out} in the current directory.
20243
20244 @item -m n
20245 @cindex @option{-m} (@code{gnatmem})
20246 This switch causes @code{gnatmem} to mask the allocation roots that have less
20247 than n leaks. The default value is 1. Specifying the value of 0 will allow to
20248 examine even the roots that didn't result in leaks.
20249
20250 @item -s order
20251 @cindex @option{-s} (@code{gnatmem})
20252 This switch causes @code{gnatmem} to sort the allocation roots according to the
20253 specified order of sort criteria, each identified by a single letter. The
20254 currently supported criteria are @code{n, h, w} standing respectively for
20255 number of unfreed allocations, high watermark, and final watermark
20256 corresponding to a specific root. The default order is @code{nwh}.
20257
20258 @end table
20259
20260 @node Example of gnatmem Usage
20261 @subsection Example of @code{gnatmem} Usage
20262
20263 @noindent
20264 The following example shows the use of @code{gnatmem}
20265 on a simple memory-leaking program.
20266 Suppose that we have the following Ada program:
20267
20268 @smallexample @c ada
20269 @group
20270 @cartouche
20271 with Unchecked_Deallocation;
20272 procedure Test_Gm is
20273
20274    type T is array (1..1000) of Integer;
20275    type Ptr is access T;
20276    procedure Free is new Unchecked_Deallocation (T, Ptr);
20277    A : Ptr;
20278
20279    procedure My_Alloc is
20280    begin
20281       A := new T;
20282    end My_Alloc;
20283
20284    procedure My_DeAlloc is
20285       B : Ptr := A;
20286    begin
20287       Free (B);
20288    end My_DeAlloc;
20289
20290 begin
20291    My_Alloc;
20292    for I in 1 .. 5 loop
20293       for J in I .. 5 loop
20294          My_Alloc;
20295       end loop;
20296       My_Dealloc;
20297    end loop;
20298 end;
20299 @end cartouche
20300 @end group
20301 @end smallexample
20302
20303 @noindent
20304 The program needs to be compiled with debugging option and linked with
20305 @code{gmem} library:
20306
20307 @smallexample
20308 $ gnatmake -g test_gm -largs -lgmem
20309 @end smallexample
20310
20311 @noindent
20312 Then we execute the program as usual:
20313
20314 @smallexample
20315 $ test_gm
20316 @end smallexample
20317
20318 @noindent
20319 Then @code{gnatmem} is invoked simply with
20320 @smallexample
20321 $ gnatmem test_gm
20322 @end smallexample
20323
20324 @noindent
20325 which produces the following output (result may vary on different platforms):
20326
20327 @smallexample
20328 Global information
20329 ------------------
20330    Total number of allocations        :  18
20331    Total number of deallocations      :   5
20332    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20333    High Water Mark                    :  56.90 Kilobytes
20334
20335 Allocation Root # 1
20336 -------------------
20337  Number of non freed allocations    :  11
20338  Final Water Mark (non freed mem)   :  42.97 Kilobytes
20339  High Water Mark                    :  46.88 Kilobytes
20340  Backtrace                          :
20341    test_gm.adb:11 test_gm.my_alloc
20342
20343 Allocation Root # 2
20344 -------------------
20345  Number of non freed allocations    :   1
20346  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20347  High Water Mark                    :  10.02 Kilobytes
20348  Backtrace                          :
20349    s-secsta.adb:81 system.secondary_stack.ss_init
20350
20351 Allocation Root # 3
20352 -------------------
20353  Number of non freed allocations    :   1
20354  Final Water Mark (non freed mem)   :  12 Bytes
20355  High Water Mark                    :  12 Bytes
20356  Backtrace                          :
20357    s-secsta.adb:181 system.secondary_stack.ss_init
20358 @end smallexample
20359
20360 @noindent
20361 Note that the GNAT run time contains itself a certain number of
20362 allocations that have no  corresponding deallocation,
20363 as shown here for root #2 and root
20364 #3. This is a normal behavior when the number of non-freed allocations
20365 is one, it allocates dynamic data structures that the run time needs for
20366 the complete lifetime of the program. Note also that there is only one
20367 allocation root in the user program with a single line back trace:
20368 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
20369 program shows that 'My_Alloc' is called at 2 different points in the
20370 source (line 21 and line 24). If those two allocation roots need to be
20371 distinguished, the backtrace depth parameter can be used:
20372
20373 @smallexample
20374 $ gnatmem 3 test_gm
20375 @end smallexample
20376
20377 @noindent
20378 which will give the following output:
20379
20380 @smallexample
20381 Global information
20382 ------------------
20383    Total number of allocations        :  18
20384    Total number of deallocations      :   5
20385    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20386    High Water Mark                    :  56.90 Kilobytes
20387
20388 Allocation Root # 1
20389 -------------------
20390  Number of non freed allocations    :  10
20391  Final Water Mark (non freed mem)   :  39.06 Kilobytes
20392  High Water Mark                    :  42.97 Kilobytes
20393  Backtrace                          :
20394    test_gm.adb:11 test_gm.my_alloc
20395    test_gm.adb:24 test_gm
20396    b_test_gm.c:52 main
20397
20398 Allocation Root # 2
20399 -------------------
20400  Number of non freed allocations    :   1
20401  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20402  High Water Mark                    :  10.02 Kilobytes
20403  Backtrace                          :
20404    s-secsta.adb:81  system.secondary_stack.ss_init
20405    s-secsta.adb:283 <system__secondary_stack___elabb>
20406    b_test_gm.c:33   adainit
20407
20408 Allocation Root # 3
20409 -------------------
20410  Number of non freed allocations    :   1
20411  Final Water Mark (non freed mem)   :   3.91 Kilobytes
20412  High Water Mark                    :   3.91 Kilobytes
20413  Backtrace                          :
20414    test_gm.adb:11 test_gm.my_alloc
20415    test_gm.adb:21 test_gm
20416    b_test_gm.c:52 main
20417
20418 Allocation Root # 4
20419 -------------------
20420  Number of non freed allocations    :   1
20421  Final Water Mark (non freed mem)   :  12 Bytes
20422  High Water Mark                    :  12 Bytes
20423  Backtrace                          :
20424    s-secsta.adb:181 system.secondary_stack.ss_init
20425    s-secsta.adb:283 <system__secondary_stack___elabb>
20426    b_test_gm.c:33   adainit
20427 @end smallexample
20428
20429 @noindent
20430 The allocation root #1 of the first example has been split in 2 roots #1
20431 and #3 thanks to the more precise associated backtrace.
20432
20433 @end ifclear
20434
20435 @node Stack Related Facilities
20436 @chapter Stack Related Facilities
20437
20438 @noindent
20439 This chapter describes some useful tools associated with stack
20440 checking and analysis. In
20441 particular, it deals with dynamic and static stack usage measurements.
20442
20443 @menu
20444 * Stack Overflow Checking::
20445 * Static Stack Usage Analysis::
20446 * Dynamic Stack Usage Analysis::
20447 @end menu
20448
20449 @node Stack Overflow Checking
20450 @section Stack Overflow Checking
20451 @cindex Stack Overflow Checking
20452 @cindex -fstack-check
20453
20454 @noindent
20455 For most operating systems, @command{gcc} does not perform stack overflow
20456 checking by default. This means that if the main environment task or
20457 some other task exceeds the available stack space, then unpredictable
20458 behavior will occur. Most native systems offer some level of protection by
20459 adding a guard page at the end of each task stack. This mechanism is usually
20460 not enough for dealing properly with stack overflow situations because
20461 a large local variable could ``jump'' above the guard page.
20462 Furthermore, when the
20463 guard page is hit, there may not be any space left on the stack for executing
20464 the exception propagation code. Enabling stack checking avoids
20465 such situations.
20466
20467 To activate stack checking, compile all units with the gcc option
20468 @option{-fstack-check}. For example:
20469
20470 @smallexample
20471 gcc -c -fstack-check package1.adb
20472 @end smallexample
20473
20474 @noindent
20475 Units compiled with this option will generate extra instructions to check
20476 that any use of the stack (for procedure calls or for declaring local
20477 variables in declare blocks) does not exceed the available stack space.
20478 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20479
20480 For declared tasks, the stack size is controlled by the size
20481 given in an applicable @code{Storage_Size} pragma or by the value specified
20482 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20483 the default size as defined in the GNAT runtime otherwise.
20484
20485 For the environment task, the stack size depends on
20486 system defaults and is unknown to the compiler. Stack checking
20487 may still work correctly if a fixed
20488 size stack is allocated, but this cannot be guaranteed.
20489 @ifclear vms
20490 To ensure that a clean exception is signalled for stack
20491 overflow, set the environment variable
20492 @env{GNAT_STACK_LIMIT} to indicate the maximum
20493 stack area that can be used, as in:
20494 @cindex GNAT_STACK_LIMIT
20495
20496 @smallexample
20497 SET GNAT_STACK_LIMIT 1600
20498 @end smallexample
20499
20500 @noindent
20501 The limit is given in kilobytes, so the above declaration would
20502 set the stack limit of the environment task to 1.6 megabytes.
20503 Note that the only purpose of this usage is to limit the amount
20504 of stack used by the environment task. If it is necessary to
20505 increase the amount of stack for the environment task, then this
20506 is an operating systems issue, and must be addressed with the
20507 appropriate operating systems commands.
20508 @end ifclear
20509 @ifset vms
20510 To have a fixed size stack in the environment task, the stack must be put
20511 in the P0 address space and its size specified.  Use these switches to
20512 create a p0 image:
20513
20514 @smallexample
20515 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20516 @end smallexample
20517
20518 @noindent
20519 The quotes are required to keep case.  The number after @samp{STACK=} is the
20520 size of the environmental task stack in pagelets (512 bytes).  In this example
20521 the stack size is about 2 megabytes.
20522
20523 @noindent
20524 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20525 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
20526 more details about the @option{/p0image} qualifier and the @option{stack}
20527 option.
20528 @end ifset
20529
20530 @node Static Stack Usage Analysis
20531 @section Static Stack Usage Analysis
20532 @cindex Static Stack Usage Analysis
20533 @cindex -fstack-usage
20534
20535 @noindent
20536 A unit compiled with @option{-fstack-usage} will generate an extra file
20537 that specifies
20538 the maximum amount of stack used, on a per-function basis.
20539 The file has the same
20540 basename as the target object file with a @file{.su} extension.
20541 Each line of this file is made up of three fields:
20542
20543 @itemize
20544 @item
20545 The name of the function.
20546 @item
20547 A number of bytes.
20548 @item
20549 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20550 @end itemize
20551
20552 The second field corresponds to the size of the known part of the function
20553 frame.
20554
20555 The qualifier @code{static} means that the function frame size
20556 is purely static.
20557 It usually means that all local variables have a static size.
20558 In this case, the second field is a reliable measure of the function stack
20559 utilization.
20560
20561 The qualifier @code{dynamic} means that the function frame size is not static.
20562 It happens mainly when some local variables have a dynamic size. When this
20563 qualifier appears alone, the second field is not a reliable measure
20564 of the function stack analysis. When it is qualified with  @code{bounded}, it
20565 means that the second field is a reliable maximum of the function stack
20566 utilization.
20567
20568 @node Dynamic Stack Usage Analysis
20569 @section Dynamic Stack Usage Analysis
20570
20571 @noindent
20572 It is possible to measure the maximum amount of stack used by a task, by
20573 adding a switch to @command{gnatbind}, as:
20574
20575 @smallexample
20576 $ gnatbind -u0 file
20577 @end smallexample
20578
20579 @noindent
20580 With this option, at each task termination, its stack usage is  output on
20581 @file{stderr}.
20582 It is not always convenient to output the stack usage when the program
20583 is still running. Hence, it is possible to delay this output until program
20584 termination. for a given number of tasks specified as the argument of the
20585 @option{-u} option. For instance:
20586
20587 @smallexample
20588 $ gnatbind -u100 file
20589 @end smallexample
20590
20591 @noindent
20592 will buffer the stack usage information of the first 100 tasks to terminate and
20593 output this info at program termination. Results are displayed in four
20594 columns:
20595
20596 @noindent
20597 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
20598
20599 @noindent
20600 where:
20601
20602 @table @emph
20603 @item Index
20604 is a number associated with each task.
20605
20606 @item Task Name
20607 is the name of the task analyzed.
20608
20609 @item Stack Size
20610 is the maximum size for the stack.
20611
20612 @item Stack Usage
20613 is the measure done by the stack analyzer. In order to prevent overflow, the stack
20614 is not entirely analyzed, and it's not possible to know exactly how
20615 much has actually been used. The report thus contains the theoretical stack usage
20616 (Value) and the possible variation (Variation) around this value.
20617
20618 @end table
20619
20620 @noindent
20621 The environment task stack, e.g., the stack that contains the main unit, is
20622 only processed when the environment variable GNAT_STACK_LIMIT is set.
20623
20624
20625 @c *********************************
20626 @c *            GNATCHECK          *
20627 @c *********************************
20628 @node Verifying Properties Using gnatcheck
20629 @chapter Verifying Properties Using @command{gnatcheck}
20630 @findex gnatcheck
20631 @cindex @command{gnatcheck}
20632
20633 @noindent
20634 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20635 of Ada source files according to a given set of semantic rules.
20636 @cindex ASIS
20637
20638 In order to check compliance with a given rule, @command{gnatcheck} has to
20639 semantically analyze the Ada sources.
20640 Therefore, checks can only be performed on
20641 legal Ada units. Moreover, when a unit depends semantically upon units located
20642 outside the current directory, the source search path has to be provided when
20643 calling @command{gnatcheck}, either through a specified project file or
20644 through @command{gnatcheck} switches as described below.
20645
20646 A number of rules are predefined in @command{gnatcheck} and are described
20647 later in this chapter.
20648 You can also add new rules, by modifying the @command{gnatcheck} code and
20649 rebuilding the tool. In order to add a simple rule making some local checks,
20650 a small amount of straightforward ASIS-based programming is usually needed.
20651
20652 Project support for @command{gnatcheck} is provided by the GNAT
20653 driver (see @ref{The GNAT Driver and Project Files}).
20654
20655 Invoking @command{gnatcheck} on the command line has the form:
20656
20657 @smallexample
20658 $ gnatcheck @ovar{switches}  @{@var{filename}@}
20659       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20660       @r{[}-cargs @var{gcc_switches}@r{]} @r{[}-rules @var{rule_options}@r{]}
20661 @end smallexample
20662
20663 @noindent
20664 where
20665 @itemize @bullet
20666 @item
20667 @var{switches} specify the general tool options
20668
20669 @item
20670 Each @var{filename} is the name (including the extension) of a source
20671 file to process. ``Wildcards'' are allowed, and
20672 the file name may contain path information.
20673
20674 @item
20675 Each @var{arg_list_filename} is the name (including the extension) of a text
20676 file containing the names of the source files to process, separated by spaces
20677 or line breaks.
20678
20679 @item
20680 @var{gcc_switches} is a list of switches for
20681 @command{gcc}. They will be passed on to all compiler invocations made by
20682 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20683 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20684 and use the @option{-gnatec} switch to set the configuration file.
20685
20686 @item
20687 @var{rule_options} is a list of options for controlling a set of
20688 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20689 @end itemize
20690
20691 @noindent
20692 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be supplied.
20693
20694 @menu
20695 * Format of the Report File::
20696 * General gnatcheck Switches::
20697 * gnatcheck Rule Options::
20698 * Adding the Results of Compiler Checks to gnatcheck Output::
20699 * Project-Wide Checks::
20700 * Rule exemption::
20701 * Predefined Rules::
20702 @end menu
20703
20704 @node Format of the Report File
20705 @section Format of the Report File
20706 @cindex Report file (for @code{gnatcheck})
20707
20708 @noindent
20709 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20710 rule violations.
20711 It also creates a text file  that
20712 contains the complete report of the last gnatcheck run. By default this file is
20713 named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the current
20714 directory, @option{^-o^/OUTPUT^} option can be used to change the name and/or
20715 location of the report file. This report contains:
20716 @itemize @bullet
20717 @item date and time of @command{gnatcheck} run, the version of
20718 the tool that has generated this report and the full paarmeters
20719 of the  @command{gnatcheck} invocation;
20720 @item the list of enabled rules;
20721 @item the total number of detected violations;
20722 @item list of source files for that rule violations have been detected;
20723 @item list of source files with no violations detected;
20724 @end itemize
20725
20726 @node General gnatcheck Switches
20727 @section General @command{gnatcheck} Switches
20728
20729 @noindent
20730 The following switches control the general @command{gnatcheck} behavior
20731
20732 @table @option
20733 @c !sort!
20734 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20735 @item ^-a^/ALL^
20736 Process all units including those with read-only ALI files such as
20737 those from GNAT Run-Time library.
20738
20739 @ifclear vms
20740 @ignore
20741 @cindex @option{-d} (@command{gnatcheck})
20742 @item -d
20743 Debug mode
20744 @end ignore
20745
20746 @cindex @option{-dd} (@command{gnatcheck})
20747 @item -dd
20748 Progress indicator mode (for use in GPS)
20749 @end ifclear
20750
20751 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20752 @item ^-h^/HELP^
20753 List the predefined and user-defined rules. For more details see
20754 @ref{Predefined Rules}.
20755
20756 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20757 @item ^-l^/LOCS^
20758 Use full source locations references in the report file. For a construct from
20759 a generic instantiation a full source location is a chain from the location
20760 of this construct in the generic unit to the place where this unit is
20761 instantiated.
20762
20763 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
20764 @item ^-log^/LOG^
20765 Duplicate all the output sent to Stderr into a log file. The log file is
20766 named @var{gnatcheck.log} and is located in the current directory.
20767
20768 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20769 @item ^-m@i{nnn}^/DIAGNOSTIC_LIMIT=@i{nnn}^
20770 Maximum number of diagnoses to be sent to Stdout, @i{nnn} from o@dots{}1000,
20771 the default value is 500. Zero means that there is no limitation on
20772 the number of diagnostic messages to be printed into Stdout.
20773
20774 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20775 @item ^-q^/QUIET^
20776 Quiet mode. All the diagnoses about rule violations are placed in the
20777 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
20778
20779 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20780 @item ^-s^/SHORT^
20781 Short format of the report file (no version information, no list of applied
20782 rules, no list of checked sources is included)
20783
20784 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
20785 @item ^-s1^/COMPILER_STYLE^
20786 Include the compiler-style section in the report file
20787
20788 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
20789 @item ^-s2^/BY_RULES^
20790 Include the section containing diagnoses ordered by rules in the report file
20791
20792 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
20793 @item ^-s3^/BY_FILES_BY_RULES^
20794 Include the section containing diagnoses ordered by files and then by rules
20795 in the report file
20796
20797 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
20798 @item ^-t^/TIME^
20799 Print out execution time.
20800
20801 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20802 @item ^-v^/VERBOSE^
20803 Verbose mode; @command{gnatcheck} generates version information and then
20804 a trace of sources being processed.
20805
20806 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
20807 @item ^-o ^/OUTPUT=^@var{report_file}
20808 Set name of report file file to @var{report_file} .
20809
20810 @end table
20811
20812 @noindent
20813 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20814 @option{^-s2^/BY_RULES^} or
20815 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20816 then the  @command{gnatcheck} report file will only contain sections
20817 explicitly denoted by these options.
20818
20819 @node gnatcheck Rule Options
20820 @section @command{gnatcheck} Rule Options
20821
20822 @noindent
20823 The following options control the processing performed by
20824 @command{gnatcheck}.
20825
20826 @table @option
20827 @cindex @option{+ALL} (@command{gnatcheck})
20828 @item +ALL
20829 Turn all the rule checks ON.
20830
20831 @cindex @option{-ALL} (@command{gnatcheck})
20832 @item -ALL
20833 Turn all the rule checks OFF.
20834
20835 @cindex @option{+R} (@command{gnatcheck})
20836 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20837 Turn on the check for a specified rule with the specified parameter, if any.
20838 @var{rule_id} must be the identifier of one of the currently implemented rules
20839 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20840 are not case-sensitive. The @var{param} item must
20841 be a string representing a valid parameter(s) for the specified rule.
20842 If it contains any space characters then this string must be enclosed in
20843 quotation marks.
20844
20845 @cindex @option{-R} (@command{gnatcheck})
20846 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20847 Turn off the check for a specified rule with the specified parameter, if any.
20848
20849 @cindex @option{-from} (@command{gnatcheck})
20850 @item -from=@var{rule_option_filename}
20851 Read the rule options from the text file @var{rule_option_filename}, referred as
20852 ``rule file'' below.
20853
20854 @end table
20855
20856 @noindent
20857 The default behavior is that all the rule checks are disabled.
20858
20859 A rule file is a text file containing a set of rule options.
20860 @cindex Rule file (for @code{gnatcheck})
20861 The file may contain empty lines and Ada-style comments (comment
20862 lines and end-of-line comments). The rule file has free format; that is,
20863 you do not have to start a new rule option on a new line.
20864
20865 A rule file may contain other @option{-from=@var{rule_option_filename}}
20866 options, each such option being replaced with the content of the
20867 corresponding rule file during the rule files processing. In case a
20868 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20869 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20870 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20871 the processing of rule files is interrupted and a part of their content
20872 is ignored.
20873
20874
20875 @node Adding the Results of Compiler Checks to gnatcheck Output
20876 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20877
20878 @noindent
20879 The @command{gnatcheck} tool can include in the generated diagnostic messages
20880 and in
20881 the report file the results of the checks performed by the compiler. Though
20882 disabled by default, this effect may be obtained by using @option{+R} with
20883 the following rule identifiers and parameters:
20884
20885 @table @option
20886 @item Restrictions
20887 To record restrictions violations (that are performed by the compiler if the
20888 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20889 use the rule named
20890 @code{Restrictions} with the same parameters as pragma
20891 @code{Restrictions} or @code{Restriction_Warnings}.
20892
20893 @item Style_Checks
20894 To record compiler style checks(@pxref{Style Checking}), use the rule named
20895 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
20896 which enables all the standard style checks that corresponds to @option{-gnatyy}
20897 GNAT style check option, or a string that has exactly the same
20898 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
20899 @code{Style_Checks} (for further information about this pragma,
20900 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}). For example,
20901 @code{+RStyle_Checks:O} rule option activates and adds to @command{gnatcheck}
20902 output the compiler style check that corresponds to
20903 @code{-gnatyO} style check option.
20904
20905 @item Warnings
20906 To record compiler warnings (@pxref{Warning Message Control}), use the rule
20907 named @code{Warnings} with a parameter that is a valid
20908 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
20909 (for further information about this pragma, @pxref{Pragma Warnings,,,
20910 gnat_rm, GNAT Reference Manual}). Note, that in case of gnatcheck
20911 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20912 all the specific warnings, but not suppresses the warning mode,
20913 and 'e' parameter, corresponding to @option{-gnatwe} that means
20914 "treat warnings as errors", does not have any effect.
20915
20916 @end table
20917
20918 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20919 option with the corresponding restriction name as a parameter. @code{-R} is
20920 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20921 warnings and style checks, use the corresponding warning and style options.
20922
20923 @node Project-Wide Checks
20924 @section Project-Wide Checks
20925 @cindex Project-wide checks (for @command{gnatcheck})
20926
20927 @noindent
20928 In order to perform checks on all units of a given project, you can use
20929 the GNAT driver along with the @option{-P} option:
20930 @smallexample
20931    gnat check -Pproj -rules -from=my_rules
20932 @end smallexample
20933
20934 @noindent
20935 If the project @code{proj} depends upon other projects, you can perform
20936 checks on the project closure using the @option{-U} option:
20937 @smallexample
20938    gnat check -Pproj -U -rules -from=my_rules
20939 @end smallexample
20940
20941 @noindent
20942 Finally, if not all the units are relevant to a particular main
20943 program in the project closure, you can perform checks for the set
20944 of units needed to create a given main program (unit closure) using
20945 the @option{-U} option followed by the name of the main unit:
20946 @smallexample
20947    gnat check -Pproj -U main -rules -from=my_rules
20948 @end smallexample
20949
20950
20951 @node Rule exemption
20952 @section Rule exemption
20953 @cindex Rule exemption (for @command{gnatcheck})
20954
20955 @noindent
20956 One of the most useful applications of @command{gnatcheck} is to
20957 automate the enforcement of project-specific coding standards,
20958 for example in safety-critical systems where particular features
20959 must be restricted in order to simplify the certification effort.
20960 However, it may sometimes be appropriate to violate a coding standard rule,
20961 and in such cases the rationale for the violation should be provided
20962 in the source program itself so that the individuals
20963 reviewing or maintaining the program can immediately understand the intent.
20964
20965 The @command{gnatcheck} tool supports this practice with the notion of
20966 a ``rule exemption'' covering a specific source code section. Normally
20967 rule violation messages are issued both on @file{stderr}
20968 and in a report file. In contrast, exempted violations are not listed on
20969 @file{stderr}; thus users invoking @command{gnatcheck} interactively
20970 (e.g. in its GPS interface) do not need to pay attention to known and
20971 justified violations. However, exempted violations along with their
20972 justification are documented in a special section of the report file that
20973 @command{gnatcheck} generates.
20974
20975 @menu
20976 * Using pragma Annotate to Control Rule Exemption::
20977 * gnatcheck Annotations Rules::
20978 @end menu
20979
20980 @node Using pragma Annotate to Control Rule Exemption
20981 @subsection Using pragma @code{Annotate} to Control Rule Exemption
20982 @cindex Using pragma Annotate to control rule exemption
20983
20984 @noindent
20985 Rule exemption is controlled by pragma @code{Annotate} when its first
20986 argument is ``gnatcheck''. The syntax of @command{gnatcheck}'s
20987 exemption control annotations is as follows:
20988
20989 @smallexample @c ada
20990 @group
20991 pragma Annotate (gnatcheck, @i{exemption_control}, @i{Rule_Name}, [@i{justification}]);
20992
20993 @i{exemption_control} ::= "Exempt_On" | "Exempt_Off"
20994
20995 @i{Rule_Name}         ::= string_literal
20996
20997 @i{justification}     ::= string_literal
20998 @end group
20999 @end smallexample
21000
21001 @noindent
21002 When a @command{gnatcheck} annotatation has more then four arguments,
21003 @command{gnatcheck} issues a warning and ignores the additional arguments.
21004 If the additional arguments do not follow the syntax above,
21005 @command{gnatcheck} emits a warning and ignores the annotation.
21006
21007 The @i{@code{Rule_Name}} argument should be the name of some existing
21008 @command{gnatcheck} rule.
21009 Otherwise a warning message is generated and the pragma is
21010 ignored. If @code{Rule_Name} denotes a rule that is not activated by the given
21011 @command{gnatcheck} call, the pragma is ignored and no warning is issued.
21012
21013 A source code section where an exemption is active for a given rule is
21014 delimited by an @code{exempt_on} and @code{exempt_off} annotation pair:
21015
21016 @smallexample @c ada
21017 pragma Annotate (gnatcheck, "Exempt_On", Rule_Name, "justification");
21018 -- source code section
21019 pragma Annotate (gnatcheck, "Exempt_Off", Rule_Name);
21020 @end smallexample
21021
21022
21023 @node gnatcheck Annotations Rules
21024 @subsection @command{gnatcheck} Annotations Rules
21025 @cindex @command{gnatcheck} annotations rules
21026
21027 @itemize @bullet
21028
21029 @item
21030 An ``Exempt_Off'' annotation can only appear after a corresponding
21031 ``Exempt_On'' annotation.
21032
21033 @item
21034 Exempted source code sections are only based on the source location of the
21035 annotations. Any source construct between the two
21036 annotations is part of the exempted source code section.
21037
21038 @item
21039 Exempted source code sections for different rules are independent. They can
21040 be nested or intersect with one another without limitation.
21041 Creating nested or intersecting source code sections for the same rule is
21042 not allowed.
21043
21044 @item
21045 Malformed exempted source code sections are reported by a warning, and
21046 the corresponding rule exemptions are ignored.
21047
21048 @item
21049 When an exempted source code section does not contain at least one violation
21050 of the exempted rule, a warning is emitted on @file{stderr}.
21051
21052 @item
21053 If an ``Exempt_On'' annotation pragma does not have a matching
21054 ``Exempt_Off'' annotation pragma in the same compilation unit, then the
21055 exemption for the given rule is ignored and a warning is issued.
21056 @end itemize
21057
21058
21059 @node Predefined Rules
21060 @section Predefined Rules
21061 @cindex Predefined rules (for @command{gnatcheck})
21062
21063 @ignore
21064 @c (Jan 2007) Since the global rules are still under development and are not
21065 @c documented, there is no point in explaining the difference between
21066 @c global and local rules
21067 @noindent
21068 A rule in @command{gnatcheck} is either local or global.
21069 A @emph{local rule} is a rule that applies to a well-defined section
21070 of a program and that can be checked by analyzing only this section.
21071 A @emph{global rule} requires analysis of some global properties of the
21072 whole program (mostly related to the program call graph).
21073 As of @value{NOW}, the implementation of global rules should be
21074 considered to be at a preliminary stage. You can use the
21075 @option{+GLOBAL} option to enable all the global rules, and the
21076 @option{-GLOBAL} rule option to disable all the global rules.
21077
21078 All the global rules in the list below are
21079 so indicated by marking them ``GLOBAL''.
21080 This +GLOBAL and -GLOBAL options are not
21081 included in the list of gnatcheck options above, because at the moment they
21082 are considered as a temporary debug options.
21083
21084 @command{gnatcheck} performs rule checks for generic
21085 instances only for global rules.  This limitation may be relaxed in a later
21086 release.
21087 @end ignore
21088
21089 @noindent
21090 The following subsections document the rules implemented in
21091 @command{gnatcheck}.
21092 The subsection title is the same as the rule identifier, which may be
21093 used as a parameter of the @option{+R} or @option{-R} options.
21094
21095
21096 @menu
21097 * Abstract_Type_Declarations::
21098 * Anonymous_Arrays::
21099 * Anonymous_Subtypes::
21100 * Blocks::
21101 * Boolean_Relational_Operators::
21102 @ignore
21103 * Ceiling_Violations::
21104 @end ignore
21105 * Complex_Inlined_Subprograms::
21106 * Controlled_Type_Declarations::
21107 * Declarations_In_Blocks::
21108 * Deep_Inheritance_Hierarchies::
21109 * Deeply_Nested_Generics::
21110 * Deeply_Nested_Inlining::
21111 @ignore
21112 * Deeply_Nested_Local_Inlining::
21113 @end ignore
21114 * Default_Parameters::
21115 * Direct_Calls_To_Primitives::
21116 * Discriminated_Records::
21117 * Enumeration_Ranges_In_CASE_Statements::
21118 * Exceptions_As_Control_Flow::
21119 * Exits_From_Conditional_Loops::
21120 * EXIT_Statements_With_No_Loop_Name::
21121 * Expanded_Loop_Exit_Names::
21122 * Explicit_Full_Discrete_Ranges::
21123 * Float_Equality_Checks::
21124 * Forbidden_Attributes::
21125 * Forbidden_Pragmas::
21126 * Function_Style_Procedures::
21127 * Generics_In_Subprograms::
21128 * GOTO_Statements::
21129 * Implicit_IN_Mode_Parameters::
21130 * Implicit_SMALL_For_Fixed_Point_Types::
21131 * Improperly_Located_Instantiations::
21132 * Improper_Returns::
21133 * Library_Level_Subprograms::
21134 * Local_Packages::
21135 @ignore
21136 * Improperly_Called_Protected_Entries::
21137 @end ignore
21138 * Metrics::
21139 * Misnamed_Controlling_Parameters::
21140 * Misnamed_Identifiers::
21141 * Multiple_Entries_In_Protected_Definitions::
21142 * Name_Clashes::
21143 * Non_Qualified_Aggregates::
21144 * Non_Short_Circuit_Operators::
21145 * Non_SPARK_Attributes::
21146 * Non_Tagged_Derived_Types::
21147 * Non_Visible_Exceptions::
21148 * Numeric_Literals::
21149 * OTHERS_In_Aggregates::
21150 * OTHERS_In_CASE_Statements::
21151 * OTHERS_In_Exception_Handlers::
21152 * Outer_Loop_Exits::
21153 * Overloaded_Operators::
21154 * Overly_Nested_Control_Structures::
21155 * Parameters_Out_Of_Order::
21156 * Positional_Actuals_For_Defaulted_Generic_Parameters::
21157 * Positional_Actuals_For_Defaulted_Parameters::
21158 * Positional_Components::
21159 * Positional_Generic_Parameters::
21160 * Positional_Parameters::
21161 * Predefined_Numeric_Types::
21162 * Raising_External_Exceptions::
21163 * Raising_Predefined_Exceptions::
21164 * Separate_Numeric_Error_Handlers::
21165 @ignore
21166 * Recursion::
21167 * Side_Effect_Functions::
21168 @end ignore
21169 * Slices::
21170 * Too_Many_Parents::
21171 * Unassigned_OUT_Parameters::
21172 * Uncommented_BEGIN_In_Package_Bodies::
21173 * Unconditional_Exits::
21174 * Unconstrained_Array_Returns::
21175 * Universal_Ranges::
21176 * Unnamed_Blocks_And_Loops::
21177 @ignore
21178 * Unused_Subprograms::
21179 @end ignore
21180 * USE_PACKAGE_Clauses::
21181 * Visible_Components::
21182 * Volatile_Objects_Without_Address_Clauses::
21183 @end menu
21184
21185
21186 @node Abstract_Type_Declarations
21187 @subsection @code{Abstract_Type_Declarations}
21188 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
21189
21190 @noindent
21191 Flag all declarations of abstract types. For an abstract private
21192 type, both the private and full type declarations are flagged.
21193
21194 This rule has no parameters.
21195
21196
21197 @node Anonymous_Arrays
21198 @subsection @code{Anonymous_Arrays}
21199 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
21200
21201 @noindent
21202 Flag all anonymous array type definitions (by Ada semantics these can only
21203 occur in object declarations).
21204
21205 This rule has no parameters.
21206
21207 @node Anonymous_Subtypes
21208 @subsection @code{Anonymous_Subtypes}
21209 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
21210
21211 @noindent
21212 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
21213 any instance of a subtype indication with a constraint, other than one
21214 that occurs immediately within a subtype declaration. Any use of a range
21215 other than as a constraint used immediately within a subtype declaration
21216 is considered as an anonymous subtype.
21217
21218 An effect of this rule is that @code{for} loops such as the following are
21219 flagged (since @code{1..N} is formally a ``range''):
21220
21221 @smallexample @c ada
21222 for I in 1 .. N loop
21223    @dots{}
21224 end loop;
21225 @end smallexample
21226
21227 @noindent
21228 Declaring an explicit subtype solves the problem:
21229
21230 @smallexample @c ada
21231 subtype S is Integer range 1..N;
21232 @dots{}
21233 for I in S loop
21234    @dots{}
21235 end loop;
21236 @end smallexample
21237
21238 @noindent
21239 This rule has no parameters.
21240
21241 @node Blocks
21242 @subsection @code{Blocks}
21243 @cindex @code{Blocks} rule (for @command{gnatcheck})
21244
21245 @noindent
21246 Flag each block statement.
21247
21248 This rule has no parameters.
21249
21250 @node Boolean_Relational_Operators
21251 @subsection @code{Boolean_Relational_Operators}
21252 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
21253
21254 @noindent
21255 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
21256 ``>='', ``='' and ``/='') for the predefined Boolean type.
21257 (This rule is useful in enforcing the SPARK language restrictions.)
21258
21259 Calls to predefined relational operators of any type derived from
21260 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
21261 with these designators, and uses of operators that are renamings
21262 of the predefined relational operators for @code{Standard.Boolean},
21263 are likewise not detected.
21264
21265 This rule has no parameters.
21266
21267 @ignore
21268 @node Ceiling_Violations
21269 @subsection @code{Ceiling5_Violations} (under construction, GLOBAL)
21270 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
21271
21272 @noindent
21273 Flag invocations of a protected operation by a task whose priority exceeds
21274 the protected object's ceiling.
21275
21276 As of @value{NOW}, this rule has the following limitations:
21277
21278 @itemize @bullet
21279
21280 @item
21281  We consider only pragmas Priority and Interrupt_Priority as means to define
21282   a task/protected operation priority. We do not consider the effect of using
21283   Ada.Dynamic_Priorities.Set_Priority procedure;
21284
21285 @item
21286  We consider only base task priorities, and no priority inheritance. That is,
21287   we do not make a difference between calls issued during task activation and
21288   execution of the sequence of statements from task body;
21289
21290 @item
21291  Any situation when the priority of protected operation caller is set by a
21292   dynamic expression (that is, the corresponding Priority or
21293   Interrupt_Priority pragma has a non-static expression as an argument) we
21294   treat as a priority inconsistency (and, therefore, detect this situation).
21295 @end itemize
21296
21297 @noindent
21298 At the moment the notion of the main subprogram is not implemented in
21299 gnatcheck, so any pragma Priority in a library level subprogram body (in case
21300 if this subprogram can be a main subprogram of a partition) changes the
21301 priority of an environment task. So if we have more then one such pragma in
21302 the set of processed sources, the pragma that is processed last, defines the
21303 priority of an environment task.
21304
21305 This rule has no parameters.
21306 @end ignore
21307
21308 @node Controlled_Type_Declarations
21309 @subsection @code{Controlled_Type_Declarations}
21310 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
21311
21312 @noindent
21313 Flag all declarations of controlled types. A declaration of a private type
21314 is flagged if its full declaration declares a controlled type. A declaration
21315 of a derived type is flagged if its ancestor type is controlled. Subtype
21316 declarations are not checked. A declaration of a type that itself is not a
21317 descendant of a type declared in @code{Ada.Finalization} but has a controlled
21318 component is not checked.
21319
21320 This rule has no parameters.
21321
21322
21323 @node Complex_Inlined_Subprograms
21324 @subsection @code{Complex_Inlined_Subprograms}
21325 @cindex @code{Complex_Inlined_Subprograms} rule (for @command{gnatcheck})
21326
21327 @noindent
21328 Flags a subprogram (or generic subprogram) if
21329 pragma Inline is applied to the subprogram and at least one of the following
21330 conditions is met:
21331
21332 @itemize @bullet
21333 @item
21334 it contains at least one complex declaration such as a subprogram body,
21335 package, task, protected declaration, or a generic instantiation
21336 (except instantiation of @code{Ada.Unchecked_Conversion});
21337
21338 @item
21339 it contains at least one complex statement such as a loop, a case
21340 or a if statement, or a short circuit control form;
21341
21342 @item
21343 the number of statements exceeds
21344 a value specified by the @option{N} rule parameter;
21345 @end itemize
21346
21347 @noindent
21348 This rule has the following (mandatory) parameter for the @option{+R} option:
21349
21350 @table @emph
21351 @item N
21352 Positive integer specifying the maximum allowed total number of statements
21353 in the subprogram body.
21354 @end table
21355
21356
21357 @node Declarations_In_Blocks
21358 @subsection @code{Declarations_In_Blocks}
21359 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
21360
21361 @noindent
21362 Flag all block statements containing local declarations. A @code{declare}
21363 block with an empty @i{declarative_part} or with a @i{declarative part}
21364 containing only pragmas and/or @code{use} clauses is not flagged.
21365
21366 This rule has no parameters.
21367
21368
21369 @node Deep_Inheritance_Hierarchies
21370 @subsection @code{Deep_Inheritance_Hierarchies}
21371 @cindex @code{Deep_Inheritance_Hierarchies} rule (for @command{gnatcheck})
21372
21373 @noindent
21374 Flags a tagged derived type declaration or an interface type declaration if
21375 its depth (in its inheritance
21376 hierarchy) exceeds the value specified by the @option{N} rule parameter.
21377
21378 The inheritance depth of a tagged type or interface type is defined as 0 for
21379 a type  with no parent and no progenitor, and otherwise as 1 + max of the
21380 depths of the immediate parent and immediate progenitors.
21381
21382 This rule does not flag private extension
21383 declarations. In the case of a private extension, the correspondong full
21384 declaration is checked.
21385
21386 This rule has the following (mandatory) parameter for the @option{+R} option:
21387
21388 @table @emph
21389 @item N
21390 Integer not less then -1 specifying the maximal allowed depth of any inheritance
21391 hierarchy. If the rule parameter is set to -1, the rule flags all the declarations
21392 of tagged and interface types.
21393 @end table
21394
21395
21396 @node Deeply_Nested_Generics
21397 @subsection @code{Deeply_Nested_Generics}
21398 @cindex @code{Deeply_Nested_Generics} rule (for @command{gnatcheck})
21399
21400 @noindent
21401 Flags a generic declaration nested in another generic declaration if
21402 the nesting level of the inner generic exceeds
21403 a value specified by the @option{N} rule parameter.
21404 The nesting level is the number of generic declaratons that enclose the given
21405 (generic) declaration. Formal packages are not flagged by this rule.
21406
21407 This rule has the following (mandatory) parameters for the @option{+R} option:
21408
21409 @table @emph
21410 @item N
21411 Positive integer specifying the maximal allowed nesting level
21412 for a generic declaration.
21413 @end table
21414
21415 @node Deeply_Nested_Inlining
21416 @subsection @code{Deeply_Nested_Inlining}
21417 @cindex @code{Deeply_Nested_Inlining} rule (for @command{gnatcheck})
21418
21419 @noindent
21420 Flags a subprogram (or generic subprogram) if
21421 pragma Inline has been applied to the subprogram but the subprogram
21422 calls to another inlined subprogram that results in nested inlining
21423 with nesting depth exceeding the value specified by the
21424 @option{N} rule parameter.
21425
21426 This rule requires the global analysis of all the compilation units that
21427 are @command{gnatcheck} arguments; such analysis may affect the tool's
21428 performance.
21429
21430 This rule has the following (mandatory) parameter for the @option{+R} option:
21431
21432 @table @emph
21433 @item N
21434 Positive integer specifying the maximal allowed level of nested inlining.
21435 @end table
21436
21437
21438 @ignore
21439 @node Deeply_Nested_Local_Inlining
21440 @subsection @code{Deeply_Nested_Local_Inlining}
21441 @cindex @code{Deeply_Nested_Local_Inlining} rule (for @command{gnatcheck})
21442
21443 @noindent
21444 Flags a subprogram body if a pragma @code{Inline} is applied to the
21445 corresponding subprogram (or generic subprogram) and the body contains a call
21446 to another inlined subprogram that results in nested inlining with nesting
21447 depth more then a value specified by the @option{N} rule parameter.
21448 This rule is similar to @code{Deeply_Nested_Inlining} rule, but it
21449 assumes that calls to subprograms in
21450 with'ed units are not inlided, so all the analysis of the depth of inlining is
21451 limited by the compilation unit where the subprogram body is located and the
21452 units it depends semantically upon. Such analysis may be usefull for the case
21453 when neiter @option{-gnatn} nor @option{-gnatN} option is used when building
21454 the executable.
21455
21456 This rule has the following (mandatory) parameters for the @option{+R} option:
21457
21458 @table @emph
21459 @item N
21460 Positive integer specifying the maximal allowed level of nested inlining.
21461 @end table
21462
21463 @end ignore
21464
21465 @node Default_Parameters
21466 @subsection @code{Default_Parameters}
21467 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
21468
21469 @noindent
21470 Flag all default expressions for subprogram parameters. Parameter
21471 declarations of formal and generic subprograms are also checked.
21472
21473 This rule has no parameters.
21474
21475
21476 @node Direct_Calls_To_Primitives
21477 @subsection @code{Direct_Calls_To_Primitives}
21478 @cindex @code{Direct_Calls_To_Primitives} rule (for @command{gnatcheck})
21479
21480 @noindent
21481 Flags any non-dispatching call to a dispatching primitive operation, except
21482 for the common idiom where a primitive subprogram for a tagged type
21483 directly calls the same primitive subprogram of the type's immediate ancestor.
21484
21485 This rule has no parameters.
21486
21487
21488 @node Discriminated_Records
21489 @subsection @code{Discriminated_Records}
21490 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
21491
21492 @noindent
21493 Flag all declarations of record types with discriminants. Only the
21494 declarations of record and record extension types are checked. Incomplete,
21495 formal, private, derived and private extension type declarations are not
21496 checked. Task and protected type declarations also are not checked.
21497
21498 This rule has no parameters.
21499
21500
21501 @node Enumeration_Ranges_In_CASE_Statements
21502 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
21503 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
21504
21505 @noindent
21506 Flag each use of a range of enumeration literals as a choice in a
21507 @code{case} statement.
21508 All forms for specifying a range (explicit ranges
21509 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
21510 An enumeration range is
21511 flagged even if contains exactly one enumeration value or no values at all. A
21512 type derived from an enumeration type is considered as an enumeration type.
21513
21514 This rule helps prevent maintenance problems arising from adding an
21515 enumeration value to a type and having it implicitly handled by an existing
21516 @code{case} statement with an enumeration range that includes the new literal.
21517
21518 This rule has no parameters.
21519
21520
21521 @node Exceptions_As_Control_Flow
21522 @subsection @code{Exceptions_As_Control_Flow}
21523 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
21524
21525 @noindent
21526 Flag each place where an exception is explicitly raised and handled in the
21527 same subprogram body. A @code{raise} statement in an exception handler,
21528 package body, task body or entry body is not flagged.
21529
21530 The rule has no parameters.
21531
21532 @node Exits_From_Conditional_Loops
21533 @subsection @code{Exits_From_Conditional_Loops}
21534 @cindex @code{Exits_From_Conditional_Loops} (for @command{gnatcheck})
21535
21536 @noindent
21537 Flag any exit statement if it transfers the control out of a @code{for} loop
21538 or a @code{while} loop. This includes cases when the @code{exit} statement
21539 applies to a @code{FOR} or @code{while} loop, and cases when it is enclosed
21540 in some @code{for} or @code{while} loop, but transfers the control from some
21541 outer (inconditional) @code{loop} statement.
21542
21543 The rule has no parameters.
21544
21545
21546 @node EXIT_Statements_With_No_Loop_Name
21547 @subsection @code{EXIT_Statements_With_No_Loop_Name}
21548 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
21549
21550 @noindent
21551 Flag each @code{exit} statement that does not specify the name of the loop
21552 being exited.
21553
21554 The rule has no parameters.
21555
21556
21557 @node Expanded_Loop_Exit_Names
21558 @subsection @code{Expanded_Loop_Exit_Names}
21559 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
21560
21561 @noindent
21562 Flag all expanded loop names in @code{exit} statements.
21563
21564 This rule has no parameters.
21565
21566 @node Explicit_Full_Discrete_Ranges
21567 @subsection @code{Explicit_Full_Discrete_Ranges}
21568 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
21569
21570 @noindent
21571 Flag each discrete range that has the form @code{A'First .. A'Last}.
21572
21573 This rule has no parameters.
21574
21575 @node Float_Equality_Checks
21576 @subsection @code{Float_Equality_Checks}
21577 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
21578
21579 @noindent
21580 Flag all calls to the predefined equality operations for floating-point types.
21581 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
21582 User-defined equality operations are not flagged, nor are ``@code{=}''
21583 and ``@code{/=}'' operations for fixed-point types.
21584
21585 This rule has no parameters.
21586
21587
21588 @node Forbidden_Attributes
21589 @subsection @code{Forbidden_Attributes}
21590 @cindex @code{Forbidden_Attributes} rule (for @command{gnatcheck})
21591
21592 @noindent
21593 Flag each use of the specified attributes. The attributes to be detected are
21594 named in the rule's parameters.
21595
21596 This rule has the following parameters:
21597
21598 @itemize @bullet
21599 @item For the @option{+R} option
21600
21601 @table @asis
21602 @item @emph{Attribute_Designator}
21603 Adds the specified attribute to the set of attributes to be detected and sets
21604 the detection checks for all the specified attributes ON.
21605 If @emph{Attribute_Designator}
21606 does not denote any attribute defined in the Ada standard
21607 or in
21608 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
21609 Manual}, it is treated as the name of unknown attribute.
21610
21611 @item @code{GNAT}
21612 All the GNAT-specific attributes are detected; this sets
21613 the detection checks for all the specified attributes ON.
21614
21615 @item @code{ALL}
21616 All attributes are detected; this sets the rule ON.
21617 @end table
21618
21619 @item For the @option{-R} option
21620 @table @asis
21621 @item @emph{Attribute_Designator}
21622 Removes the specified attribute from the set of attributes to be
21623 detected without affecting detection checks for
21624 other attributes. If @emph{Attribute_Designator} does not correspond to any
21625 attribute defined in the Ada standard or in
21626 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference Manual},
21627 this option is treated as turning OFF detection of all unknown attributes.
21628
21629 @item GNAT
21630 Turn OFF detection of all GNAT-specific attributes
21631
21632 @item ALL
21633 Clear the list of the attributes to be detected and
21634 turn the rule OFF.
21635 @end table
21636 @end itemize
21637
21638 @noindent
21639 Parameters are not case sensitive. If @emph{Attribute_Designator} does not
21640 have the syntax of an Ada identifier and therefore can not be considered as a
21641 (part of an) attribute designator, a diagnostic message is generated and the
21642 corresponding parameter is ignored. (If an attribute allows a static
21643 expression to be a part of the attribute designator, this expression is
21644 ignored by this rule.)
21645
21646 When more then one parameter is given in the same rule option, the parameters
21647 must be separated by commas.
21648
21649 If more then one option for this rule is specified for the gnatcheck call, a
21650 new option overrides the previous one(s).
21651
21652 The @option{+R} option with no parameters turns the rule ON, with the set of
21653 attributes to be detected defined by the previous rule options.
21654 (By default this set is empty, so if the only option specified for the rule is
21655 @option{+RForbidden_Attributes} (with
21656 no parameter), then the rule is enabled, but it does not detect anything).
21657 The @option{-R} option with no parameter turns the rule OFF, but it does not
21658 affect the set of attributes to be detected.
21659
21660
21661 @node Forbidden_Pragmas
21662 @subsection @code{Forbidden_Pragmas}
21663 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
21664
21665 @noindent
21666 Flag each use of the specified pragmas.  The pragmas to be detected
21667 are named in the rule's  parameters.
21668
21669 This rule has the following parameters:
21670
21671 @itemize @bullet
21672 @item For the @option{+R} option
21673
21674 @table @asis
21675 @item @emph{Pragma_Name}
21676 Adds the specified pragma to the set of pragmas to be
21677 checked and sets the checks for all the specified pragmas
21678 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
21679 does not correspond to any pragma name defined in the Ada
21680 standard or to the name of a GNAT-specific pragma defined
21681 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21682 Manual}, it is treated as the name of unknown pragma.
21683
21684 @item @code{GNAT}
21685 All the GNAT-specific pragmas are detected; this sets
21686 the checks for all the specified pragmas ON.
21687
21688 @item @code{ALL}
21689 All pragmas are detected; this sets the rule ON.
21690 @end table
21691
21692 @item For the @option{-R} option
21693 @table @asis
21694 @item @emph{Pragma_Name}
21695 Removes the specified pragma from the set of pragmas to be
21696 checked without affecting checks for
21697 other pragmas. @emph{Pragma_Name} is treated as a name
21698 of a pragma. If it does not correspond to any pragma
21699 defined in the Ada standard or to any name defined in
21700 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21701 this option is treated as turning OFF detection of all unknown pragmas.
21702
21703 @item GNAT
21704 Turn OFF detection of all GNAT-specific pragmas
21705
21706 @item ALL
21707 Clear the list of the pragmas to be detected and
21708 turn the rule OFF.
21709 @end table
21710 @end itemize
21711
21712 @noindent
21713 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
21714 the syntax of an Ada identifier and therefore can not be considered
21715 as a pragma name, a diagnostic message is generated and the corresponding
21716 parameter is ignored.
21717
21718 When more then one parameter is given in the same rule option, the parameters
21719 must be separated by a comma.
21720
21721 If more then one option for this rule is specified for the @command{gnatcheck}
21722 call, a new option overrides the previous one(s).
21723
21724 The @option{+R} option with no parameters turns the rule ON with the set of
21725 pragmas to be detected defined by the previous rule options.
21726 (By default this set is empty, so if the only option specified for the rule is
21727 @option{+RForbidden_Pragmas} (with
21728 no parameter), then the rule is enabled, but it does not detect anything).
21729 The @option{-R} option with no parameter turns the rule OFF, but it does not
21730 affect the set of pragmas to be detected.
21731
21732
21733
21734
21735 @node Function_Style_Procedures
21736 @subsection @code{Function_Style_Procedures}
21737 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
21738
21739 @noindent
21740 Flag each procedure that can be rewritten as a function. A procedure can be
21741 converted into a function if it has exactly one parameter of mode @code{out}
21742 and no parameters of mode @code{in out}. Procedure declarations,
21743 formal procedure declarations, and generic procedure declarations are always
21744 checked. Procedure
21745 bodies and body stubs are flagged only if they do not have corresponding
21746 separate declarations. Procedure renamings and procedure instantiations are
21747 not flagged.
21748
21749 If a procedure can be rewritten as a function, but its @code{out} parameter is
21750 of a limited type, it is not flagged.
21751
21752 Protected procedures are not flagged. Null procedures also are not flagged.
21753
21754 This rule has no parameters.
21755
21756
21757 @node Generics_In_Subprograms
21758 @subsection @code{Generics_In_Subprograms}
21759 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21760
21761 @noindent
21762 Flag each declaration of a generic unit in a subprogram. Generic
21763 declarations in the bodies of generic subprograms are also flagged.
21764 A generic unit nested in another generic unit is not flagged.
21765 If a generic unit is
21766 declared in a local package that is declared in a subprogram body, the
21767 generic unit is flagged.
21768
21769 This rule has no parameters.
21770
21771
21772 @node GOTO_Statements
21773 @subsection @code{GOTO_Statements}
21774 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21775
21776 @noindent
21777 Flag each occurrence of a @code{goto} statement.
21778
21779 This rule has no parameters.
21780
21781
21782 @node Implicit_IN_Mode_Parameters
21783 @subsection @code{Implicit_IN_Mode_Parameters}
21784 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21785
21786 @noindent
21787 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21788 Note that @code{access} parameters, although they technically behave
21789 like @code{in} parameters, are not flagged.
21790
21791 This rule has no parameters.
21792
21793
21794 @node Implicit_SMALL_For_Fixed_Point_Types
21795 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21796 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21797
21798 @noindent
21799 Flag each fixed point type declaration that lacks an explicit
21800 representation  clause to define its @code{'Small} value.
21801 Since @code{'Small} can be  defined only for ordinary fixed point types,
21802 decimal fixed point type declarations are not checked.
21803
21804 This rule has no parameters.
21805
21806
21807 @node Improperly_Located_Instantiations
21808 @subsection @code{Improperly_Located_Instantiations}
21809 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21810
21811 @noindent
21812 Flag all generic instantiations in library-level package specs
21813 (including library generic packages) and in all subprogram bodies.
21814
21815 Instantiations in task and entry bodies are not flagged. Instantiations in the
21816 bodies of protected subprograms are flagged.
21817
21818 This rule has no parameters.
21819
21820
21821
21822 @node Improper_Returns
21823 @subsection @code{Improper_Returns}
21824 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21825
21826 @noindent
21827 Flag each explicit @code{return} statement in procedures, and
21828 multiple @code{return} statements in functions.
21829 Diagnostic messages are generated for all @code{return} statements
21830 in a procedure (thus each procedure must be written so that it
21831 returns implicitly at the end of its statement part),
21832 and for all @code{return} statements in a function after the first one.
21833 This rule supports the stylistic convention that each subprogram
21834 should have no more than one point of normal return.
21835
21836 This rule has no parameters.
21837
21838
21839 @node Library_Level_Subprograms
21840 @subsection @code{Library_Level_Subprograms}
21841 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21842
21843 @noindent
21844 Flag all library-level subprograms (including generic subprogram instantiations).
21845
21846 This rule has no parameters.
21847
21848
21849 @node Local_Packages
21850 @subsection @code{Local_Packages}
21851 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21852
21853 @noindent
21854 Flag all local packages declared in package and generic package
21855 specs.
21856 Local packages in bodies are not flagged.
21857
21858 This rule has no parameters.
21859
21860 @ignore
21861 @node Improperly_Called_Protected_Entries
21862 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21863 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21864
21865 @noindent
21866 Flag each protected entry that can be called from more than one task.
21867
21868 This rule has no parameters.
21869 @end ignore
21870
21871 @node Metrics
21872 @subsection @code{Metrics}
21873 @cindex @code{Metrics} rule (for @command{gnatcheck})
21874
21875 @noindent
21876 There is a set of checks based on computing a metric value and comparing the
21877 result with the specified upper (or lower, depending on a specific metric)
21878 value specified for a given metric. A construct is flagged if a given metric
21879 is applicable (can be computed) for it and the computed value is greater
21880 then (lover then) the specified upper (lower) bound.
21881
21882 The name of any metric-based rule consists of the prefix @code{Metrics_}
21883 followed by the name of the corresponding metric (see the table below).
21884 For @option{+R} option, each metric-based rule has a numeric parameter
21885 specifying the bound (integer or real, depending on a metric), @option{-R}
21886 option for metric rules does not have a parameter.
21887
21888 The following table shows the metric names for that the corresponding
21889 metrics-based checks are supported by gnatcheck, including the
21890 constraint that must be satisfied by the bound that is specified for the check
21891 and what bound - upper (U) or lower (L) - should be specified.
21892
21893 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21894 @ifnothtml
21895 @headitem Check Name @tab Description @tab Bounds Value
21896 @end ifnothtml
21897 @ifhtml
21898 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21899 @end ifhtml
21900 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21901 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21902 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21903 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21904 @end multitable
21905
21906 @noindent
21907 The meaning and the computed values for all these metrics are exactly
21908 the same as for the corresponding metrics in @command{gnatmetric}.
21909
21910 @emph{Example:} the rule
21911 @smallexample
21912 +RMetrics_Cyclomatic_Complexity : 7
21913 @end smallexample
21914 @noindent
21915 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21916
21917 To turn OFF the check for cyclomatic complexity metric, use the following option:
21918 @smallexample
21919 -RMetrics_Cyclomatic_Complexity
21920 @end smallexample
21921
21922
21923 @node Misnamed_Controlling_Parameters
21924 @subsection @code{Misnamed_Controlling_Parameters}
21925 @cindex @code{Misnamed_Controlling_Parameters} rule (for @command{gnatcheck})
21926
21927 @noindent
21928 Flags a declaration of a dispatching operation, if the first parameter is
21929 not a controlling one and its name is not @code{This} (the check for
21930 parameter name is not case-sensitive). Declarations of dispatching functions
21931 with controlling result and no controlling parameter are never flagged.
21932
21933 A subprogram body declaration, subprogram renaming declaration or subprogram
21934 body stub is flagged only if it is not a completion of a prior subprogram
21935 declaration.
21936
21937 This rule has no parameters.
21938
21939
21940
21941 @node Misnamed_Identifiers
21942 @subsection @code{Misnamed_Identifiers}
21943 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21944
21945 @noindent
21946 Flag the declaration of each identifier that does not have a suffix
21947 corresponding to the kind of entity being declared.
21948 The following declarations are checked:
21949
21950 @itemize @bullet
21951 @item
21952 type declarations
21953
21954 @item
21955 subtype declarations
21956
21957 @item
21958 constant declarations (but not number declarations)
21959
21960 @item
21961 package renaming declarations (but not generic package renaming
21962 declarations)
21963 @end itemize
21964
21965 @noindent
21966 This rule may have parameters. When used without parameters, the rule enforces
21967 the following checks:
21968
21969 @itemize @bullet
21970 @item
21971 type-defining names end with @code{_T}, unless the type is an access type,
21972 in which case the suffix must be @code{_A}
21973 @item
21974 constant names end with @code{_C}
21975 @item
21976 names defining package renamings end with @code{_R}
21977 @end itemize
21978
21979 @noindent
21980 Defining identifiers from incomplete type declarations are never flagged.
21981
21982 For a private type declaration (including private extensions), the defining
21983 identifier from the private type declaration is checked against the type
21984 suffix (even if the corresponding full declaration is an access type
21985 declaration), and the defining identifier from the corresponding full type
21986 declaration is not checked.
21987
21988 @noindent
21989 For a deferred constant, the defining name in the corresponding full constant
21990 declaration is not checked.
21991
21992 Defining names of formal types are not checked.
21993
21994 The rule may have the following parameters:
21995
21996 @itemize @bullet
21997 @item
21998 For the @option{+R} option:
21999 @table @code
22000 @item Default
22001 Sets the default listed above for all the names to be checked.
22002
22003 @item Type_Suffix=@emph{string}
22004 Specifies the suffix for a type name.
22005
22006 @item Access_Suffix=@emph{string}
22007 Specifies the suffix for an access type name. If
22008 this parameter is set, it overrides for access
22009 types the suffix set by the @code{Type_Suffix} parameter.
22010 For access types, @emph{string} may have the following format:
22011 @emph{suffix1(suffix2)}. That means that an access type name
22012 should have the @emph{suffix1} suffix except for the case when
22013 the designated type is also an access type, in this case the
22014 type name should have the @emph{suffix1 & suffix2} suffix.
22015
22016 @item Class_Access_Suffix=@emph{string}
22017 Specifies the suffix for the name of an access type that points to some class-wide
22018 type. If this parameter is set, it overrides for such access
22019 types the suffix set by the @code{Type_Suffix} or @code{Access_Suffix}
22020 parameter.
22021
22022 @item Class_Subtype_Suffix=@emph{string}
22023 Specifies the suffix for the name of a subtype that denotes a class-wide type.
22024
22025 @item Constant_Suffix=@emph{string}
22026 Specifies the suffix for a constant name.
22027
22028 @item Renaming_Suffix=@emph{string}
22029 Specifies the suffix for a package renaming name.
22030 @end table
22031
22032 @item
22033 For the @option{-R} option:
22034 @table @code
22035 @item All_Suffixes
22036 Remove all the suffixes specified for the
22037 identifier suffix checks, whether by default or
22038 as specified by other rule parameters. All the
22039 checks for this rule are disabled as a result.
22040
22041 @item Type_Suffix
22042 Removes the suffix specified for types. This
22043 disables checks for types but does not disable
22044 any other checks for this rule (including the
22045 check for access type names if @code{Access_Suffix} is
22046 set).
22047
22048 @item Access_Suffix
22049 Removes the suffix specified for access types.
22050 This disables checks for access type names but
22051 does not disable any other checks for this rule.
22052 If @code{Type_Suffix} is set, access type names are
22053 checked as ordinary type names.
22054
22055 @item Class_Access_Suffix
22056 Removes the suffix specified for access types pointing to class-wide
22057 type. This disables specific checks for names of access types pointing to
22058 class-wide types but does not disable any other checks for this rule.
22059 If @code{Type_Suffix} is set, access type names are
22060 checked as ordinary type names. If @code{Access_Suffix} is set, these
22061 access types are checked as any other access type name.
22062
22063 @item Class_Subtype_Suffix=@emph{string}
22064 Removes the suffix specified for subtype names.
22065 This disables checks for subtype names but
22066 does not disable any other checks for this rule.
22067
22068 @item Constant_Suffix
22069 Removes the suffix specified for constants. This
22070 disables checks for constant names but does not
22071 disable any other checks for this rule.
22072
22073 @item Renaming_Suffix
22074 Removes the suffix specified for package
22075 renamings. This disables checks for package
22076 renamings but does not disable any other checks
22077 for this rule.
22078 @end table
22079 @end itemize
22080
22081 @noindent
22082 If more than one parameter is used, parameters must be separated by commas.
22083
22084 If more than one  option is specified for the @command{gnatcheck} invocation,
22085 a new option overrides the previous one(s).
22086
22087 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
22088 checks for all the
22089 name suffixes specified by previous options used for this rule.
22090
22091 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
22092 all the checks but keeps
22093 all the suffixes specified by previous options used for this rule.
22094
22095 The @emph{string} value must be a valid suffix for an Ada identifier (after
22096 trimming all the leading and trailing space characters, if any).
22097 Parameters are not case sensitive, except the @emph{string} part.
22098
22099 If any error is detected in a rule parameter, the parameter is ignored.
22100 In such a case the options that are set for the rule are not
22101 specified.
22102
22103
22104
22105 @node Multiple_Entries_In_Protected_Definitions
22106 @subsection @code{Multiple_Entries_In_Protected_Definitions}
22107 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
22108
22109 @noindent
22110 Flag each protected definition (i.e., each protected object/type declaration)
22111 that defines more than one entry.
22112 Diagnostic messages are generated for all the entry declarations
22113 except the first one. An entry family is counted as one entry. Entries from
22114 the private part of the protected definition are also checked.
22115
22116 This rule has no parameters.
22117
22118 @node Name_Clashes
22119 @subsection @code{Name_Clashes}
22120 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
22121
22122 @noindent
22123 Check that certain names are not used as defining identifiers. To activate
22124 this rule, you need to supply a reference to the dictionary file(s) as a rule
22125 parameter(s) (more then one dictionary file can be specified). If no
22126 dictionary file is set, this rule will not cause anything to be flagged.
22127 Only defining occurrences, not references, are checked.
22128 The check is not case-sensitive.
22129
22130 This rule is enabled by default, but without setting any corresponding
22131 dictionary file(s); thus the default effect is to do no checks.
22132
22133 A dictionary file is a plain text file. The maximum line length for this file
22134 is 1024 characters.  If the line is longer then this limit, extra characters
22135 are ignored.
22136
22137 Each line can be either an empty line, a comment line, or a line containing
22138 a list of identifiers separated by space or HT characters.
22139 A comment is an Ada-style comment (from @code{--} to end-of-line).
22140 Identifiers must follow the Ada syntax for identifiers.
22141 A line containing one or more identifiers may end with a comment.
22142
22143 @node Non_Qualified_Aggregates
22144 @subsection @code{Non_Qualified_Aggregates}
22145 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
22146
22147 @noindent
22148 Flag each non-qualified aggregate.
22149 A non-qualified aggregate is an
22150 aggregate that is not the expression of a qualified expression. A
22151 string literal is not considered an aggregate, but an array
22152 aggregate of a string type is considered as a normal aggregate.
22153 Aggregates of anonymous array types are not flagged.
22154
22155 This rule has no parameters.
22156
22157
22158 @node Non_Short_Circuit_Operators
22159 @subsection @code{Non_Short_Circuit_Operators}
22160 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
22161
22162 @noindent
22163 Flag all calls to predefined @code{and} and @code{or} operators for
22164 any boolean type. Calls to
22165 user-defined @code{and} and @code{or} and to operators defined by renaming
22166 declarations are not flagged. Calls to predefined @code{and} and @code{or}
22167 operators for modular types or boolean array types are not flagged.
22168
22169 This rule has no parameters.
22170
22171
22172
22173 @node Non_SPARK_Attributes
22174 @subsection @code{Non_SPARK_Attributes}
22175 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
22176
22177 @noindent
22178 The SPARK language defines the following subset of Ada 95 attribute
22179 designators as those that can be used in SPARK programs. The use of
22180 any other attribute is flagged.
22181
22182 @itemize @bullet
22183 @item @code{'Adjacent}
22184 @item @code{'Aft}
22185 @item @code{'Base}
22186 @item @code{'Ceiling}
22187 @item @code{'Component_Size}
22188 @item @code{'Compose}
22189 @item @code{'Copy_Sign}
22190 @item @code{'Delta}
22191 @item @code{'Denorm}
22192 @item @code{'Digits}
22193 @item @code{'Exponent}
22194 @item @code{'First}
22195 @item @code{'Floor}
22196 @item @code{'Fore}
22197 @item @code{'Fraction}
22198 @item @code{'Last}
22199 @item @code{'Leading_Part}
22200 @item @code{'Length}
22201 @item @code{'Machine}
22202 @item @code{'Machine_Emax}
22203 @item @code{'Machine_Emin}
22204 @item @code{'Machine_Mantissa}
22205 @item @code{'Machine_Overflows}
22206 @item @code{'Machine_Radix}
22207 @item @code{'Machine_Rounds}
22208 @item @code{'Max}
22209 @item @code{'Min}
22210 @item @code{'Model}
22211 @item @code{'Model_Emin}
22212 @item @code{'Model_Epsilon}
22213 @item @code{'Model_Mantissa}
22214 @item @code{'Model_Small}
22215 @item @code{'Modulus}
22216 @item @code{'Pos}
22217 @item @code{'Pred}
22218 @item @code{'Range}
22219 @item @code{'Remainder}
22220 @item @code{'Rounding}
22221 @item @code{'Safe_First}
22222 @item @code{'Safe_Last}
22223 @item @code{'Scaling}
22224 @item @code{'Signed_Zeros}
22225 @item @code{'Size}
22226 @item @code{'Small}
22227 @item @code{'Succ}
22228 @item @code{'Truncation}
22229 @item @code{'Unbiased_Rounding}
22230 @item @code{'Val}
22231 @item @code{'Valid}
22232 @end itemize
22233
22234 @noindent
22235 This rule has no parameters.
22236
22237
22238 @node Non_Tagged_Derived_Types
22239 @subsection @code{Non_Tagged_Derived_Types}
22240 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
22241
22242 @noindent
22243 Flag all derived type declarations that do not have a record extension part.
22244
22245 This rule has no parameters.
22246
22247
22248
22249 @node Non_Visible_Exceptions
22250 @subsection @code{Non_Visible_Exceptions}
22251 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
22252
22253 @noindent
22254 Flag constructs leading to the possibility of propagating an exception
22255 out of the scope in which the exception is declared.
22256 Two cases are detected:
22257
22258 @itemize @bullet
22259 @item
22260 An exception declaration in a subprogram body, task body or block
22261 statement is flagged if the body or statement does not contain a handler for
22262 that exception or a handler with an @code{others} choice.
22263
22264 @item
22265 A @code{raise} statement in an exception handler of a subprogram body,
22266 task body or block statement is flagged if it (re)raises a locally
22267 declared exception.  This may occur under the following circumstances:
22268 @itemize @minus
22269 @item
22270 it explicitly raises a locally declared exception, or
22271 @item
22272 it does not specify an exception name (i.e., it is simply @code{raise;})
22273 and the enclosing handler contains a locally declared exception in its
22274 exception choices.
22275 @end itemize
22276 @end itemize
22277
22278 @noindent
22279 Renamings of local exceptions are not flagged.
22280
22281 This rule has no parameters.
22282
22283
22284 @node Numeric_Literals
22285 @subsection @code{Numeric_Literals}
22286 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
22287
22288 @noindent
22289 Flag each use of a numeric literal in an index expression, and in any
22290 circumstance except for the following:
22291
22292 @itemize @bullet
22293 @item
22294 a literal occurring in the initialization expression for a constant
22295 declaration or a named number declaration, or
22296
22297 @item
22298 an integer literal that is less than or equal to a value
22299 specified by the @option{N} rule parameter.
22300 @end itemize
22301
22302 @noindent
22303 This rule may have the following parameters for the @option{+R} option:
22304
22305 @table @asis
22306 @item @emph{N}
22307 @emph{N} is an integer literal used as the maximal value that is not flagged
22308 (i.e., integer literals not exceeding this value are allowed)
22309
22310 @item @code{ALL}
22311 All integer literals are flagged
22312 @end table
22313
22314 @noindent
22315 If no parameters are set, the maximum unflagged value is 1.
22316
22317 The last specified check limit (or the fact that there is no limit at
22318 all) is used when multiple @option{+R} options appear.
22319
22320 The @option{-R} option for this rule has no parameters.
22321 It disables the rule but retains the last specified maximum unflagged value.
22322 If the @option{+R} option subsequently appears, this value is used as the
22323 threshold for the check.
22324
22325
22326 @node OTHERS_In_Aggregates
22327 @subsection @code{OTHERS_In_Aggregates}
22328 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
22329
22330 @noindent
22331 Flag each use of an @code{others} choice in extension aggregates.
22332 In record and array aggregates, an @code{others} choice is flagged unless
22333 it is used to refer to all components, or to all but one component.
22334
22335 If, in case of a named array aggregate, there are two associations, one
22336 with an @code{others} choice and another with a discrete range, the
22337 @code{others} choice is flagged even if the discrete range specifies
22338 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
22339
22340 This rule has no parameters.
22341
22342 @node OTHERS_In_CASE_Statements
22343 @subsection @code{OTHERS_In_CASE_Statements}
22344 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
22345
22346 @noindent
22347 Flag any use of an @code{others} choice in a @code{case} statement.
22348
22349 This rule has no parameters.
22350
22351 @node OTHERS_In_Exception_Handlers
22352 @subsection @code{OTHERS_In_Exception_Handlers}
22353 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
22354
22355 @noindent
22356 Flag any use of an @code{others} choice in an exception handler.
22357
22358 This rule has no parameters.
22359
22360
22361 @node Outer_Loop_Exits
22362 @subsection @code{Outer_Loop_Exits}
22363 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
22364
22365 @noindent
22366 Flag each @code{exit} statement containing a loop name that is not the name
22367 of the immediately enclosing @code{loop} statement.
22368
22369 This rule has no parameters.
22370
22371
22372 @node Overloaded_Operators
22373 @subsection @code{Overloaded_Operators}
22374 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
22375
22376 @noindent
22377 Flag each function declaration that overloads an operator symbol.
22378 A function body is checked only if the body does not have a
22379 separate spec. Formal functions are also checked. For a
22380 renaming declaration, only renaming-as-declaration is checked
22381
22382 This rule has no parameters.
22383
22384
22385 @node Overly_Nested_Control_Structures
22386 @subsection @code{Overly_Nested_Control_Structures}
22387 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
22388
22389 @noindent
22390 Flag each control structure whose nesting level exceeds the value provided
22391 in the rule parameter.
22392
22393 The control structures checked are the following:
22394
22395 @itemize @bullet
22396 @item    @code{if} statement
22397 @item    @code{case} statement
22398 @item    @code{loop} statement
22399 @item    Selective accept statement
22400 @item    Timed entry call statement
22401 @item    Conditional entry call
22402 @item    Asynchronous select statement
22403 @end itemize
22404
22405 @noindent
22406 The rule has the following parameter for the @option{+R} option:
22407
22408 @table @emph
22409 @item N
22410 Positive integer specifying the maximal control structure nesting
22411 level that is not flagged
22412 @end table
22413
22414 @noindent
22415 If the parameter for the @option{+R} option is not specified or
22416 if it is not a positive integer, @option{+R} option is ignored.
22417
22418 If more then one  option is specified for the gnatcheck call, the later option and
22419 new parameter override the previous one(s).
22420
22421
22422 @node Parameters_Out_Of_Order
22423 @subsection @code{Parameters_Out_Of_Order}
22424 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
22425
22426 @noindent
22427 Flag each subprogram and entry declaration whose formal parameters are not
22428 ordered according to the following scheme:
22429
22430 @itemize @bullet
22431
22432 @item @code{in} and @code{access} parameters first,
22433 then @code{in out} parameters,
22434 and then @code{out} parameters;
22435
22436 @item for @code{in} mode, parameters with default initialization expressions
22437 occur last
22438 @end itemize
22439
22440 @noindent
22441 Only the first violation of the described order is flagged.
22442
22443 The following constructs are checked:
22444
22445 @itemize @bullet
22446 @item   subprogram declarations (including null procedures);
22447 @item   generic subprogram declarations;
22448 @item   formal subprogram declarations;
22449 @item   entry declarations;
22450 @item   subprogram bodies and subprogram body stubs that do not
22451 have separate specifications
22452 @end itemize
22453
22454 @noindent
22455 Subprogram renamings are not checked.
22456
22457 This rule has no parameters.
22458
22459
22460 @node Positional_Actuals_For_Defaulted_Generic_Parameters
22461 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
22462 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
22463
22464 @noindent
22465 Flag each generic actual parameter corresponding to a generic formal
22466 parameter with a default initialization, if positional notation is used.
22467
22468 This rule has no parameters.
22469
22470 @node Positional_Actuals_For_Defaulted_Parameters
22471 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
22472 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
22473
22474 @noindent
22475 Flag each actual parameter to a subprogram or entry call where the
22476 corresponding formal parameter has a default expression, if positional
22477 notation is used.
22478
22479 This rule has no parameters.
22480
22481 @node Positional_Components
22482 @subsection @code{Positional_Components}
22483 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
22484
22485 @noindent
22486 Flag each array, record and extension aggregate that includes positional
22487 notation.
22488
22489 This rule has no parameters.
22490
22491
22492 @node Positional_Generic_Parameters
22493 @subsection @code{Positional_Generic_Parameters}
22494 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
22495
22496 @noindent
22497 Flag each instantiation using positional parameter notation.
22498
22499 This rule has no parameters.
22500
22501
22502 @node Positional_Parameters
22503 @subsection @code{Positional_Parameters}
22504 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
22505
22506 @noindent
22507 Flag each subprogram or entry call using positional parameter notation,
22508 except for the following:
22509
22510 @itemize @bullet
22511 @item
22512 Invocations of prefix or infix operators are not flagged
22513 @item
22514 If the called subprogram or entry has only one formal parameter,
22515 the call is not flagged;
22516 @item
22517 If a subprogram call uses the @emph{Object.Operation} notation, then
22518 @itemize @minus
22519 @item
22520 the first parameter (that is, @emph{Object}) is not flagged;
22521 @item
22522 if the called subprogram has only two parameters, the second parameter
22523 of the call is not flagged;
22524 @end itemize
22525 @end itemize
22526
22527 @noindent
22528 This rule has no parameters.
22529
22530
22531
22532
22533 @node Predefined_Numeric_Types
22534 @subsection @code{Predefined_Numeric_Types}
22535 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
22536
22537 @noindent
22538 Flag each explicit use of the name of any numeric type or subtype defined
22539 in package @code{Standard}.
22540
22541 The rationale for this rule is to detect when the
22542 program may depend on platform-specific characteristics of the implementation
22543 of the predefined numeric types. Note that this rule is over-pessimistic;
22544 for example, a program that uses @code{String} indexing
22545 likely needs a variable of type @code{Integer}.
22546 Another example is the flagging of predefined numeric types with explicit
22547 constraints:
22548
22549 @smallexample @c ada
22550     subtype My_Integer is Integer range Left .. Right;
22551     Vy_Var : My_Integer;
22552 @end smallexample
22553
22554 @noindent
22555 This rule detects only numeric types and subtypes defined in
22556 @code{Standard}. The use of numeric types and subtypes defined in other
22557 predefined packages (such as @code{System.Any_Priority} or
22558 @code{Ada.Text_IO.Count}) is not flagged
22559
22560 This rule has no parameters.
22561
22562
22563
22564 @node Raising_External_Exceptions
22565 @subsection @code{Raising_External_Exceptions}
22566 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
22567
22568 @noindent
22569 Flag any @code{raise} statement, in a program unit declared in a library
22570 package or in a generic library package, for an exception that is
22571 neither a predefined exception nor an exception that is also declared (or
22572 renamed) in the visible part of the package.
22573
22574 This rule has no parameters.
22575
22576
22577
22578 @node Raising_Predefined_Exceptions
22579 @subsection @code{Raising_Predefined_Exceptions}
22580 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
22581
22582 @noindent
22583 Flag each @code{raise} statement that raises a predefined exception
22584 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
22585 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
22586
22587 This rule has no parameters.
22588
22589 @node Separate_Numeric_Error_Handlers
22590 @subsection @code{Separate_Numeric_Error_Handlers}
22591 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
22592
22593 @noindent
22594 Flags each exception handler that contains a choice for
22595 the predefined @code{Constraint_Error} exception, but does not contain
22596 the choice for the predefined @code{Numeric_Error} exception, or
22597 that contains the choice for @code{Numeric_Error}, but does not contain the
22598 choice for @code{Constraint_Error}.
22599
22600 This rule has no parameters.
22601
22602 @ignore
22603 @node Recursion
22604 @subsection @code{Recursion} (under construction, GLOBAL)
22605 @cindex @code{Recursion} rule (for @command{gnatcheck})
22606
22607 @noindent
22608 Flag recursive subprograms (cycles in the call graph). Declarations, and not
22609 calls, of recursive subprograms are detected.
22610
22611 This rule has no parameters.
22612 @end ignore
22613
22614 @ignore
22615 @node Side_Effect_Functions
22616 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
22617 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
22618
22619 @noindent
22620 Flag functions with side effects.
22621
22622 We define a side effect as changing any data object that is not local for the
22623 body of this function.
22624
22625 At the moment, we do NOT consider a side effect any input-output operations
22626 (changing a state or a content of any file).
22627
22628 We do not consider protected functions for this rule (???)
22629
22630 There are the following sources of side effect:
22631
22632 @enumerate
22633 @item Explicit (or direct) side-effect:
22634
22635 @itemize @bullet
22636 @item
22637 direct assignment to a non-local variable;
22638
22639 @item
22640 direct call to an entity that is known to change some data object that is
22641      not local for the body of this function (Note, that if F1 calls F2 and F2
22642      does have a side effect, this does not automatically mean that F1 also
22643      have a side effect, because it may be the case that F2 is declared in
22644      F1's body and it changes some data object that is global for F2, but
22645      local for F1);
22646 @end itemize
22647
22648 @item Indirect side-effect:
22649 @itemize @bullet
22650 @item
22651 Subprogram calls implicitly issued by:
22652 @itemize @bullet
22653 @item
22654 computing initialization expressions from type declarations as a part
22655          of object elaboration or allocator evaluation;
22656 @item
22657 computing implicit parameters of subprogram or entry calls or generic
22658          instantiations;
22659 @end itemize
22660
22661 @item
22662 activation of a task that change some non-local data object (directly or
22663      indirectly);
22664
22665 @item
22666 elaboration code of a package that is a result of a package instantiation;
22667
22668 @item
22669 controlled objects;
22670 @end itemize
22671
22672 @item Situations when we can suspect a side-effect, but the full static check
22673 is either impossible or too hard:
22674 @itemize @bullet
22675 @item
22676 assignment to access variables or to the objects pointed by access
22677      variables;
22678
22679 @item
22680 call to a subprogram pointed by access-to-subprogram value
22681
22682 @item
22683 dispatching calls;
22684 @end itemize
22685 @end enumerate
22686
22687 @noindent
22688 This rule has no parameters.
22689 @end ignore
22690
22691 @node Slices
22692 @subsection @code{Slices}
22693 @cindex @code{Slices} rule (for @command{gnatcheck})
22694
22695 @noindent
22696 Flag all uses of array slicing
22697
22698 This rule has no parameters.
22699
22700
22701 @node Too_Many_Parents
22702 @subsection @code{Too_Many_Parents}
22703 @cindex @code{Too_Many_Parents} rule (for @command{gnatcheck})
22704
22705 @noindent
22706 Flags any type declaration, single task declaration or single protected
22707 declaration that has more then  @option{N} parents,  @option{N} is a parameter
22708 of the rule.
22709 A parent here is either a (sub)type denoted by the subtype mark from the
22710 parent_subtype_indication (in case of a derived type declaration), or
22711 any of the progenitors from the interface list, if any.
22712
22713 This rule has the following (mandatory) parameters for the @option{+R} option:
22714
22715 @table @emph
22716 @item N
22717 Positive integer specifying the maximal allowed number of parents.
22718 @end table
22719
22720
22721 @node Unassigned_OUT_Parameters
22722 @subsection @code{Unassigned_OUT_Parameters}
22723 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
22724
22725 @noindent
22726 Flags procedures' @code{out} parameters that are not assigned, and
22727 identifies the contexts in which the assignments are missing.
22728
22729 An @code{out} parameter is flagged in the statements in the procedure
22730 body's handled sequence of statements (before the procedure body's
22731 @code{exception} part, if any) if this sequence of statements contains
22732 no assignments to the parameter.
22733
22734 An @code{out} parameter is flagged in an exception handler in the exception
22735 part of the procedure body's handled sequence of statements if the handler
22736 contains no assignment to the parameter.
22737
22738 Bodies of generic procedures are also considered.
22739
22740 The following are treated as assignments to an @code{out} parameter:
22741
22742 @itemize @bullet
22743 @item
22744 an assignment statement, with the parameter or some component as the target;
22745
22746 @item
22747 passing the parameter (or one of its components) as an @code{out} or
22748 @code{in out} parameter.
22749 @end itemize
22750
22751 @noindent
22752 This rule does not have any parameters.
22753
22754
22755
22756 @node Uncommented_BEGIN_In_Package_Bodies
22757 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
22758 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
22759
22760 @noindent
22761 Flags each package body with declarations and a statement part that does not
22762 include a trailing comment on the line containing the @code{begin} keyword;
22763 this trailing comment needs to specify the package name and nothing else.
22764 The @code{begin} is not flagged if the package body does not
22765 contain any declarations.
22766
22767 If the @code{begin} keyword is placed on the
22768 same line as the last declaration or the first statement, it is flagged
22769 independently of whether the line contains a trailing comment. The
22770 diagnostic message is attached to the line containing the first statement.
22771
22772 This rule has no parameters.
22773
22774 @node Unconditional_Exits
22775 @subsection @code{Unconditional_Exits}
22776 @cindex @code{Unconditional_Exits} rule (for @command{gnatcheck})
22777
22778 @noindent
22779 Flag unconditional @code{exit} statements.
22780
22781 This rule has no parameters.
22782
22783 @node Unconstrained_Array_Returns
22784 @subsection @code{Unconstrained_Array_Returns}
22785 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
22786
22787 @noindent
22788 Flag each function returning an unconstrained array. Function declarations,
22789 function bodies (and body stubs) having no separate specifications,
22790 and generic function instantiations are checked.
22791 Function calls and function renamings are
22792 not checked.
22793
22794 Generic function declarations, and function declarations in generic
22795 packages are not checked, instead this rule checks the results of
22796 generic instantiations (that is, expanded specification and expanded
22797 body corresponding to an instantiation).
22798
22799 This rule has no parameters.
22800
22801 @node Universal_Ranges
22802 @subsection @code{Universal_Ranges}
22803 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
22804
22805 @noindent
22806 Flag discrete ranges that are a part of an index constraint, constrained
22807 array definition, or @code{for}-loop parameter specification, and whose bounds
22808 are both of type @i{universal_integer}. Ranges that have at least one
22809 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
22810 or an expression of non-universal type) are not flagged.
22811
22812 This rule has no parameters.
22813
22814
22815 @node Unnamed_Blocks_And_Loops
22816 @subsection @code{Unnamed_Blocks_And_Loops}
22817 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
22818
22819 @noindent
22820 Flag each unnamed block statement and loop statement.
22821
22822 The rule has no parameters.
22823
22824
22825
22826 @ignore
22827 @node Unused_Subprograms
22828 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22829 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22830
22831 @noindent
22832 Flag all unused subprograms.
22833
22834 This rule has no parameters.
22835 @end ignore
22836
22837
22838
22839
22840 @node USE_PACKAGE_Clauses
22841 @subsection @code{USE_PACKAGE_Clauses}
22842 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22843
22844 @noindent
22845 Flag all @code{use} clauses for packages; @code{use type} clauses are
22846 not flagged.
22847
22848 This rule has no parameters.
22849
22850
22851 @node Visible_Components
22852 @subsection @code{Visible_Components}
22853 @cindex @code{Visible_Components} rule (for @command{gnatcheck})
22854
22855 @noindent
22856 Flags all the type declarations located in the visible part of a library
22857 package or a library generic package that can declare a visible component. A
22858 type is considered as declaring a visible component if it contains a record
22859 definition by its own or as a part of a record extension. Type declaration is
22860 flagged even if it contains a record definition that defines no components.
22861
22862 Declarations located in private parts of local (generic) packages are not
22863 flagged. Declarations in private packages are not flagged.
22864
22865 This rule has no parameters.
22866
22867
22868 @node Volatile_Objects_Without_Address_Clauses
22869 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22870 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22871
22872 @noindent
22873 Flag each volatile object that does not have an address clause.
22874
22875 The following check is made: if the pragma @code{Volatile} is applied to a
22876 data object or to its type, then an address clause must
22877 be supplied for this object.
22878
22879 This rule does not check the components of data objects,
22880 array components that are volatile as a result of the pragma
22881 @code{Volatile_Components}, or objects that are volatile because
22882 they are atomic as a result of pragmas @code{Atomic} or
22883 @code{Atomic_Components}.
22884
22885 Only variable declarations, and not constant declarations, are checked.
22886
22887 This rule has no parameters.
22888
22889
22890 @c *********************************
22891 @node Creating Sample Bodies Using gnatstub
22892 @chapter Creating Sample Bodies Using @command{gnatstub}
22893 @findex gnatstub
22894
22895 @noindent
22896 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
22897 for library unit declarations.
22898
22899 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
22900 driver (see @ref{The GNAT Driver and Project Files}).
22901
22902 To create a body stub, @command{gnatstub} has to compile the library
22903 unit declaration. Therefore, bodies can be created only for legal
22904 library units. Moreover, if a library unit depends semantically upon
22905 units located outside the current directory, you have to provide
22906 the source search path when calling @command{gnatstub}, see the description
22907 of @command{gnatstub} switches below.
22908
22909 By default, all the program unit body stubs generated by @code{gnatstub}
22910 raise the predefined @code{Program_Error} exception, which will catch
22911 accidental calls of generated stubs. This behavior can be changed with
22912 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
22913
22914 @menu
22915 * Running gnatstub::
22916 * Switches for gnatstub::
22917 @end menu
22918
22919 @node Running gnatstub
22920 @section Running @command{gnatstub}
22921
22922 @noindent
22923 @command{gnatstub} has the command-line interface of the form
22924
22925 @smallexample
22926 $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
22927 @end smallexample
22928
22929 @noindent
22930 where
22931 @table @var
22932 @item filename
22933 is the name of the source file that contains a library unit declaration
22934 for which a body must be created. The file name may contain the path
22935 information.
22936 The file name does not have to follow the GNAT file name conventions. If the
22937 name
22938 does not follow GNAT file naming conventions, the name of the body file must
22939 be provided
22940 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
22941 If the file name follows the GNAT file naming
22942 conventions and the name of the body file is not provided,
22943 @command{gnatstub}
22944 creates the name
22945 of the body file from the argument file name by replacing the @file{.ads}
22946 suffix
22947 with the @file{.adb} suffix.
22948
22949 @item directory
22950 indicates the directory in which the body stub is to be placed (the default
22951 is the
22952 current directory)
22953
22954 @item switches
22955 is an optional sequence of switches as described in the next section
22956 @end table
22957
22958 @node Switches for gnatstub
22959 @section Switches for @command{gnatstub}
22960
22961 @table @option
22962 @c !sort!
22963
22964 @item ^-f^/FULL^
22965 @cindex @option{^-f^/FULL^} (@command{gnatstub})
22966 If the destination directory already contains a file with the name of the
22967 body file
22968 for the argument spec file, replace it with the generated body stub.
22969
22970 @item ^-hs^/HEADER=SPEC^
22971 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
22972 Put the comment header (i.e., all the comments preceding the
22973 compilation unit) from the source of the library unit declaration
22974 into the body stub.
22975
22976 @item ^-hg^/HEADER=GENERAL^
22977 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
22978 Put a sample comment header into the body stub.
22979
22980 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
22981 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
22982 Use the content of the file as the comment header for a generated body stub.
22983
22984 @ifclear vms
22985 @item -IDIR
22986 @cindex @option{-IDIR} (@command{gnatstub})
22987 @itemx -I-
22988 @cindex @option{-I-} (@command{gnatstub})
22989 @end ifclear
22990 @ifset vms
22991 @item /NOCURRENT_DIRECTORY
22992 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
22993 @end ifset
22994 ^These switches have ^This switch has^ the same meaning as in calls to
22995 @command{gcc}.
22996 ^They define ^It defines ^ the source search path in the call to
22997 @command{gcc} issued
22998 by @command{gnatstub} to compile an argument source file.
22999
23000 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
23001 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
23002 This switch has the same meaning as in calls to @command{gcc}.
23003 It defines the additional configuration file to be passed to the call to
23004 @command{gcc} issued
23005 by @command{gnatstub} to compile an argument source file.
23006
23007 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
23008 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
23009 (@var{n} is a non-negative integer). Set the maximum line length in the
23010 body stub to @var{n}; the default is 79. The maximum value that can be
23011 specified is 32767. Note that in the special case of configuration
23012 pragma files, the maximum is always 32767 regardless of whether or
23013 not this switch appears.
23014
23015 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
23016 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
23017 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
23018 the generated body sample to @var{n}.
23019 The default indentation is 3.
23020
23021 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
23022 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
23023 Order local bodies alphabetically. (By default local bodies are ordered
23024 in the same way as the corresponding local specs in the argument spec file.)
23025
23026 @item ^-i^/INDENTATION=^@var{n}
23027 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
23028 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
23029
23030 @item ^-k^/TREE_FILE=SAVE^
23031 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
23032 Do not remove the tree file (i.e., the snapshot of the compiler internal
23033 structures used by @command{gnatstub}) after creating the body stub.
23034
23035 @item ^-l^/LINE_LENGTH=^@var{n}
23036 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
23037 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
23038
23039 @item ^--no-exception^/NO_EXCEPTION^
23040 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
23041 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
23042 This is not always possible for function stubs.
23043
23044 @item ^--no-local-header^/NO_LOCAL_HEADER^
23045 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
23046 Do not place local comment header with unit name before body stub for a
23047 unit.
23048
23049 @item ^-o ^/BODY=^@var{body-name}
23050 @cindex @option{^-o^/BODY^} (@command{gnatstub})
23051 Body file name.  This should be set if the argument file name does not
23052 follow
23053 the GNAT file naming
23054 conventions. If this switch is omitted the default name for the body will be
23055 obtained
23056 from the argument file name according to the GNAT file naming conventions.
23057
23058 @item ^-q^/QUIET^
23059 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
23060 Quiet mode: do not generate a confirmation when a body is
23061 successfully created, and do not generate a message when a body is not
23062 required for an
23063 argument unit.
23064
23065 @item ^-r^/TREE_FILE=REUSE^
23066 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
23067 Reuse the tree file (if it exists) instead of creating it.  Instead of
23068 creating the tree file for the library unit declaration, @command{gnatstub}
23069 tries to find it in the current directory and use it for creating
23070 a body. If the tree file is not found, no body is created. This option
23071 also implies @option{^-k^/SAVE^}, whether or not
23072 the latter is set explicitly.
23073
23074 @item ^-t^/TREE_FILE=OVERWRITE^
23075 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
23076 Overwrite the existing tree file.  If the current directory already
23077 contains the file which, according to the GNAT file naming rules should
23078 be considered as a tree file for the argument source file,
23079 @command{gnatstub}
23080 will refuse to create the tree file needed to create a sample body
23081 unless this option is set.
23082
23083 @item ^-v^/VERBOSE^
23084 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
23085 Verbose mode: generate version information.
23086
23087 @end table
23088
23089 @c *********************************
23090 @node Generating Ada Bindings for C and C++ headers
23091 @chapter Generating Ada Bindings for C and C++ headers
23092 @findex binding
23093
23094 @noindent
23095 GNAT now comes with a new experimental binding generator for C and C++
23096 headers which is intended to do 95% of the tedious work of generating
23097 Ada specs from C or C++ header files. Note that this still is a work in
23098 progress, not designed to generate 100% correct Ada specs.
23099
23100 The code generated is using the Ada 2005 syntax, which makes it
23101 easier to interface with other languages than previous versions of Ada.
23102
23103 @menu
23104 * Running the binding generator::
23105 * Generating bindings for C++ headers::
23106 * Switches::
23107 @end menu
23108
23109 @node Running the binding generator
23110 @section Running the binding generator
23111
23112 @noindent
23113 The binding generator is part of the @command{gcc} compiler and can be
23114 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
23115 spec files for the header files specified on the command line, and all
23116 header files needed by these files transitivitely. For example:
23117
23118 @smallexample
23119 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
23120 $ gcc -c -gnat05 *.ads
23121 @end smallexample
23122
23123 will generate, under GNU/Linux, the following files: @file{time_h.ads},
23124 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
23125 correspond to the files @file{/usr/include/time.h},
23126 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
23127 mode these Ada specs.
23128
23129 The @code{-C} switch tells @command{gcc} to extract comments from headers,
23130 and will attempt to generate corresponding Ada comments.
23131
23132 If you want to generate a single Ada file and not the transitive closure, you
23133 can use instead the @option{-fdump-ada-spec-slim} switch.
23134
23135 Note that we recommend when possible to use the @command{g++} driver to
23136 generate bindings, even for most C headers, since this will in general
23137 generate better Ada specs. For generating bindings for C++ headers, it is
23138 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
23139 is equivalent in this case. If @command{g++} cannot work on your C headers
23140 because of incompatibilities between C and C++, then you can fallback to
23141 @command{gcc} instead.
23142
23143 For an example of better bindings generated from the C++ front-end,
23144 the name of the parameters (when available) are actually ignored by the C
23145 front-end. Consider the following C header:
23146
23147 @smallexample
23148 extern void foo (int variable);
23149 @end smallexample
23150
23151 with the C front-end, @code{variable} is ignored, and the above is handled as:
23152
23153 @smallexample
23154 extern void foo (int);
23155 @end smallexample
23156
23157 generating a generic:
23158
23159 @smallexample
23160 procedure foo (param1 : int);
23161 @end smallexample
23162
23163 with the C++ front-end, the name is available, and we generate:
23164
23165 @smallexample
23166 procedure foo (variable : int);
23167 @end smallexample
23168
23169 In some cases, the generated bindings will be more complete or more meaningful
23170 when defining some macros, which you can do via the @option{-D} switch. This
23171 is for example the case with @file{Xlib.h} under GNU/Linux:
23172
23173 @smallexample
23174 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
23175 @end smallexample
23176
23177 The above will generate more complete bindings than a straight call without
23178 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
23179
23180 In other cases, it is not possible to parse a header file in a stand alone
23181 manner, because other include files need to be included first. In this
23182 case, the solution is to create a small header file including the needed
23183 @code{#include} and possible @code{#define} directives. For example, to
23184 generate Ada bindings for @file{readline/readline.h}, you need to first
23185 include @file{stdio.h}, so you can create a file with the following two
23186 lines in e.g. @file{readline1.h}:
23187
23188 @smallexample
23189 #include <stdio.h>
23190 #include <readline/readline.h>
23191 @end smallexample
23192
23193 and then generate Ada bindings from this file:
23194
23195 @smallexample
23196 $ g++ -c -fdump-ada-spec readline1.h
23197 @end smallexample
23198
23199 @node Generating bindings for C++ headers
23200 @section Generating bindings for C++ headers
23201
23202 @noindent
23203 Generating bindings for C++ headers is done using the same options, always
23204 with the @command{g++} compiler.
23205
23206 In this mode, C++ classes will be mapped to Ada tagged types, constructors
23207 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
23208 multiple inheritance of abstract classes will be mapped to Ada interfaces
23209 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
23210 information on interfacing to C++).
23211
23212 For example, given the following C++ header file:
23213
23214 @smallexample
23215 @group
23216 @cartouche
23217 class Carnivore @{
23218 public:
23219    virtual int Number_Of_Teeth () = 0;
23220 @};
23221
23222 class Domestic @{
23223 public:
23224    virtual void Set_Owner (char* Name) = 0;
23225 @};
23226
23227 class Animal @{
23228 public:
23229   int Age_Count;
23230   virtual void Set_Age (int New_Age);
23231 @};
23232
23233 class Dog : Animal, Carnivore, Domestic @{
23234  public:
23235   int  Tooth_Count;
23236   char *Owner;
23237
23238   virtual int  Number_Of_Teeth ();
23239   virtual void Set_Owner (char* Name);
23240
23241   Dog();
23242 @};
23243 @end cartouche
23244 @end group
23245 @end smallexample
23246
23247 The corresponding Ada code is generated:
23248
23249 @smallexample @c ada
23250 @group
23251 @cartouche
23252   package Class_Carnivore is
23253     type Carnivore is limited interface;
23254     pragma Import (CPP, Carnivore);
23255
23256     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
23257   end;
23258   use Class_Carnivore;
23259
23260   package Class_Domestic is
23261     type Domestic is limited interface;
23262     pragma Import (CPP, Domestic);
23263
23264     procedure Set_Owner
23265       (this : access Domestic;
23266        Name : Interfaces.C.Strings.chars_ptr) is abstract;
23267   end;
23268   use Class_Domestic;
23269
23270   package Class_Animal is
23271     type Animal is tagged limited record
23272       Age_Count : aliased int;
23273     end record;
23274     pragma Import (CPP, Animal);
23275
23276     procedure Set_Age (this : access Animal; New_Age : int);
23277     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
23278   end;
23279   use Class_Animal;
23280
23281   package Class_Dog is
23282     type Dog is new Animal and Carnivore and Domestic with record
23283       Tooth_Count : aliased int;
23284       Owner : Interfaces.C.Strings.chars_ptr;
23285     end record;
23286     pragma Import (CPP, Dog);
23287
23288     function Number_Of_Teeth (this : access Dog) return int;
23289     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
23290
23291     procedure Set_Owner
23292       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
23293     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
23294
23295     function New_Dog return Dog;
23296     pragma CPP_Constructor (New_Dog);
23297     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
23298   end;
23299   use Class_Dog;
23300 @end cartouche
23301 @end group
23302 @end smallexample
23303
23304 @node Switches
23305 @section Switches
23306
23307 @table @option
23308 @item -fdump-ada-spec
23309 @cindex @option{-fdump-ada-spec} (@command{gcc})
23310 Generate Ada spec files for the given header files transitively (including
23311 all header files that these headers depend upon).
23312
23313 @item -fdump-ada-spec-slim
23314 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
23315 Generate Ada spec files for the header files specified on the command line
23316 only.
23317
23318 @item -C
23319 @cindex @option{-C} (@command{gcc})
23320 Extract comments from headers and generate Ada comments in the Ada spec files.
23321 @end table
23322
23323 @node Other Utility Programs
23324 @chapter Other Utility Programs
23325
23326 @noindent
23327 This chapter discusses some other utility programs available in the Ada
23328 environment.
23329
23330 @menu
23331 * Using Other Utility Programs with GNAT::
23332 * The External Symbol Naming Scheme of GNAT::
23333 * Converting Ada Files to html with gnathtml::
23334 * Installing gnathtml::
23335 @ifset vms
23336 * LSE::
23337 * Profiling::
23338 @end ifset
23339 @end menu
23340
23341 @node Using Other Utility Programs with GNAT
23342 @section Using Other Utility Programs with GNAT
23343
23344 @noindent
23345 The object files generated by GNAT are in standard system format and in
23346 particular the debugging information uses this format. This means
23347 programs generated by GNAT can be used with existing utilities that
23348 depend on these formats.
23349
23350 @ifclear vms
23351 In general, any utility program that works with C will also often work with
23352 Ada programs generated by GNAT. This includes software utilities such as
23353 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
23354 as Purify.
23355 @end ifclear
23356
23357 @node The External Symbol Naming Scheme of GNAT
23358 @section The External Symbol Naming Scheme of GNAT
23359
23360 @noindent
23361 In order to interpret the output from GNAT, when using tools that are
23362 originally intended for use with other languages, it is useful to
23363 understand the conventions used to generate link names from the Ada
23364 entity names.
23365
23366 All link names are in all lowercase letters. With the exception of library
23367 procedure names, the mechanism used is simply to use the full expanded
23368 Ada name with dots replaced by double underscores. For example, suppose
23369 we have the following package spec:
23370
23371 @smallexample @c ada
23372 @group
23373 @cartouche
23374 package QRS is
23375    MN : Integer;
23376 end QRS;
23377 @end cartouche
23378 @end group
23379 @end smallexample
23380
23381 @noindent
23382 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
23383 the corresponding link name is @code{qrs__mn}.
23384 @findex Export
23385 Of course if a @code{pragma Export} is used this may be overridden:
23386
23387 @smallexample @c ada
23388 @group
23389 @cartouche
23390 package Exports is
23391    Var1 : Integer;
23392    pragma Export (Var1, C, External_Name => "var1_name");
23393    Var2 : Integer;
23394    pragma Export (Var2, C, Link_Name => "var2_link_name");
23395 end Exports;
23396 @end cartouche
23397 @end group
23398 @end smallexample
23399
23400 @noindent
23401 In this case, the link name for @var{Var1} is whatever link name the
23402 C compiler would assign for the C function @var{var1_name}. This typically
23403 would be either @var{var1_name} or @var{_var1_name}, depending on operating
23404 system conventions, but other possibilities exist. The link name for
23405 @var{Var2} is @var{var2_link_name}, and this is not operating system
23406 dependent.
23407
23408 @findex _main
23409 One exception occurs for library level procedures. A potential ambiguity
23410 arises between the required name @code{_main} for the C main program,
23411 and the name we would otherwise assign to an Ada library level procedure
23412 called @code{Main} (which might well not be the main program).
23413
23414 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
23415 names. So if we have a library level procedure such as
23416
23417 @smallexample @c ada
23418 @group
23419 @cartouche
23420 procedure Hello (S : String);
23421 @end cartouche
23422 @end group
23423 @end smallexample
23424
23425 @noindent
23426 the external name of this procedure will be @var{_ada_hello}.
23427
23428
23429 @node Converting Ada Files to html with gnathtml
23430 @section Converting Ada Files to HTML with @code{gnathtml}
23431
23432 @noindent
23433 This @code{Perl} script allows Ada source files to be browsed using
23434 standard Web browsers. For installation procedure, see the section
23435 @xref{Installing gnathtml}.
23436
23437 Ada reserved keywords are highlighted in a bold font and Ada comments in
23438 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
23439 switch to suppress the generation of cross-referencing information, user
23440 defined variables and types will appear in a different color; you will
23441 be able to click on any identifier and go to its declaration.
23442
23443 The command line is as follow:
23444 @smallexample
23445 $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
23446 @end smallexample
23447
23448 @noindent
23449 You can pass it as many Ada files as you want. @code{gnathtml} will generate
23450 an html file for every ada file, and a global file called @file{index.htm}.
23451 This file is an index of every identifier defined in the files.
23452
23453 The available ^switches^options^ are the following ones:
23454
23455 @table @option
23456 @item -83
23457 @cindex @option{-83} (@code{gnathtml})
23458 Only the Ada 83 subset of keywords will be highlighted.
23459
23460 @item -cc @var{color}
23461 @cindex @option{-cc} (@code{gnathtml})
23462 This option allows you to change the color used for comments. The default
23463 value is green. The color argument can be any name accepted by html.
23464
23465 @item -d
23466 @cindex @option{-d} (@code{gnathtml})
23467 If the Ada files depend on some other files (for instance through
23468 @code{with} clauses, the latter files will also be converted to html.
23469 Only the files in the user project will be converted to html, not the files
23470 in the run-time library itself.
23471
23472 @item -D
23473 @cindex @option{-D} (@code{gnathtml})
23474 This command is the same as @option{-d} above, but @command{gnathtml} will
23475 also look for files in the run-time library, and generate html files for them.
23476
23477 @item -ext @var{extension}
23478 @cindex @option{-ext} (@code{gnathtml})
23479 This option allows you to change the extension of the generated HTML files.
23480 If you do not specify an extension, it will default to @file{htm}.
23481
23482 @item -f
23483 @cindex @option{-f} (@code{gnathtml})
23484 By default, gnathtml will generate html links only for global entities
23485 ('with'ed units, global variables and types,@dots{}).  If you specify
23486 @option{-f} on the command line, then links will be generated for local
23487 entities too.
23488
23489 @item -l @var{number}
23490 @cindex @option{-l} (@code{gnathtml})
23491 If this ^switch^option^ is provided and @var{number} is not 0, then
23492 @code{gnathtml} will number the html files every @var{number} line.
23493
23494 @item -I @var{dir}
23495 @cindex @option{-I} (@code{gnathtml})
23496 Specify a directory to search for library files (@file{.ALI} files) and
23497 source files. You can provide several -I switches on the command line,
23498 and the directories will be parsed in the order of the command line.
23499
23500 @item -o @var{dir}
23501 @cindex @option{-o} (@code{gnathtml})
23502 Specify the output directory for html files. By default, gnathtml will
23503 saved the generated html files in a subdirectory named @file{html/}.
23504
23505 @item -p @var{file}
23506 @cindex @option{-p} (@code{gnathtml})
23507 If you are using Emacs and the most recent Emacs Ada mode, which provides
23508 a full Integrated Development Environment for compiling, checking,
23509 running and debugging applications, you may use @file{.gpr} files
23510 to give the directories where Emacs can find sources and object files.
23511
23512 Using this ^switch^option^, you can tell gnathtml to use these files.
23513 This allows you to get an html version of your application, even if it
23514 is spread over multiple directories.
23515
23516 @item -sc @var{color}
23517 @cindex @option{-sc} (@code{gnathtml})
23518 This ^switch^option^ allows you to change the color used for symbol
23519 definitions.
23520 The default value is red. The color argument can be any name accepted by html.
23521
23522 @item -t @var{file}
23523 @cindex @option{-t} (@code{gnathtml})
23524 This ^switch^option^ provides the name of a file. This file contains a list of
23525 file names to be converted, and the effect is exactly as though they had
23526 appeared explicitly on the command line. This
23527 is the recommended way to work around the command line length limit on some
23528 systems.
23529
23530 @end table
23531
23532 @node Installing gnathtml
23533 @section Installing @code{gnathtml}
23534
23535 @noindent
23536 @code{Perl} needs to be installed on your machine to run this script.
23537 @code{Perl} is freely available for almost every architecture and
23538 Operating System via the Internet.
23539
23540 On Unix systems, you  may want to modify  the  first line of  the script
23541 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
23542 is. The syntax of this line is:
23543 @smallexample
23544 #!full_path_name_to_perl
23545 @end smallexample
23546
23547 @noindent
23548 Alternatively, you may run the script using the following command line:
23549
23550 @smallexample
23551 $ perl gnathtml.pl @ovar{switches} @var{files}
23552 @end smallexample
23553
23554 @ifset vms
23555 @node LSE
23556 @section LSE
23557 @findex LSE
23558
23559 @noindent
23560 The GNAT distribution provides an Ada 95 template for the HP Language
23561 Sensitive Editor (LSE), a component of DECset. In order to
23562 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
23563
23564 @node Profiling
23565 @section Profiling
23566 @findex PCA
23567
23568 @noindent
23569 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
23570 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
23571 the collection phase with the /DEBUG qualifier.
23572
23573 @smallexample
23574 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
23575 $ DEFINE LIB$DEBUG PCA$COLLECTOR
23576 $ RUN/DEBUG <PROGRAM_NAME>
23577 @end smallexample
23578 @noindent
23579 @end ifset
23580
23581 @ifclear vms
23582 @c ******************************
23583 @node Code Coverage and Profiling
23584 @chapter Code Coverage and Profiling
23585 @cindex Code Coverage
23586 @cindex Profiling
23587
23588 @noindent
23589 This chapter describes how to use @code{gcov} - coverage testing tool - and
23590 @code{gprof} - profiler tool - on your Ada programs.
23591
23592 @menu
23593 * Code Coverage of Ada Programs using gcov::
23594 * Profiling an Ada Program using gprof::
23595 @end menu
23596
23597 @node Code Coverage of Ada Programs using gcov
23598 @section Code Coverage of Ada Programs using gcov
23599 @cindex gcov
23600 @cindex -fprofile-arcs
23601 @cindex -ftest-coverage
23602 @cindex -coverage
23603 @cindex Code Coverage
23604
23605 @noindent
23606 @code{gcov} is a test coverage program: it analyzes the execution of a given
23607 program on selected tests, to help you determine the portions of the program
23608 that are still untested.
23609
23610 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
23611 User's Guide. You can refer to this documentation for a more complete
23612 description.
23613
23614 This chapter provides a quick startup guide, and
23615 details some Gnat-specific features.
23616
23617 @menu
23618 * Quick startup guide::
23619 * Gnat specifics::
23620 @end menu
23621
23622 @node Quick startup guide
23623 @subsection Quick startup guide
23624
23625 In order to perform coverage analysis of a program using @code{gcov}, 3
23626 steps are needed:
23627
23628 @itemize @bullet
23629 @item
23630 Code instrumentation during the compilation process
23631 @item
23632 Execution of the instrumented program
23633 @item
23634 Execution of the @code{gcov} tool to generate the result.
23635 @end itemize
23636
23637 The code instrumentation needed by gcov is created at the object level:
23638 The source code is not modified in any way, because the instrumentation code is
23639 inserted by gcc during the compilation process. To compile your code with code
23640 coverage activated, you need to recompile your whole project using the
23641 switches
23642 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
23643 @code{-fprofile-arcs}.
23644
23645 @smallexample
23646 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
23647    -largs -fprofile-arcs
23648 @end smallexample
23649
23650 This compilation process will create @file{.gcno} files together with
23651 the usual object files.
23652
23653 Once the program is compiled with coverage instrumentation, you can
23654 run it as many times as needed - on portions of a test suite for
23655 example. The first execution will produce @file{.gcda} files at the
23656 same location as the @file{.gcno} files.  The following executions
23657 will update those files, so that a cumulative result of the covered
23658 portions of the program is generated.
23659
23660 Finally, you need to call the @code{gcov} tool. The different options of
23661 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
23662
23663 This will create annotated source files with a @file{.gcov} extension:
23664 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
23665
23666 @node Gnat specifics
23667 @subsection Gnat specifics
23668
23669 Because Ada semantics, portions of the source code may be shared among
23670 several object files. This is the case for example when generics are
23671 involved, when inlining is active  or when declarations generate  initialisation
23672 calls. In order to take
23673 into account this shared code, you need to call @code{gcov} on all
23674 source files of the tested program at once.
23675
23676 The list of source files might exceed the system's maximum command line
23677 length. In order to bypass this limitation, a new mechanism has been
23678 implemented in @code{gcov}: you can now list all your project's files into a
23679 text file, and provide this file to gcov as a parameter,  preceded by a @@
23680 (e.g. @samp{gcov @@mysrclist.txt}).
23681
23682 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
23683 not supported as there can be unresolved symbols during the final link.
23684
23685 @node Profiling an Ada Program using gprof
23686 @section Profiling an Ada Program using gprof
23687 @cindex gprof
23688 @cindex -pg
23689 @cindex Profiling
23690
23691 @noindent
23692 This section is not meant to be an exhaustive documentation of @code{gprof}.
23693 Full documentation for it can be found in the GNU Profiler User's Guide
23694 documentation that is part of this GNAT distribution.
23695
23696 Profiling a program helps determine the parts of a program that are executed
23697 most often, and are therefore the most time-consuming.
23698
23699 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
23700 better handle Ada programs and multitasking.
23701 It is currently supported on the following platforms
23702 @itemize @bullet
23703 @item
23704 linux x86/x86_64
23705 @item
23706 solaris sparc/sparc64/x86
23707 @item
23708 windows x86
23709 @end itemize
23710
23711 @noindent
23712 In order to profile a program using @code{gprof}, 3 steps are needed:
23713
23714 @itemize @bullet
23715 @item
23716 Code instrumentation, requiring a full recompilation of the project with the
23717 proper switches.
23718 @item
23719 Execution of the program under the analysis conditions, i.e. with the desired
23720 input.
23721 @item
23722 Analysis of the results using the @code{gprof} tool.
23723 @end itemize
23724
23725 @noindent
23726 The following sections detail the different steps, and indicate how
23727 to interpret the results:
23728 @menu
23729 * Compilation for profiling::
23730 * Program execution::
23731 * Running gprof::
23732 * Interpretation of profiling results::
23733 @end menu
23734
23735 @node Compilation for profiling
23736 @subsection Compilation for profiling
23737 @cindex -pg
23738 @cindex Profiling
23739
23740 In order to profile a program the first step is to tell the compiler
23741 to generate the necessary profiling information. The compiler switch to be used
23742 is @code{-pg}, which must be added to other compilation switches. This
23743 switch needs to be specified both during compilation and link stages, and can
23744 be specified once when using gnatmake:
23745
23746 @smallexample
23747 gnatmake -f -pg -P my_project
23748 @end smallexample
23749
23750 @noindent
23751 Note that only the objects that were compiled with the @samp{-pg} switch will be
23752 profiled; if you need to profile your whole project, use the
23753 @samp{-f} gnatmake switch to force full recompilation.
23754
23755 @node Program execution
23756 @subsection Program execution
23757
23758 @noindent
23759 Once the program has been compiled for profiling, you can run it as usual.
23760
23761 The only constraint imposed by profiling is that the program must terminate
23762 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
23763 properly analyzed.
23764
23765 Once the program completes execution, a data file called @file{gmon.out} is
23766 generated in the directory where the program was launched from. If this file
23767 already exists, it will be overwritten.
23768
23769 @node Running gprof
23770 @subsection Running gprof
23771
23772 @noindent
23773 The @code{gprof} tool is called as follow:
23774
23775 @smallexample
23776 gprof my_prog gmon.out
23777 @end smallexample
23778
23779 @noindent
23780 or simpler:
23781
23782 @smallexample
23783 gprof my_prog
23784 @end smallexample
23785
23786 @noindent
23787 The complete form of the gprof command line is the following:
23788
23789 @smallexample
23790 gprof [^switches^options^] [executable [data-file]]
23791 @end smallexample
23792
23793 @noindent
23794 @code{gprof} supports numerous ^switch^options^. The order of these
23795 ^switch^options^ does not matter. The full list of options can be found in
23796 the GNU Profiler User's Guide documentation that comes with this documentation.
23797
23798 The following is the subset of those switches that is most relevant:
23799
23800 @table @option
23801
23802 @item --demangle[=@var{style}]
23803 @itemx --no-demangle
23804 @cindex @option{--demangle} (@code{gprof})
23805 These options control whether symbol names should be demangled when
23806 printing output.  The default is to demangle C++ symbols.  The
23807 @code{--no-demangle} option may be used to turn off demangling. Different
23808 compilers have different mangling styles.  The optional demangling style
23809 argument can be used to choose an appropriate demangling style for your
23810 compiler, in particular Ada symbols generated by GNAT can be demangled using
23811 @code{--demangle=gnat}.
23812
23813 @item -e @var{function_name}
23814 @cindex @option{-e} (@code{gprof})
23815 The @samp{-e @var{function}} option tells @code{gprof} not to print
23816 information about the function @var{function_name} (and its
23817 children@dots{}) in the call graph.  The function will still be listed
23818 as a child of any functions that call it, but its index number will be
23819 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
23820 given; only one @var{function_name} may be indicated with each @samp{-e}
23821 option.
23822
23823 @item -E @var{function_name}
23824 @cindex @option{-E} (@code{gprof})
23825 The @code{-E @var{function}} option works like the @code{-e} option, but
23826 execution time spent in the function (and children who were not called from
23827 anywhere else), will not be used to compute the percentages-of-time for
23828 the call graph.  More than one @samp{-E} option may be given; only one
23829 @var{function_name} may be indicated with each @samp{-E} option.
23830
23831 @item -f @var{function_name}
23832 @cindex @option{-f} (@code{gprof})
23833 The @samp{-f @var{function}} option causes @code{gprof} to limit the
23834 call graph to the function @var{function_name} and its children (and
23835 their children@dots{}).  More than one @samp{-f} option may be given;
23836 only one @var{function_name} may be indicated with each @samp{-f}
23837 option.
23838
23839 @item -F @var{function_name}
23840 @cindex @option{-F} (@code{gprof})
23841 The @samp{-F @var{function}} option works like the @code{-f} option, but
23842 only time spent in the function and its children (and their
23843 children@dots{}) will be used to determine total-time and
23844 percentages-of-time for the call graph.  More than one @samp{-F} option
23845 may be given; only one @var{function_name} may be indicated with each
23846 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
23847
23848 @end table
23849
23850 @node Interpretation of profiling results
23851 @subsection Interpretation of profiling results
23852
23853 @noindent
23854
23855 The results of the profiling analysis are represented by two arrays: the
23856 'flat profile' and the 'call graph'. Full documentation of those outputs
23857 can be found in the GNU Profiler User's Guide.
23858
23859 The flat profile shows the time spent in each function of the program, and how
23860 many time it has been called. This allows you to locate easily the most
23861 time-consuming functions.
23862
23863 The call graph shows, for each subprogram, the subprograms that call it,
23864 and the subprograms that it calls. It also provides an estimate of the time
23865 spent in each of those callers/called subprograms.
23866 @end ifclear
23867
23868 @c ******************************
23869 @node Running and Debugging Ada Programs
23870 @chapter Running and Debugging Ada Programs
23871 @cindex Debugging
23872
23873 @noindent
23874 This chapter discusses how to debug Ada programs.
23875 @ifset vms
23876 It applies to GNAT on the Alpha OpenVMS platform;
23877 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
23878 since HP has implemented Ada support in the OpenVMS debugger on I64.
23879 @end ifset
23880
23881 An incorrect Ada program may be handled in three ways by the GNAT compiler:
23882
23883 @enumerate
23884 @item
23885 The illegality may be a violation of the static semantics of Ada. In
23886 that case GNAT diagnoses the constructs in the program that are illegal.
23887 It is then a straightforward matter for the user to modify those parts of
23888 the program.
23889
23890 @item
23891 The illegality may be a violation of the dynamic semantics of Ada. In
23892 that case the program compiles and executes, but may generate incorrect
23893 results, or may terminate abnormally with some exception.
23894
23895 @item
23896 When presented with a program that contains convoluted errors, GNAT
23897 itself may terminate abnormally without providing full diagnostics on
23898 the incorrect user program.
23899 @end enumerate
23900
23901 @menu
23902 * The GNAT Debugger GDB::
23903 * Running GDB::
23904 * Introduction to GDB Commands::
23905 * Using Ada Expressions::
23906 * Calling User-Defined Subprograms::
23907 * Using the Next Command in a Function::
23908 * Ada Exceptions::
23909 * Ada Tasks::
23910 * Debugging Generic Units::
23911 * GNAT Abnormal Termination or Failure to Terminate::
23912 * Naming Conventions for GNAT Source Files::
23913 * Getting Internal Debugging Information::
23914 * Stack Traceback::
23915 @end menu
23916
23917 @cindex Debugger
23918 @findex gdb
23919
23920 @node The GNAT Debugger GDB
23921 @section The GNAT Debugger GDB
23922
23923 @noindent
23924 @code{GDB} is a general purpose, platform-independent debugger that
23925 can be used to debug mixed-language programs compiled with @command{gcc},
23926 and in particular is capable of debugging Ada programs compiled with
23927 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
23928 complex Ada data structures.
23929
23930 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
23931 @ifset vms
23932 located in the GNU:[DOCS] directory,
23933 @end ifset
23934 for full details on the usage of @code{GDB}, including a section on
23935 its usage on programs. This manual should be consulted for full
23936 details. The section that follows is a brief introduction to the
23937 philosophy and use of @code{GDB}.
23938
23939 When GNAT programs are compiled, the compiler optionally writes debugging
23940 information into the generated object file, including information on
23941 line numbers, and on declared types and variables. This information is
23942 separate from the generated code. It makes the object files considerably
23943 larger, but it does not add to the size of the actual executable that
23944 will be loaded into memory, and has no impact on run-time performance. The
23945 generation of debug information is triggered by the use of the
23946 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
23947 used to carry out the compilations. It is important to emphasize that
23948 the use of these options does not change the generated code.
23949
23950 The debugging information is written in standard system formats that
23951 are used by many tools, including debuggers and profilers. The format
23952 of the information is typically designed to describe C types and
23953 semantics, but GNAT implements a translation scheme which allows full
23954 details about Ada types and variables to be encoded into these
23955 standard C formats. Details of this encoding scheme may be found in
23956 the file exp_dbug.ads in the GNAT source distribution. However, the
23957 details of this encoding are, in general, of no interest to a user,
23958 since @code{GDB} automatically performs the necessary decoding.
23959
23960 When a program is bound and linked, the debugging information is
23961 collected from the object files, and stored in the executable image of
23962 the program. Again, this process significantly increases the size of
23963 the generated executable file, but it does not increase the size of
23964 the executable program itself. Furthermore, if this program is run in
23965 the normal manner, it runs exactly as if the debug information were
23966 not present, and takes no more actual memory.
23967
23968 However, if the program is run under control of @code{GDB}, the
23969 debugger is activated.  The image of the program is loaded, at which
23970 point it is ready to run.  If a run command is given, then the program
23971 will run exactly as it would have if @code{GDB} were not present. This
23972 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
23973 entirely non-intrusive until a breakpoint is encountered.  If no
23974 breakpoint is ever hit, the program will run exactly as it would if no
23975 debugger were present. When a breakpoint is hit, @code{GDB} accesses
23976 the debugging information and can respond to user commands to inspect
23977 variables, and more generally to report on the state of execution.
23978
23979 @c **************
23980 @node Running GDB
23981 @section Running GDB
23982
23983 @noindent
23984 This section describes how to initiate the debugger.
23985 @c The above sentence is really just filler, but it was otherwise
23986 @c clumsy to get the first paragraph nonindented given the conditional
23987 @c nature of the description
23988
23989 @ifclear vms
23990 The debugger can be launched from a @code{GPS} menu or
23991 directly from the command line. The description below covers the latter use.
23992 All the commands shown can be used in the @code{GPS} debug console window,
23993 but there are usually more GUI-based ways to achieve the same effect.
23994 @end ifclear
23995
23996 The command to run @code{GDB} is
23997
23998 @smallexample
23999 $ ^gdb program^GDB PROGRAM^
24000 @end smallexample
24001
24002 @noindent
24003 where @code{^program^PROGRAM^} is the name of the executable file. This
24004 activates the debugger and results in a prompt for debugger commands.
24005 The simplest command is simply @code{run}, which causes the program to run
24006 exactly as if the debugger were not present. The following section
24007 describes some of the additional commands that can be given to @code{GDB}.
24008
24009 @c *******************************
24010 @node Introduction to GDB Commands
24011 @section Introduction to GDB Commands
24012
24013 @noindent
24014 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
24015 Debugging with GDB, gdb, Debugging with GDB},
24016 @ifset vms
24017 located in the GNU:[DOCS] directory,
24018 @end ifset
24019 for extensive documentation on the use
24020 of these commands, together with examples of their use. Furthermore,
24021 the command @command{help} invoked from within GDB activates a simple help
24022 facility which summarizes the available commands and their options.
24023 In this section we summarize a few of the most commonly
24024 used commands to give an idea of what @code{GDB} is about. You should create
24025 a simple program with debugging information and experiment with the use of
24026 these @code{GDB} commands on the program as you read through the
24027 following section.
24028
24029 @table @code
24030 @item set args @var{arguments}
24031 The @var{arguments} list above is a list of arguments to be passed to
24032 the program on a subsequent run command, just as though the arguments
24033 had been entered on a normal invocation of the program. The @code{set args}
24034 command is not needed if the program does not require arguments.
24035
24036 @item run
24037 The @code{run} command causes execution of the program to start from
24038 the beginning. If the program is already running, that is to say if
24039 you are currently positioned at a breakpoint, then a prompt will ask
24040 for confirmation that you want to abandon the current execution and
24041 restart.
24042
24043 @item breakpoint @var{location}
24044 The breakpoint command sets a breakpoint, that is to say a point at which
24045 execution will halt and @code{GDB} will await further
24046 commands. @var{location} is
24047 either a line number within a file, given in the format @code{file:linenumber},
24048 or it is the name of a subprogram. If you request that a breakpoint be set on
24049 a subprogram that is overloaded, a prompt will ask you to specify on which of
24050 those subprograms you want to breakpoint. You can also
24051 specify that all of them should be breakpointed. If the program is run
24052 and execution encounters the breakpoint, then the program
24053 stops and @code{GDB} signals that the breakpoint was encountered by
24054 printing the line of code before which the program is halted.
24055
24056 @item breakpoint exception @var{name}
24057 A special form of the breakpoint command which breakpoints whenever
24058 exception @var{name} is raised.
24059 If @var{name} is omitted,
24060 then a breakpoint will occur when any exception is raised.
24061
24062 @item print @var{expression}
24063 This will print the value of the given expression. Most simple
24064 Ada expression formats are properly handled by @code{GDB}, so the expression
24065 can contain function calls, variables, operators, and attribute references.
24066
24067 @item continue
24068 Continues execution following a breakpoint, until the next breakpoint or the
24069 termination of the program.
24070
24071 @item step
24072 Executes a single line after a breakpoint. If the next statement
24073 is a subprogram call, execution continues into (the first statement of)
24074 the called subprogram.
24075
24076 @item next
24077 Executes a single line. If this line is a subprogram call, executes and
24078 returns from the call.
24079
24080 @item list
24081 Lists a few lines around the current source location. In practice, it
24082 is usually more convenient to have a separate edit window open with the
24083 relevant source file displayed. Successive applications of this command
24084 print subsequent lines. The command can be given an argument which is a
24085 line number, in which case it displays a few lines around the specified one.
24086
24087 @item backtrace
24088 Displays a backtrace of the call chain. This command is typically
24089 used after a breakpoint has occurred, to examine the sequence of calls that
24090 leads to the current breakpoint. The display includes one line for each
24091 activation record (frame) corresponding to an active subprogram.
24092
24093 @item up
24094 At a breakpoint, @code{GDB} can display the values of variables local
24095 to the current frame. The command @code{up} can be used to
24096 examine the contents of other active frames, by moving the focus up
24097 the stack, that is to say from callee to caller, one frame at a time.
24098
24099 @item down
24100 Moves the focus of @code{GDB} down from the frame currently being
24101 examined to the frame of its callee (the reverse of the previous command),
24102
24103 @item frame @var{n}
24104 Inspect the frame with the given number. The value 0 denotes the frame
24105 of the current breakpoint, that is to say the top of the call stack.
24106
24107 @end table
24108
24109 @noindent
24110 The above list is a very short introduction to the commands that
24111 @code{GDB} provides. Important additional capabilities, including conditional
24112 breakpoints, the ability to execute command sequences on a breakpoint,
24113 the ability to debug at the machine instruction level and many other
24114 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
24115 Debugging with GDB}.  Note that most commands can be abbreviated
24116 (for example, c for continue, bt for backtrace).
24117
24118 @node Using Ada Expressions
24119 @section Using Ada Expressions
24120 @cindex Ada expressions
24121
24122 @noindent
24123 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
24124 extensions. The philosophy behind the design of this subset is
24125
24126 @itemize @bullet
24127 @item
24128 That @code{GDB} should provide basic literals and access to operations for
24129 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
24130 leaving more sophisticated computations to subprograms written into the
24131 program (which therefore may be called from @code{GDB}).
24132
24133 @item
24134 That type safety and strict adherence to Ada language restrictions
24135 are not particularly important to the @code{GDB} user.
24136
24137 @item
24138 That brevity is important to the @code{GDB} user.
24139 @end itemize
24140
24141 @noindent
24142 Thus, for brevity, the debugger acts as if there were
24143 implicit @code{with} and @code{use} clauses in effect for all user-written
24144 packages, thus making it unnecessary to fully qualify most names with
24145 their packages, regardless of context. Where this causes ambiguity,
24146 @code{GDB} asks the user's intent.
24147
24148 For details on the supported Ada syntax, see @ref{Top,, Debugging with
24149 GDB, gdb, Debugging with GDB}.
24150
24151 @node Calling User-Defined Subprograms
24152 @section Calling User-Defined Subprograms
24153
24154 @noindent
24155 An important capability of @code{GDB} is the ability to call user-defined
24156 subprograms while debugging. This is achieved simply by entering
24157 a subprogram call statement in the form:
24158
24159 @smallexample
24160 call subprogram-name (parameters)
24161 @end smallexample
24162
24163 @noindent
24164 The keyword @code{call} can be omitted in the normal case where the
24165 @code{subprogram-name} does not coincide with any of the predefined
24166 @code{GDB} commands.
24167
24168 The effect is to invoke the given subprogram, passing it the
24169 list of parameters that is supplied. The parameters can be expressions and
24170 can include variables from the program being debugged. The
24171 subprogram must be defined
24172 at the library level within your program, and @code{GDB} will call the
24173 subprogram within the environment of your program execution (which
24174 means that the subprogram is free to access or even modify variables
24175 within your program).
24176
24177 The most important use of this facility is in allowing the inclusion of
24178 debugging routines that are tailored to particular data structures
24179 in your program. Such debugging routines can be written to provide a suitably
24180 high-level description of an abstract type, rather than a low-level dump
24181 of its physical layout. After all, the standard
24182 @code{GDB print} command only knows the physical layout of your
24183 types, not their abstract meaning. Debugging routines can provide information
24184 at the desired semantic level and are thus enormously useful.
24185
24186 For example, when debugging GNAT itself, it is crucial to have access to
24187 the contents of the tree nodes used to represent the program internally.
24188 But tree nodes are represented simply by an integer value (which in turn
24189 is an index into a table of nodes).
24190 Using the @code{print} command on a tree node would simply print this integer
24191 value, which is not very useful. But the PN routine (defined in file
24192 treepr.adb in the GNAT sources) takes a tree node as input, and displays
24193 a useful high level representation of the tree node, which includes the
24194 syntactic category of the node, its position in the source, the integers
24195 that denote descendant nodes and parent node, as well as varied
24196 semantic information. To study this example in more detail, you might want to
24197 look at the body of the PN procedure in the stated file.
24198
24199 @node Using the Next Command in a Function
24200 @section Using the Next Command in a Function
24201
24202 @noindent
24203 When you use the @code{next} command in a function, the current source
24204 location will advance to the next statement as usual. A special case
24205 arises in the case of a @code{return} statement.
24206
24207 Part of the code for a return statement is the ``epilog'' of the function.
24208 This is the code that returns to the caller. There is only one copy of
24209 this epilog code, and it is typically associated with the last return
24210 statement in the function if there is more than one return. In some
24211 implementations, this epilog is associated with the first statement
24212 of the function.
24213
24214 The result is that if you use the @code{next} command from a return
24215 statement that is not the last return statement of the function you
24216 may see a strange apparent jump to the last return statement or to
24217 the start of the function. You should simply ignore this odd jump.
24218 The value returned is always that from the first return statement
24219 that was stepped through.
24220
24221 @node Ada Exceptions
24222 @section Breaking on Ada Exceptions
24223 @cindex Exceptions
24224
24225 @noindent
24226 You can set breakpoints that trip when your program raises
24227 selected exceptions.
24228
24229 @table @code
24230 @item break exception
24231 Set a breakpoint that trips whenever (any task in the) program raises
24232 any exception.
24233
24234 @item break exception @var{name}
24235 Set a breakpoint that trips whenever (any task in the) program raises
24236 the exception @var{name}.
24237
24238 @item break exception unhandled
24239 Set a breakpoint that trips whenever (any task in the) program raises an
24240 exception for which there is no handler.
24241
24242 @item info exceptions
24243 @itemx info exceptions @var{regexp}
24244 The @code{info exceptions} command permits the user to examine all defined
24245 exceptions within Ada programs. With a regular expression, @var{regexp}, as
24246 argument, prints out only those exceptions whose name matches @var{regexp}.
24247 @end table
24248
24249 @node Ada Tasks
24250 @section Ada Tasks
24251 @cindex Tasks
24252
24253 @noindent
24254 @code{GDB} allows the following task-related commands:
24255
24256 @table @code
24257 @item info tasks
24258 This command shows a list of current Ada tasks, as in the following example:
24259
24260 @smallexample
24261 @iftex
24262 @leftskip=0cm
24263 @end iftex
24264 (gdb) info tasks
24265   ID       TID P-ID   Thread Pri State                 Name
24266    1   8088000   0   807e000  15 Child Activation Wait main_task
24267    2   80a4000   1   80ae000  15 Accept/Select Wait    b
24268    3   809a800   1   80a4800  15 Child Activation Wait a
24269 *  4   80ae800   3   80b8000  15 Running               c
24270 @end smallexample
24271
24272 @noindent
24273 In this listing, the asterisk before the first task indicates it to be the
24274 currently running task. The first column lists the task ID that is used
24275 to refer to tasks in the following commands.
24276
24277 @item break @var{linespec} task @var{taskid}
24278 @itemx break @var{linespec} task @var{taskid} if @dots{}
24279 @cindex Breakpoints and tasks
24280 These commands are like the @code{break @dots{} thread @dots{}}.
24281 @var{linespec} specifies source lines.
24282
24283 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
24284 to specify that you only want @code{GDB} to stop the program when a
24285 particular Ada task reaches this breakpoint. @var{taskid} is one of the
24286 numeric task identifiers assigned by @code{GDB}, shown in the first
24287 column of the @samp{info tasks} display.
24288
24289 If you do not specify @samp{task @var{taskid}} when you set a
24290 breakpoint, the breakpoint applies to @emph{all} tasks of your
24291 program.
24292
24293 You can use the @code{task} qualifier on conditional breakpoints as
24294 well; in this case, place @samp{task @var{taskid}} before the
24295 breakpoint condition (before the @code{if}).
24296
24297 @item task @var{taskno}
24298 @cindex Task switching
24299
24300 This command allows to switch to the task referred by @var{taskno}. In
24301 particular, This allows to browse the backtrace of the specified
24302 task. It is advised to switch back to the original task before
24303 continuing execution otherwise the scheduling of the program may be
24304 perturbed.
24305 @end table
24306
24307 @noindent
24308 For more detailed information on the tasking support,
24309 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
24310
24311 @node Debugging Generic Units
24312 @section Debugging Generic Units
24313 @cindex Debugging Generic Units
24314 @cindex Generics
24315
24316 @noindent
24317 GNAT always uses code expansion for generic instantiation. This means that
24318 each time an instantiation occurs, a complete copy of the original code is
24319 made, with appropriate substitutions of formals by actuals.
24320
24321 It is not possible to refer to the original generic entities in
24322 @code{GDB}, but it is always possible to debug a particular instance of
24323 a generic, by using the appropriate expanded names. For example, if we have
24324
24325 @smallexample @c ada
24326 @group
24327 @cartouche
24328 procedure g is
24329
24330    generic package k is
24331       procedure kp (v1 : in out integer);
24332    end k;
24333
24334    package body k is
24335       procedure kp (v1 : in out integer) is
24336       begin
24337          v1 := v1 + 1;
24338       end kp;
24339    end k;
24340
24341    package k1 is new k;
24342    package k2 is new k;
24343
24344    var : integer := 1;
24345
24346 begin
24347    k1.kp (var);
24348    k2.kp (var);
24349    k1.kp (var);
24350    k2.kp (var);
24351 end;
24352 @end cartouche
24353 @end group
24354 @end smallexample
24355
24356 @noindent
24357 Then to break on a call to procedure kp in the k2 instance, simply
24358 use the command:
24359
24360 @smallexample
24361 (gdb) break g.k2.kp
24362 @end smallexample
24363
24364 @noindent
24365 When the breakpoint occurs, you can step through the code of the
24366 instance in the normal manner and examine the values of local variables, as for
24367 other units.
24368
24369 @node GNAT Abnormal Termination or Failure to Terminate
24370 @section GNAT Abnormal Termination or Failure to Terminate
24371 @cindex GNAT Abnormal Termination or Failure to Terminate
24372
24373 @noindent
24374 When presented with programs that contain serious errors in syntax
24375 or semantics,
24376 GNAT may on rare occasions  experience problems in operation, such
24377 as aborting with a
24378 segmentation fault or illegal memory access, raising an internal
24379 exception, terminating abnormally, or failing to terminate at all.
24380 In such cases, you can activate
24381 various features of GNAT that can help you pinpoint the construct in your
24382 program that is the likely source of the problem.
24383
24384 The following strategies are presented in increasing order of
24385 difficulty, corresponding to your experience in using GNAT and your
24386 familiarity with compiler internals.
24387
24388 @enumerate
24389 @item
24390 Run @command{gcc} with the @option{-gnatf}. This first
24391 switch causes all errors on a given line to be reported. In its absence,
24392 only the first error on a line is displayed.
24393
24394 The @option{-gnatdO} switch causes errors to be displayed as soon as they
24395 are encountered, rather than after compilation is terminated. If GNAT
24396 terminates prematurely or goes into an infinite loop, the last error
24397 message displayed may help to pinpoint the culprit.
24398
24399 @item
24400 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
24401 mode, @command{gcc} produces ongoing information about the progress of the
24402 compilation and provides the name of each procedure as code is
24403 generated. This switch allows you to find which Ada procedure was being
24404 compiled when it encountered a code generation problem.
24405
24406 @item
24407 @cindex @option{-gnatdc} switch
24408 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
24409 switch that does for the front-end what @option{^-v^VERBOSE^} does
24410 for the back end. The system prints the name of each unit,
24411 either a compilation unit or nested unit, as it is being analyzed.
24412 @item
24413 Finally, you can start
24414 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
24415 front-end of GNAT, and can be run independently (normally it is just
24416 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
24417 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
24418 @code{where} command is the first line of attack; the variable
24419 @code{lineno} (seen by @code{print lineno}), used by the second phase of
24420 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
24421 which the execution stopped, and @code{input_file name} indicates the name of
24422 the source file.
24423 @end enumerate
24424
24425 @node Naming Conventions for GNAT Source Files
24426 @section Naming Conventions for GNAT Source Files
24427
24428 @noindent
24429 In order to examine the workings of the GNAT system, the following
24430 brief description of its organization may be helpful:
24431
24432 @itemize @bullet
24433 @item
24434 Files with prefix @file{^sc^SC^} contain the lexical scanner.
24435
24436 @item
24437 All files prefixed with @file{^par^PAR^} are components of the parser. The
24438 numbers correspond to chapters of the Ada Reference Manual. For example,
24439 parsing of select statements can be found in @file{par-ch9.adb}.
24440
24441 @item
24442 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
24443 numbers correspond to chapters of the Ada standard. For example, all
24444 issues involving context clauses can be found in @file{sem_ch10.adb}. In
24445 addition, some features of the language require sufficient special processing
24446 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
24447 dynamic dispatching, etc.
24448
24449 @item
24450 All files prefixed with @file{^exp^EXP^} perform normalization and
24451 expansion of the intermediate representation (abstract syntax tree, or AST).
24452 these files use the same numbering scheme as the parser and semantics files.
24453 For example, the construction of record initialization procedures is done in
24454 @file{exp_ch3.adb}.
24455
24456 @item
24457 The files prefixed with @file{^bind^BIND^} implement the binder, which
24458 verifies the consistency of the compilation, determines an order of
24459 elaboration, and generates the bind file.
24460
24461 @item
24462 The files @file{atree.ads} and @file{atree.adb} detail the low-level
24463 data structures used by the front-end.
24464
24465 @item
24466 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
24467 the abstract syntax tree as produced by the parser.
24468
24469 @item
24470 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
24471 all entities, computed during semantic analysis.
24472
24473 @item
24474 Library management issues are dealt with in files with prefix
24475 @file{^lib^LIB^}.
24476
24477 @item
24478 @findex Ada
24479 @cindex Annex A
24480 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
24481 defined in Annex A.
24482
24483 @item
24484 @findex Interfaces
24485 @cindex Annex B
24486 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
24487 defined in Annex B.
24488
24489 @item
24490 @findex System
24491 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
24492 both language-defined children and GNAT run-time routines.
24493
24494 @item
24495 @findex GNAT
24496 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
24497 general-purpose packages, fully documented in their specs. All
24498 the other @file{.c} files are modifications of common @command{gcc} files.
24499 @end itemize
24500
24501 @node Getting Internal Debugging Information
24502 @section Getting Internal Debugging Information
24503
24504 @noindent
24505 Most compilers have internal debugging switches and modes. GNAT
24506 does also, except GNAT internal debugging switches and modes are not
24507 secret. A summary and full description of all the compiler and binder
24508 debug flags are in the file @file{debug.adb}. You must obtain the
24509 sources of the compiler to see the full detailed effects of these flags.
24510
24511 The switches that print the source of the program (reconstructed from
24512 the internal tree) are of general interest for user programs, as are the
24513 options to print
24514 the full internal tree, and the entity table (the symbol table
24515 information). The reconstructed source provides a readable version of the
24516 program after the front-end has completed analysis and  expansion,
24517 and is useful when studying the performance of specific constructs.
24518 For example, constraint checks are indicated, complex aggregates
24519 are replaced with loops and assignments, and tasking primitives
24520 are replaced with run-time calls.
24521
24522 @node Stack Traceback
24523 @section Stack Traceback
24524 @cindex traceback
24525 @cindex stack traceback
24526 @cindex stack unwinding
24527
24528 @noindent
24529 Traceback is a mechanism to display the sequence of subprogram calls that
24530 leads to a specified execution point in a program. Often (but not always)
24531 the execution point is an instruction at which an exception has been raised.
24532 This mechanism is also known as @i{stack unwinding} because it obtains
24533 its information by scanning the run-time stack and recovering the activation
24534 records of all active subprograms. Stack unwinding is one of the most
24535 important tools for program debugging.
24536
24537 The first entry stored in traceback corresponds to the deepest calling level,
24538 that is to say the subprogram currently executing the instruction
24539 from which we want to obtain the traceback.
24540
24541 Note that there is no runtime performance penalty when stack traceback
24542 is enabled, and no exception is raised during program execution.
24543
24544 @menu
24545 * Non-Symbolic Traceback::
24546 * Symbolic Traceback::
24547 @end menu
24548
24549 @node Non-Symbolic Traceback
24550 @subsection Non-Symbolic Traceback
24551 @cindex traceback, non-symbolic
24552
24553 @noindent
24554 Note: this feature is not supported on all platforms. See
24555 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
24556 platforms.
24557
24558 @menu
24559 * Tracebacks From an Unhandled Exception::
24560 * Tracebacks From Exception Occurrences (non-symbolic)::
24561 * Tracebacks From Anywhere in a Program (non-symbolic)::
24562 @end menu
24563
24564 @node Tracebacks From an Unhandled Exception
24565 @subsubsection Tracebacks From an Unhandled Exception
24566
24567 @noindent
24568 A runtime non-symbolic traceback is a list of addresses of call instructions.
24569 To enable this feature you must use the @option{-E}
24570 @code{gnatbind}'s option. With this option a stack traceback is stored as part
24571 of exception information. You can retrieve this information using the
24572 @code{addr2line} tool.
24573
24574 Here is a simple example:
24575
24576 @smallexample @c ada
24577 @cartouche
24578 procedure STB is
24579
24580    procedure P1 is
24581    begin
24582       raise Constraint_Error;
24583    end P1;
24584
24585    procedure P2 is
24586    begin
24587       P1;
24588    end P2;
24589
24590 begin
24591    P2;
24592 end STB;
24593 @end cartouche
24594 @end smallexample
24595
24596 @smallexample
24597 $ gnatmake stb -bargs -E
24598 $ stb
24599
24600 Execution terminated by unhandled exception
24601 Exception name: CONSTRAINT_ERROR
24602 Message: stb.adb:5
24603 Call stack traceback locations:
24604 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24605 @end smallexample
24606
24607 @noindent
24608 As we see the traceback lists a sequence of addresses for the unhandled
24609 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
24610 guess that this exception come from procedure P1. To translate these
24611 addresses into the source lines where the calls appear, the
24612 @code{addr2line} tool, described below, is invaluable. The use of this tool
24613 requires the program to be compiled with debug information.
24614
24615 @smallexample
24616 $ gnatmake -g stb -bargs -E
24617 $ stb
24618
24619 Execution terminated by unhandled exception
24620 Exception name: CONSTRAINT_ERROR
24621 Message: stb.adb:5
24622 Call stack traceback locations:
24623 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24624
24625 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
24626    0x4011f1 0x77e892a4
24627
24628 00401373 at d:/stb/stb.adb:5
24629 0040138B at d:/stb/stb.adb:10
24630 0040139C at d:/stb/stb.adb:14
24631 00401335 at d:/stb/b~stb.adb:104
24632 004011C4 at /build/@dots{}/crt1.c:200
24633 004011F1 at /build/@dots{}/crt1.c:222
24634 77E892A4 in ?? at ??:0
24635 @end smallexample
24636
24637 @noindent
24638 The @code{addr2line} tool has several other useful options:
24639
24640 @table @code
24641 @item --functions
24642 to get the function name corresponding to any location
24643
24644 @item --demangle=gnat
24645 to use the gnat decoding mode for the function names. Note that
24646 for binutils version 2.9.x the option is simply @option{--demangle}.
24647 @end table
24648
24649 @smallexample
24650 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
24651    0x40139c 0x401335 0x4011c4 0x4011f1
24652
24653 00401373 in stb.p1 at d:/stb/stb.adb:5
24654 0040138B in stb.p2 at d:/stb/stb.adb:10
24655 0040139C in stb at d:/stb/stb.adb:14
24656 00401335 in main at d:/stb/b~stb.adb:104
24657 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
24658 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
24659 @end smallexample
24660
24661 @noindent
24662 From this traceback we can see that the exception was raised in
24663 @file{stb.adb} at line 5, which was reached from a procedure call in
24664 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
24665 which contains the call to the main program.
24666 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
24667 and the output will vary from platform to platform.
24668
24669 It is also possible to use @code{GDB} with these traceback addresses to debug
24670 the program. For example, we can break at a given code location, as reported
24671 in the stack traceback:
24672
24673 @smallexample
24674 $ gdb -nw stb
24675 @ifclear vms
24676 @noindent
24677 Furthermore, this feature is not implemented inside Windows DLL. Only
24678 the non-symbolic traceback is reported in this case.
24679 @end ifclear
24680
24681 (gdb) break *0x401373
24682 Breakpoint 1 at 0x401373: file stb.adb, line 5.
24683 @end smallexample
24684
24685 @noindent
24686 It is important to note that the stack traceback addresses
24687 do not change when debug information is included. This is particularly useful
24688 because it makes it possible to release software without debug information (to
24689 minimize object size), get a field report that includes a stack traceback
24690 whenever an internal bug occurs, and then be able to retrieve the sequence
24691 of calls with the same program compiled with debug information.
24692
24693 @node Tracebacks From Exception Occurrences (non-symbolic)
24694 @subsubsection Tracebacks From Exception Occurrences
24695
24696 @noindent
24697 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
24698 The stack traceback is attached to the exception information string, and can
24699 be retrieved in an exception handler within the Ada program, by means of the
24700 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
24701
24702 @smallexample @c ada
24703 with Ada.Text_IO;
24704 with Ada.Exceptions;
24705
24706 procedure STB is
24707
24708    use Ada;
24709    use Ada.Exceptions;
24710
24711    procedure P1 is
24712       K : Positive := 1;
24713    begin
24714       K := K - 1;
24715    exception
24716       when E : others =>
24717          Text_IO.Put_Line (Exception_Information (E));
24718    end P1;
24719
24720    procedure P2 is
24721    begin
24722       P1;
24723    end P2;
24724
24725 begin
24726    P2;
24727 end STB;
24728 @end smallexample
24729
24730 @noindent
24731 This program will output:
24732
24733 @smallexample
24734 $ stb
24735
24736 Exception name: CONSTRAINT_ERROR
24737 Message: stb.adb:12
24738 Call stack traceback locations:
24739 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
24740 @end smallexample
24741
24742 @node Tracebacks From Anywhere in a Program (non-symbolic)
24743 @subsubsection Tracebacks From Anywhere in a Program
24744
24745 @noindent
24746 It is also possible to retrieve a stack traceback from anywhere in a
24747 program. For this you need to
24748 use the @code{GNAT.Traceback} API. This package includes a procedure called
24749 @code{Call_Chain} that computes a complete stack traceback, as well as useful
24750 display procedures described below. It is not necessary to use the
24751 @option{-E gnatbind} option in this case, because the stack traceback mechanism
24752 is invoked explicitly.
24753
24754 @noindent
24755 In the following example we compute a traceback at a specific location in
24756 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
24757 convert addresses to strings:
24758
24759 @smallexample @c ada
24760 with Ada.Text_IO;
24761 with GNAT.Traceback;
24762 with GNAT.Debug_Utilities;
24763
24764 procedure STB is
24765
24766    use Ada;
24767    use GNAT;
24768    use GNAT.Traceback;
24769
24770    procedure P1 is
24771       TB  : Tracebacks_Array (1 .. 10);
24772       --  We are asking for a maximum of 10 stack frames.
24773       Len : Natural;
24774       --  Len will receive the actual number of stack frames returned.
24775    begin
24776       Call_Chain (TB, Len);
24777
24778       Text_IO.Put ("In STB.P1 : ");
24779
24780       for K in 1 .. Len loop
24781          Text_IO.Put (Debug_Utilities.Image (TB (K)));
24782          Text_IO.Put (' ');
24783       end loop;
24784
24785       Text_IO.New_Line;
24786    end P1;
24787
24788    procedure P2 is
24789    begin
24790       P1;
24791    end P2;
24792
24793 begin
24794    P2;
24795 end STB;
24796 @end smallexample
24797
24798 @smallexample
24799 $ gnatmake -g stb
24800 $ stb
24801
24802 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
24803 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
24804 @end smallexample
24805
24806 @noindent
24807 You can then get further information by invoking the @code{addr2line}
24808 tool as described earlier (note that the hexadecimal addresses
24809 need to be specified in C format, with a leading ``0x'').
24810
24811 @node Symbolic Traceback
24812 @subsection Symbolic Traceback
24813 @cindex traceback, symbolic
24814
24815 @noindent
24816 A symbolic traceback is a stack traceback in which procedure names are
24817 associated with each code location.
24818
24819 @noindent
24820 Note that this feature is not supported on all platforms. See
24821 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
24822 list of currently supported platforms.
24823
24824 @noindent
24825 Note that the symbolic traceback requires that the program be compiled
24826 with debug information. If it is not compiled with debug information
24827 only the non-symbolic information will be valid.
24828
24829 @menu
24830 * Tracebacks From Exception Occurrences (symbolic)::
24831 * Tracebacks From Anywhere in a Program (symbolic)::
24832 @end menu
24833
24834 @node Tracebacks From Exception Occurrences (symbolic)
24835 @subsubsection Tracebacks From Exception Occurrences
24836
24837 @smallexample @c ada
24838 with Ada.Text_IO;
24839 with GNAT.Traceback.Symbolic;
24840
24841 procedure STB is
24842
24843    procedure P1 is
24844    begin
24845       raise Constraint_Error;
24846    end P1;
24847
24848    procedure P2 is
24849    begin
24850       P1;
24851    end P2;
24852
24853    procedure P3 is
24854    begin
24855       P2;
24856    end P3;
24857
24858 begin
24859    P3;
24860 exception
24861    when E : others =>
24862       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
24863 end STB;
24864 @end smallexample
24865
24866 @smallexample
24867 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
24868 $ stb
24869
24870 0040149F in stb.p1 at stb.adb:8
24871 004014B7 in stb.p2 at stb.adb:13
24872 004014CF in stb.p3 at stb.adb:18
24873 004015DD in ada.stb at stb.adb:22
24874 00401461 in main at b~stb.adb:168
24875 004011C4 in __mingw_CRTStartup at crt1.c:200
24876 004011F1 in mainCRTStartup at crt1.c:222
24877 77E892A4 in ?? at ??:0
24878 @end smallexample
24879
24880 @noindent
24881 In the above example the ``.\'' syntax in the @command{gnatmake} command
24882 is currently required by @command{addr2line} for files that are in
24883 the current working directory.
24884 Moreover, the exact sequence of linker options may vary from platform
24885 to platform.
24886 The above @option{-largs} section is for Windows platforms. By contrast,
24887 under Unix there is no need for the @option{-largs} section.
24888 Differences across platforms are due to details of linker implementation.
24889
24890 @node Tracebacks From Anywhere in a Program (symbolic)
24891 @subsubsection Tracebacks From Anywhere in a Program
24892
24893 @noindent
24894 It is possible to get a symbolic stack traceback
24895 from anywhere in a program, just as for non-symbolic tracebacks.
24896 The first step is to obtain a non-symbolic
24897 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
24898 information. Here is an example:
24899
24900 @smallexample @c ada
24901 with Ada.Text_IO;
24902 with GNAT.Traceback;
24903 with GNAT.Traceback.Symbolic;
24904
24905 procedure STB is
24906
24907    use Ada;
24908    use GNAT.Traceback;
24909    use GNAT.Traceback.Symbolic;
24910
24911    procedure P1 is
24912       TB  : Tracebacks_Array (1 .. 10);
24913       --  We are asking for a maximum of 10 stack frames.
24914       Len : Natural;
24915       --  Len will receive the actual number of stack frames returned.
24916    begin
24917       Call_Chain (TB, Len);
24918       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
24919    end P1;
24920
24921    procedure P2 is
24922    begin
24923       P1;
24924    end P2;
24925
24926 begin
24927    P2;
24928 end STB;
24929 @end smallexample
24930
24931 @c ******************************
24932 @ifset vms
24933 @node Compatibility with HP Ada
24934 @chapter Compatibility with HP Ada
24935 @cindex Compatibility
24936
24937 @noindent
24938 @cindex DEC Ada
24939 @cindex HP Ada
24940 @cindex Compatibility between GNAT and HP Ada
24941 This chapter compares HP Ada (formerly known as ``DEC Ada'')
24942 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
24943 GNAT is highly compatible
24944 with HP Ada, and it should generally be straightforward to port code
24945 from the HP Ada environment to GNAT. However, there are a few language
24946 and implementation differences of which the user must be aware. These
24947 differences are discussed in this chapter. In
24948 addition, the operating environment and command structure for the
24949 compiler are different, and these differences are also discussed.
24950
24951 For further details on these and other compatibility issues,
24952 see Appendix E of the HP publication
24953 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
24954
24955 Except where otherwise indicated, the description of GNAT for OpenVMS
24956 applies to both the Alpha and I64 platforms.
24957
24958 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
24959 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24960
24961 The discussion in this chapter addresses specifically the implementation
24962 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
24963 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
24964 GNAT always follows the Alpha implementation.
24965
24966 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
24967 attributes are recognized, although only a subset of them can sensibly
24968 be implemented.  The description of pragmas in
24969 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
24970 indicates whether or not they are applicable to non-VMS systems.
24971
24972 @menu
24973 * Ada Language Compatibility::
24974 * Differences in the Definition of Package System::
24975 * Language-Related Features::
24976 * The Package STANDARD::
24977 * The Package SYSTEM::
24978 * Tasking and Task-Related Features::
24979 * Pragmas and Pragma-Related Features::
24980 * Library of Predefined Units::
24981 * Bindings::
24982 * Main Program Definition::
24983 * Implementation-Defined Attributes::
24984 * Compiler and Run-Time Interfacing::
24985 * Program Compilation and Library Management::
24986 * Input-Output::
24987 * Implementation Limits::
24988 * Tools and Utilities::
24989 @end menu
24990
24991 @node Ada Language Compatibility
24992 @section Ada Language Compatibility
24993
24994 @noindent
24995 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
24996 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
24997 with Ada 83, and therefore Ada 83 programs will compile
24998 and run under GNAT with
24999 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
25000 provides details on specific incompatibilities.
25001
25002 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
25003 as well as the pragma @code{ADA_83}, to force the compiler to
25004 operate in Ada 83 mode. This mode does not guarantee complete
25005 conformance to Ada 83, but in practice is sufficient to
25006 eliminate most sources of incompatibilities.
25007 In particular, it eliminates the recognition of the
25008 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
25009 in Ada 83 programs is legal, and handles the cases of packages
25010 with optional bodies, and generics that instantiate unconstrained
25011 types without the use of @code{(<>)}.
25012
25013 @node Differences in the Definition of Package System
25014 @section Differences in the Definition of Package @code{System}
25015
25016 @noindent
25017 An Ada compiler is allowed to add
25018 implementation-dependent declarations to package @code{System}.
25019 In normal mode,
25020 GNAT does not take advantage of this permission, and the version of
25021 @code{System} provided by GNAT exactly matches that defined in the Ada
25022 Reference Manual.
25023
25024 However, HP Ada adds an extensive set of declarations to package
25025 @code{System},
25026 as fully documented in the HP Ada manuals. To minimize changes required
25027 for programs that make use of these extensions, GNAT provides the pragma
25028 @code{Extend_System} for extending the definition of package System. By using:
25029 @cindex pragma @code{Extend_System}
25030 @cindex @code{Extend_System} pragma
25031
25032 @smallexample @c ada
25033 @group
25034 @cartouche
25035 pragma Extend_System (Aux_DEC);
25036 @end cartouche
25037 @end group
25038 @end smallexample
25039
25040 @noindent
25041 the set of definitions in @code{System} is extended to include those in
25042 package @code{System.Aux_DEC}.
25043 @cindex @code{System.Aux_DEC} package
25044 @cindex @code{Aux_DEC} package (child of @code{System})
25045 These definitions are incorporated directly into package @code{System},
25046 as though they had been declared there. For a
25047 list of the declarations added, see the spec of this package,
25048 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
25049 @cindex @file{s-auxdec.ads} file
25050 The pragma @code{Extend_System} is a configuration pragma, which means that
25051 it can be placed in the file @file{gnat.adc}, so that it will automatically
25052 apply to all subsequent compilations. See @ref{Configuration Pragmas},
25053 for further details.
25054
25055 An alternative approach that avoids the use of the non-standard
25056 @code{Extend_System} pragma is to add a context clause to the unit that
25057 references these facilities:
25058
25059 @smallexample @c ada
25060 @cartouche
25061 with System.Aux_DEC;
25062 use  System.Aux_DEC;
25063 @end cartouche
25064 @end smallexample
25065
25066 @noindent
25067 The effect is not quite semantically identical to incorporating
25068 the declarations directly into package @code{System},
25069 but most programs will not notice a difference
25070 unless they use prefix notation (e.g.@: @code{System.Integer_8})
25071 to reference the entities directly in package @code{System}.
25072 For units containing such references,
25073 the prefixes must either be removed, or the pragma @code{Extend_System}
25074 must be used.
25075
25076 @node Language-Related Features
25077 @section Language-Related Features
25078
25079 @noindent
25080 The following sections highlight differences in types,
25081 representations of types, operations, alignment, and
25082 related topics.
25083
25084 @menu
25085 * Integer Types and Representations::
25086 * Floating-Point Types and Representations::
25087 * Pragmas Float_Representation and Long_Float::
25088 * Fixed-Point Types and Representations::
25089 * Record and Array Component Alignment::
25090 * Address Clauses::
25091 * Other Representation Clauses::
25092 @end menu
25093
25094 @node Integer Types and Representations
25095 @subsection Integer Types and Representations
25096
25097 @noindent
25098 The set of predefined integer types is identical in HP Ada and GNAT.
25099 Furthermore the representation of these integer types is also identical,
25100 including the capability of size clauses forcing biased representation.
25101
25102 In addition,
25103 HP Ada for OpenVMS Alpha systems has defined the
25104 following additional integer types in package @code{System}:
25105
25106 @itemize @bullet
25107
25108 @item
25109 @code{INTEGER_8}
25110
25111 @item
25112 @code{INTEGER_16}
25113
25114 @item
25115 @code{INTEGER_32}
25116
25117 @item
25118 @code{INTEGER_64}
25119
25120 @item
25121 @code{LARGEST_INTEGER}
25122 @end itemize
25123
25124 @noindent
25125 In GNAT, the first four of these types may be obtained from the
25126 standard Ada package @code{Interfaces}.
25127 Alternatively, by use of the pragma @code{Extend_System}, identical
25128 declarations can be referenced directly in package @code{System}.
25129 On both GNAT and HP Ada, the maximum integer size is 64 bits.
25130
25131 @node Floating-Point Types and Representations
25132 @subsection Floating-Point Types and Representations
25133 @cindex Floating-Point types
25134
25135 @noindent
25136 The set of predefined floating-point types is identical in HP Ada and GNAT.
25137 Furthermore the representation of these floating-point
25138 types is also identical. One important difference is that the default
25139 representation for HP Ada is @code{VAX_Float}, but the default representation
25140 for GNAT is IEEE.
25141
25142 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
25143 pragma @code{Float_Representation} as described in the HP Ada
25144 documentation.
25145 For example, the declarations:
25146
25147 @smallexample @c ada
25148 @cartouche
25149 type F_Float is digits 6;
25150 pragma Float_Representation (VAX_Float, F_Float);
25151 @end cartouche
25152 @end smallexample
25153
25154 @noindent
25155 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
25156 format.
25157 This set of declarations actually appears in @code{System.Aux_DEC},
25158 which contains
25159 the full set of additional floating-point declarations provided in
25160 the HP Ada version of package @code{System}.
25161 This and similar declarations may be accessed in a user program
25162 by using pragma @code{Extend_System}. The use of this
25163 pragma, and the related pragma @code{Long_Float} is described in further
25164 detail in the following section.
25165
25166 @node Pragmas Float_Representation and Long_Float
25167 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
25168
25169 @noindent
25170 HP Ada provides the pragma @code{Float_Representation}, which
25171 acts as a program library switch to allow control over
25172 the internal representation chosen for the predefined
25173 floating-point types declared in the package @code{Standard}.
25174 The format of this pragma is as follows:
25175
25176 @smallexample @c ada
25177 @cartouche
25178 pragma Float_Representation(VAX_Float | IEEE_Float);
25179 @end cartouche
25180 @end smallexample
25181
25182 @noindent
25183 This pragma controls the representation of floating-point
25184 types as follows:
25185
25186 @itemize @bullet
25187 @item
25188 @code{VAX_Float} specifies that floating-point
25189 types are represented by default with the VAX system hardware types
25190 @code{F-floating}, @code{D-floating}, @code{G-floating}.
25191 Note that the @code{H-floating}
25192 type was available only on VAX systems, and is not available
25193 in either HP Ada or GNAT.
25194
25195 @item
25196 @code{IEEE_Float} specifies that floating-point
25197 types are represented by default with the IEEE single and
25198 double floating-point types.
25199 @end itemize
25200
25201 @noindent
25202 GNAT provides an identical implementation of the pragma
25203 @code{Float_Representation}, except that it functions as a
25204 configuration pragma. Note that the
25205 notion of configuration pragma corresponds closely to the
25206 HP Ada notion of a program library switch.
25207
25208 When no pragma is used in GNAT, the default is @code{IEEE_Float},
25209 which is different
25210 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
25211 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
25212 advisable to change the format of numbers passed to standard library
25213 routines, and if necessary explicit type conversions may be needed.
25214
25215 The use of @code{IEEE_Float} is recommended in GNAT since it is more
25216 efficient, and (given that it conforms to an international standard)
25217 potentially more portable.
25218 The situation in which @code{VAX_Float} may be useful is in interfacing
25219 to existing code and data that expect the use of @code{VAX_Float}.
25220 In such a situation use the predefined @code{VAX_Float}
25221 types in package @code{System}, as extended by
25222 @code{Extend_System}. For example, use @code{System.F_Float}
25223 to specify the 32-bit @code{F-Float} format.
25224
25225 @noindent
25226 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
25227 to allow control over the internal representation chosen
25228 for the predefined type @code{Long_Float} and for floating-point
25229 type declarations with digits specified in the range 7 .. 15.
25230 The format of this pragma is as follows:
25231
25232 @smallexample @c ada
25233 @cartouche
25234 pragma Long_Float (D_FLOAT | G_FLOAT);
25235 @end cartouche
25236 @end smallexample
25237
25238 @node Fixed-Point Types and Representations
25239 @subsection Fixed-Point Types and Representations
25240
25241 @noindent
25242 On HP Ada for OpenVMS Alpha systems, rounding is
25243 away from zero for both positive and negative numbers.
25244 Therefore, @code{+0.5} rounds to @code{1},
25245 and @code{-0.5} rounds to @code{-1}.
25246
25247 On GNAT the results of operations
25248 on fixed-point types are in accordance with the Ada
25249 rules. In particular, results of operations on decimal
25250 fixed-point types are truncated.
25251
25252 @node Record and Array Component Alignment
25253 @subsection Record and Array Component Alignment
25254
25255 @noindent
25256 On HP Ada for OpenVMS Alpha, all non-composite components
25257 are aligned on natural boundaries. For example, 1-byte
25258 components are aligned on byte boundaries, 2-byte
25259 components on 2-byte boundaries, 4-byte components on 4-byte
25260 byte boundaries, and so on. The OpenVMS Alpha hardware
25261 runs more efficiently with naturally aligned data.
25262
25263 On GNAT, alignment rules are compatible
25264 with HP Ada for OpenVMS Alpha.
25265
25266 @node Address Clauses
25267 @subsection Address Clauses
25268
25269 @noindent
25270 In HP Ada and GNAT, address clauses are supported for
25271 objects and imported subprograms.
25272 The predefined type @code{System.Address} is a private type
25273 in both compilers on Alpha OpenVMS, with the same representation
25274 (it is simply a machine pointer). Addition, subtraction, and comparison
25275 operations are available in the standard Ada package
25276 @code{System.Storage_Elements}, or in package @code{System}
25277 if it is extended to include @code{System.Aux_DEC} using a
25278 pragma @code{Extend_System} as previously described.
25279
25280 Note that code that @code{with}'s both this extended package @code{System}
25281 and the package @code{System.Storage_Elements} should not @code{use}
25282 both packages, or ambiguities will result. In general it is better
25283 not to mix these two sets of facilities. The Ada package was
25284 designed specifically to provide the kind of features that HP Ada
25285 adds directly to package @code{System}.
25286
25287 The type @code{System.Address} is a 64-bit integer type in GNAT for
25288 I64 OpenVMS.  For more information,
25289 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
25290
25291 GNAT is compatible with HP Ada in its handling of address
25292 clauses, except for some limitations in
25293 the form of address clauses for composite objects with
25294 initialization. Such address clauses are easily replaced
25295 by the use of an explicitly-defined constant as described
25296 in the Ada Reference Manual (13.1(22)). For example, the sequence
25297 of declarations:
25298
25299 @smallexample @c ada
25300 @cartouche
25301 X, Y : Integer := Init_Func;
25302 Q : String (X .. Y) := "abc";
25303 @dots{}
25304 for Q'Address use Compute_Address;
25305 @end cartouche
25306 @end smallexample
25307
25308 @noindent
25309 will be rejected by GNAT, since the address cannot be computed at the time
25310 that @code{Q} is declared. To achieve the intended effect, write instead:
25311
25312 @smallexample @c ada
25313 @group
25314 @cartouche
25315 X, Y : Integer := Init_Func;
25316 Q_Address : constant Address := Compute_Address;
25317 Q : String (X .. Y) := "abc";
25318 @dots{}
25319 for Q'Address use Q_Address;
25320 @end cartouche
25321 @end group
25322 @end smallexample
25323
25324 @noindent
25325 which will be accepted by GNAT (and other Ada compilers), and is also
25326 compatible with Ada 83. A fuller description of the restrictions
25327 on address specifications is found in @ref{Top, GNAT Reference Manual,
25328 About This Guide, gnat_rm, GNAT Reference Manual}.
25329
25330 @node Other Representation Clauses
25331 @subsection Other Representation Clauses
25332
25333 @noindent
25334 GNAT implements in a compatible manner all the representation
25335 clauses supported by HP Ada. In addition, GNAT
25336 implements the representation clause forms that were introduced in Ada 95,
25337 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
25338
25339 @node The Package STANDARD
25340 @section The Package @code{STANDARD}
25341
25342 @noindent
25343 The package @code{STANDARD}, as implemented by HP Ada, is fully
25344 described in the @cite{Ada Reference Manual} and in the
25345 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
25346 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
25347
25348 In addition, HP Ada supports the Latin-1 character set in
25349 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
25350 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
25351 the type @code{WIDE_CHARACTER}.
25352
25353 The floating-point types supported by GNAT are those
25354 supported by HP Ada, but the defaults are different, and are controlled by
25355 pragmas. See @ref{Floating-Point Types and Representations}, for details.
25356
25357 @node The Package SYSTEM
25358 @section The Package @code{SYSTEM}
25359
25360 @noindent
25361 HP Ada provides a specific version of the package
25362 @code{SYSTEM} for each platform on which the language is implemented.
25363 For the complete spec of the package @code{SYSTEM}, see
25364 Appendix F of the @cite{HP Ada Language Reference Manual}.
25365
25366 On HP Ada, the package @code{SYSTEM} includes the following conversion
25367 functions:
25368 @itemize @bullet
25369 @item @code{TO_ADDRESS(INTEGER)}
25370
25371 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
25372
25373 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
25374
25375 @item @code{TO_INTEGER(ADDRESS)}
25376
25377 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
25378
25379 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
25380 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
25381 @end itemize
25382
25383 @noindent
25384 By default, GNAT supplies a version of @code{SYSTEM} that matches
25385 the definition given in the @cite{Ada Reference Manual}.
25386 This
25387 is a subset of the HP system definitions, which is as
25388 close as possible to the original definitions. The only difference
25389 is that the definition of @code{SYSTEM_NAME} is different:
25390
25391 @smallexample @c ada
25392 @cartouche
25393 type Name is (SYSTEM_NAME_GNAT);
25394 System_Name : constant Name := SYSTEM_NAME_GNAT;
25395 @end cartouche
25396 @end smallexample
25397
25398 @noindent
25399 Also, GNAT adds the Ada declarations for
25400 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
25401
25402 However, the use of the following pragma causes GNAT
25403 to extend the definition of package @code{SYSTEM} so that it
25404 encompasses the full set of HP-specific extensions,
25405 including the functions listed above:
25406
25407 @smallexample @c ada
25408 @cartouche
25409 pragma Extend_System (Aux_DEC);
25410 @end cartouche
25411 @end smallexample
25412
25413 @noindent
25414 The pragma @code{Extend_System} is a configuration pragma that
25415 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
25416 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
25417
25418 HP Ada does not allow the recompilation of the package
25419 @code{SYSTEM}. Instead HP Ada provides several pragmas
25420 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
25421 to modify values in the package @code{SYSTEM}.
25422 On OpenVMS Alpha systems, the pragma
25423 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
25424 its single argument.
25425
25426 GNAT does permit the recompilation of package @code{SYSTEM} using
25427 the special switch @option{-gnatg}, and this switch can be used if
25428 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
25429 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
25430 or @code{MEMORY_SIZE} by any other means.
25431
25432 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
25433 enumeration literal @code{SYSTEM_NAME_GNAT}.
25434
25435 The definitions provided by the use of
25436
25437 @smallexample @c ada
25438 pragma Extend_System (AUX_Dec);
25439 @end smallexample
25440
25441 @noindent
25442 are virtually identical to those provided by the HP Ada 83 package
25443 @code{SYSTEM}. One important difference is that the name of the
25444 @code{TO_ADDRESS}
25445 function for type @code{UNSIGNED_LONGWORD} is changed to
25446 @code{TO_ADDRESS_LONG}.
25447 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
25448 discussion of why this change was necessary.
25449
25450 @noindent
25451 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
25452 is in fact
25453 an extension to Ada 83 not strictly compatible with the reference manual.
25454 GNAT, in order to be exactly compatible with the standard,
25455 does not provide this capability. In HP Ada 83, the
25456 point of this definition is to deal with a call like:
25457
25458 @smallexample @c ada
25459 TO_ADDRESS (16#12777#);
25460 @end smallexample
25461
25462 @noindent
25463 Normally, according to Ada 83 semantics, one would expect this to be
25464 ambiguous, since it matches both the @code{INTEGER} and
25465 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
25466 However, in HP Ada 83, there is no ambiguity, since the
25467 definition using @i{universal_integer} takes precedence.
25468
25469 In GNAT, since the version with @i{universal_integer} cannot be supplied,
25470 it is
25471 not possible to be 100% compatible. Since there are many programs using
25472 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
25473 GNAT was
25474 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
25475 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
25476
25477 @smallexample @c ada
25478 function To_Address (X : Integer) return Address;
25479 pragma Pure_Function (To_Address);
25480
25481 function To_Address_Long (X : Unsigned_Longword) return Address;
25482 pragma Pure_Function (To_Address_Long);
25483 @end smallexample
25484
25485 @noindent
25486 This means that programs using @code{TO_ADDRESS} for
25487 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
25488
25489 @node Tasking and Task-Related Features
25490 @section Tasking and Task-Related Features
25491
25492 @noindent
25493 This section compares the treatment of tasking in GNAT
25494 and in HP Ada for OpenVMS Alpha.
25495 The GNAT description applies to both Alpha and I64 OpenVMS.
25496 For detailed information on tasking in
25497 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
25498 relevant run-time reference manual.
25499
25500 @menu
25501 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
25502 * Assigning Task IDs::
25503 * Task IDs and Delays::
25504 * Task-Related Pragmas::
25505 * Scheduling and Task Priority::
25506 * The Task Stack::
25507 * External Interrupts::
25508 @end menu
25509
25510 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25511 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25512
25513 @noindent
25514 On OpenVMS Alpha systems, each Ada task (except a passive
25515 task) is implemented as a single stream of execution
25516 that is created and managed by the kernel. On these
25517 systems, HP Ada tasking support is based on DECthreads,
25518 an implementation of the POSIX standard for threads.
25519
25520 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
25521 code that calls DECthreads routines can be used together.
25522 The interaction between Ada tasks and DECthreads routines
25523 can have some benefits. For example when on OpenVMS Alpha,
25524 HP Ada can call C code that is already threaded.
25525
25526 GNAT uses the facilities of DECthreads,
25527 and Ada tasks are mapped to threads.
25528
25529 @node Assigning Task IDs
25530 @subsection Assigning Task IDs
25531
25532 @noindent
25533 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
25534 the environment task that executes the main program. On
25535 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
25536 that have been created but are not yet activated.
25537
25538 On OpenVMS Alpha systems, task IDs are assigned at
25539 activation. On GNAT systems, task IDs are also assigned at
25540 task creation but do not have the same form or values as
25541 task ID values in HP Ada. There is no null task, and the
25542 environment task does not have a specific task ID value.
25543
25544 @node Task IDs and Delays
25545 @subsection Task IDs and Delays
25546
25547 @noindent
25548 On OpenVMS Alpha systems, tasking delays are implemented
25549 using Timer System Services. The Task ID is used for the
25550 identification of the timer request (the @code{REQIDT} parameter).
25551 If Timers are used in the application take care not to use
25552 @code{0} for the identification, because cancelling such a timer
25553 will cancel all timers and may lead to unpredictable results.
25554
25555 @node Task-Related Pragmas
25556 @subsection Task-Related Pragmas
25557
25558 @noindent
25559 Ada supplies the pragma @code{TASK_STORAGE}, which allows
25560 specification of the size of the guard area for a task
25561 stack. (The guard area forms an area of memory that has no
25562 read or write access and thus helps in the detection of
25563 stack overflow.) On OpenVMS Alpha systems, if the pragma
25564 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
25565 area is created. In the absence of a pragma @code{TASK_STORAGE},
25566 a default guard area is created.
25567
25568 GNAT supplies the following task-related pragmas:
25569
25570 @itemize @bullet
25571 @item  @code{TASK_INFO}
25572
25573 This pragma appears within a task definition and
25574 applies to the task in which it appears. The argument
25575 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
25576
25577 @item  @code{TASK_STORAGE}
25578
25579 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
25580 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
25581 @code{SUPPRESS}, and @code{VOLATILE}.
25582 @end itemize
25583 @node Scheduling and Task Priority
25584 @subsection Scheduling and Task Priority
25585
25586 @noindent
25587 HP Ada implements the Ada language requirement that
25588 when two tasks are eligible for execution and they have
25589 different priorities, the lower priority task does not
25590 execute while the higher priority task is waiting. The HP
25591 Ada Run-Time Library keeps a task running until either the
25592 task is suspended or a higher priority task becomes ready.
25593
25594 On OpenVMS Alpha systems, the default strategy is round-
25595 robin with preemption. Tasks of equal priority take turns
25596 at the processor. A task is run for a certain period of
25597 time and then placed at the tail of the ready queue for
25598 its priority level.
25599
25600 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
25601 which can be used to enable or disable round-robin
25602 scheduling of tasks with the same priority.
25603 See the relevant HP Ada run-time reference manual for
25604 information on using the pragmas to control HP Ada task
25605 scheduling.
25606
25607 GNAT follows the scheduling rules of Annex D (Real-Time
25608 Annex) of the @cite{Ada Reference Manual}. In general, this
25609 scheduling strategy is fully compatible with HP Ada
25610 although it provides some additional constraints (as
25611 fully documented in Annex D).
25612 GNAT implements time slicing control in a manner compatible with
25613 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
25614 are identical to the HP Ada 83 pragma of the same name.
25615 Note that it is not possible to mix GNAT tasking and
25616 HP Ada 83 tasking in the same program, since the two run-time
25617 libraries are not compatible.
25618
25619 @node The Task Stack
25620 @subsection The Task Stack
25621
25622 @noindent
25623 In HP Ada, a task stack is allocated each time a
25624 non-passive task is activated. As soon as the task is
25625 terminated, the storage for the task stack is deallocated.
25626 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
25627 a default stack size is used. Also, regardless of the size
25628 specified, some additional space is allocated for task
25629 management purposes. On OpenVMS Alpha systems, at least
25630 one page is allocated.
25631
25632 GNAT handles task stacks in a similar manner. In accordance with
25633 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
25634 an alternative method for controlling the task stack size.
25635 The specification of the attribute @code{T'STORAGE_SIZE} is also
25636 supported in a manner compatible with HP Ada.
25637
25638 @node External Interrupts
25639 @subsection External Interrupts
25640
25641 @noindent
25642 On HP Ada, external interrupts can be associated with task entries.
25643 GNAT is compatible with HP Ada in its handling of external interrupts.
25644
25645 @node Pragmas and Pragma-Related Features
25646 @section Pragmas and Pragma-Related Features
25647
25648 @noindent
25649 Both HP Ada and GNAT supply all language-defined pragmas
25650 as specified by the Ada 83 standard. GNAT also supplies all
25651 language-defined pragmas introduced by Ada 95 and Ada 2005.
25652 In addition, GNAT implements the implementation-defined pragmas
25653 from HP Ada 83.
25654
25655 @itemize @bullet
25656 @item  @code{AST_ENTRY}
25657
25658 @item  @code{COMMON_OBJECT}
25659
25660 @item  @code{COMPONENT_ALIGNMENT}
25661
25662 @item  @code{EXPORT_EXCEPTION}
25663
25664 @item  @code{EXPORT_FUNCTION}
25665
25666 @item  @code{EXPORT_OBJECT}
25667
25668 @item  @code{EXPORT_PROCEDURE}
25669
25670 @item  @code{EXPORT_VALUED_PROCEDURE}
25671
25672 @item  @code{FLOAT_REPRESENTATION}
25673
25674 @item  @code{IDENT}
25675
25676 @item  @code{IMPORT_EXCEPTION}
25677
25678 @item  @code{IMPORT_FUNCTION}
25679
25680 @item  @code{IMPORT_OBJECT}
25681
25682 @item  @code{IMPORT_PROCEDURE}
25683
25684 @item  @code{IMPORT_VALUED_PROCEDURE}
25685
25686 @item  @code{INLINE_GENERIC}
25687
25688 @item  @code{INTERFACE_NAME}
25689
25690 @item  @code{LONG_FLOAT}
25691
25692 @item  @code{MAIN_STORAGE}
25693
25694 @item  @code{PASSIVE}
25695
25696 @item  @code{PSECT_OBJECT}
25697
25698 @item  @code{SHARE_GENERIC}
25699
25700 @item  @code{SUPPRESS_ALL}
25701
25702 @item  @code{TASK_STORAGE}
25703
25704 @item  @code{TIME_SLICE}
25705
25706 @item  @code{TITLE}
25707 @end itemize
25708
25709 @noindent
25710 These pragmas are all fully implemented, with the exception of @code{TITLE},
25711 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
25712 recognized, but which have no
25713 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
25714 use of Ada protected objects. In GNAT, all generics are inlined.
25715
25716 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
25717 a separate subprogram specification which must appear before the
25718 subprogram body.
25719
25720 GNAT also supplies a number of implementation-defined pragmas as follows:
25721 @itemize @bullet
25722 @item  @code{ABORT_DEFER}
25723
25724 @item  @code{ADA_83}
25725
25726 @item  @code{ADA_95}
25727
25728 @item  @code{ADA_05}
25729
25730 @item  @code{ANNOTATE}
25731
25732 @item  @code{ASSERT}
25733
25734 @item  @code{C_PASS_BY_COPY}
25735
25736 @item  @code{CPP_CLASS}
25737
25738 @item  @code{CPP_CONSTRUCTOR}
25739
25740 @item  @code{CPP_DESTRUCTOR}
25741
25742 @item  @code{DEBUG}
25743
25744 @item  @code{EXTEND_SYSTEM}
25745
25746 @item  @code{LINKER_ALIAS}
25747
25748 @item  @code{LINKER_SECTION}
25749
25750 @item  @code{MACHINE_ATTRIBUTE}
25751
25752 @item  @code{NO_RETURN}
25753
25754 @item  @code{PURE_FUNCTION}
25755
25756 @item  @code{SOURCE_FILE_NAME}
25757
25758 @item  @code{SOURCE_REFERENCE}
25759
25760 @item  @code{TASK_INFO}
25761
25762 @item  @code{UNCHECKED_UNION}
25763
25764 @item  @code{UNIMPLEMENTED_UNIT}
25765
25766 @item  @code{UNIVERSAL_DATA}
25767
25768 @item  @code{UNSUPPRESS}
25769
25770 @item  @code{WARNINGS}
25771
25772 @item  @code{WEAK_EXTERNAL}
25773 @end itemize
25774
25775 @noindent
25776 For full details on these GNAT implementation-defined pragmas,
25777 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
25778 Manual}.
25779
25780 @menu
25781 * Restrictions on the Pragma INLINE::
25782 * Restrictions on the Pragma INTERFACE::
25783 * Restrictions on the Pragma SYSTEM_NAME::
25784 @end menu
25785
25786 @node Restrictions on the Pragma INLINE
25787 @subsection Restrictions on Pragma @code{INLINE}
25788
25789 @noindent
25790 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
25791 @itemize @bullet
25792 @item  Parameters cannot have a task type.
25793
25794 @item  Function results cannot be task types, unconstrained
25795 array types, or unconstrained types with discriminants.
25796
25797 @item  Bodies cannot declare the following:
25798 @itemize @bullet
25799 @item  Subprogram body or stub (imported subprogram is allowed)
25800
25801 @item  Tasks
25802
25803 @item  Generic declarations
25804
25805 @item  Instantiations
25806
25807 @item  Exceptions
25808
25809 @item  Access types (types derived from access types allowed)
25810
25811 @item  Array or record types
25812
25813 @item  Dependent tasks
25814
25815 @item  Direct recursive calls of subprogram or containing
25816 subprogram, directly or via a renaming
25817
25818 @end itemize
25819 @end itemize
25820
25821 @noindent
25822 In GNAT, the only restriction on pragma @code{INLINE} is that the
25823 body must occur before the call if both are in the same
25824 unit, and the size must be appropriately small. There are
25825 no other specific restrictions which cause subprograms to
25826 be incapable of being inlined.
25827
25828 @node  Restrictions on the Pragma INTERFACE
25829 @subsection  Restrictions on Pragma @code{INTERFACE}
25830
25831 @noindent
25832 The following restrictions on pragma @code{INTERFACE}
25833 are enforced by both HP Ada and GNAT:
25834 @itemize @bullet
25835 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
25836 Default is the default on OpenVMS Alpha systems.
25837
25838 @item  Parameter passing: Language specifies default
25839 mechanisms but can be overridden with an @code{EXPORT} pragma.
25840
25841 @itemize @bullet
25842 @item  Ada: Use internal Ada rules.
25843
25844 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
25845 record or task type. Result cannot be a string, an
25846 array, or a record.
25847
25848 @item  Fortran: Parameters cannot have a task type. Result cannot
25849 be a string, an array, or a record.
25850 @end itemize
25851 @end itemize
25852
25853 @noindent
25854 GNAT is entirely upwards compatible with HP Ada, and in addition allows
25855 record parameters for all languages.
25856
25857 @node  Restrictions on the Pragma SYSTEM_NAME
25858 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
25859
25860 @noindent
25861 For HP Ada for OpenVMS Alpha, the enumeration literal
25862 for the type @code{NAME} is @code{OPENVMS_AXP}.
25863 In GNAT, the enumeration
25864 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
25865
25866 @node  Library of Predefined Units
25867 @section  Library of Predefined Units
25868
25869 @noindent
25870 A library of predefined units is provided as part of the
25871 HP Ada and GNAT implementations. HP Ada does not provide
25872 the package @code{MACHINE_CODE} but instead recommends importing
25873 assembler code.
25874
25875 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
25876 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
25877 version.
25878 The HP Ada Predefined Library units are modified to remove post-Ada 83
25879 incompatibilities and to make them interoperable with GNAT
25880 (@pxref{Changes to DECLIB}, for details).
25881 The units are located in the @file{DECLIB} directory.
25882
25883 The GNAT RTL is contained in
25884 the @file{ADALIB} directory, and
25885 the default search path is set up to find @code{DECLIB} units in preference
25886 to @code{ADALIB} units with the same name (@code{TEXT_IO},
25887 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
25888
25889 @menu
25890 * Changes to DECLIB::
25891 @end menu
25892
25893 @node Changes to DECLIB
25894 @subsection Changes to @code{DECLIB}
25895
25896 @noindent
25897 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
25898 compatibility are minor and include the following:
25899
25900 @itemize @bullet
25901 @item  Adjusting the location of pragmas and record representation
25902 clauses to obey Ada 95 (and thus Ada 2005) rules
25903
25904 @item  Adding the proper notation to generic formal parameters
25905 that take unconstrained types in instantiation
25906
25907 @item  Adding pragma @code{ELABORATE_BODY} to package specs
25908 that have package bodies not otherwise allowed
25909
25910 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
25911 ``@code{PROTECTD}''.
25912 Currently these are found only in the @code{STARLET} package spec.
25913
25914 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
25915 where the address size is constrained to 32 bits.
25916 @end itemize
25917
25918 @noindent
25919 None of the above changes is visible to users.
25920
25921 @node Bindings
25922 @section Bindings
25923
25924 @noindent
25925 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
25926 @itemize @bullet
25927
25928 @item  Command Language Interpreter (CLI interface)
25929
25930 @item  DECtalk Run-Time Library (DTK interface)
25931
25932 @item  Librarian utility routines (LBR interface)
25933
25934 @item  General Purpose Run-Time Library (LIB interface)
25935
25936 @item  Math Run-Time Library (MTH interface)
25937
25938 @item  National Character Set Run-Time Library (NCS interface)
25939
25940 @item  Compiled Code Support Run-Time Library (OTS interface)
25941
25942 @item  Parallel Processing Run-Time Library (PPL interface)
25943
25944 @item  Screen Management Run-Time Library (SMG interface)
25945
25946 @item  Sort Run-Time Library (SOR interface)
25947
25948 @item  String Run-Time Library (STR interface)
25949
25950 @item STARLET System Library
25951 @findex Starlet
25952
25953 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
25954
25955 @item  X Windows Toolkit (XT interface)
25956
25957 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
25958 @end itemize
25959
25960 @noindent
25961 GNAT provides implementations of these HP bindings in the @code{DECLIB}
25962 directory, on both the Alpha and I64 OpenVMS platforms.
25963
25964 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
25965 in the
25966 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
25967 A pragma @code{Linker_Options} has been added to packages @code{Xm},
25968 @code{Xt}, and @code{X_Lib}
25969 causing the default X/Motif sharable image libraries to be linked in. This
25970 is done via options files named @file{xm.opt}, @file{xt.opt}, and
25971 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
25972
25973 It may be necessary to edit these options files to update or correct the
25974 library names if, for example, the newer X/Motif bindings from
25975 @file{ADA$EXAMPLES}
25976 had been (previous to installing GNAT) copied and renamed to supersede the
25977 default @file{ADA$PREDEFINED} versions.
25978
25979 @menu
25980 * Shared Libraries and Options Files::
25981 * Interfaces to C::
25982 @end menu
25983
25984 @node Shared Libraries and Options Files
25985 @subsection Shared Libraries and Options Files
25986
25987 @noindent
25988 When using the HP Ada
25989 predefined X and Motif bindings, the linking with their sharable images is
25990 done automatically by @command{GNAT LINK}.
25991 When using other X and Motif bindings, you need
25992 to add the corresponding sharable images to the command line for
25993 @code{GNAT LINK}. When linking with shared libraries, or with
25994 @file{.OPT} files, you must
25995 also add them to the command line for @command{GNAT LINK}.
25996
25997 A shared library to be used with GNAT is built in the same way as other
25998 libraries under VMS. The VMS Link command can be used in standard fashion.
25999
26000 @node Interfaces to C
26001 @subsection Interfaces to C
26002
26003 @noindent
26004 HP Ada
26005 provides the following Ada types and operations:
26006
26007 @itemize @bullet
26008 @item C types package (@code{C_TYPES})
26009
26010 @item C strings (@code{C_TYPES.NULL_TERMINATED})
26011
26012 @item Other_types (@code{SHORT_INT})
26013 @end itemize
26014
26015 @noindent
26016 Interfacing to C with GNAT, you can use the above approach
26017 described for HP Ada or the facilities of Annex B of
26018 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
26019 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
26020 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
26021
26022 The @option{-gnatF} qualifier forces default and explicit
26023 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
26024 to be uppercased for compatibility with the default behavior
26025 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
26026
26027 @node Main Program Definition
26028 @section Main Program Definition
26029
26030 @noindent
26031 The following section discusses differences in the
26032 definition of main programs on HP Ada and GNAT.
26033 On HP Ada, main programs are defined to meet the
26034 following conditions:
26035 @itemize @bullet
26036 @item  Procedure with no formal parameters (returns @code{0} upon
26037 normal completion)
26038
26039 @item  Procedure with no formal parameters (returns @code{42} when
26040 an unhandled exception is raised)
26041
26042 @item  Function with no formal parameters whose returned value
26043 is of a discrete type
26044
26045 @item  Procedure with one @code{out} formal of a discrete type for
26046 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
26047
26048 @end itemize
26049
26050 @noindent
26051 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
26052 a main function or main procedure returns a discrete
26053 value whose size is less than 64 bits (32 on VAX systems),
26054 the value is zero- or sign-extended as appropriate.
26055 On GNAT, main programs are defined as follows:
26056 @itemize @bullet
26057 @item  Must be a non-generic, parameterless subprogram that
26058 is either a procedure or function returning an Ada
26059 @code{STANDARD.INTEGER} (the predefined type)
26060
26061 @item  Cannot be a generic subprogram or an instantiation of a
26062 generic subprogram
26063 @end itemize
26064
26065 @node Implementation-Defined Attributes
26066 @section Implementation-Defined Attributes
26067
26068 @noindent
26069 GNAT provides all HP Ada implementation-defined
26070 attributes.
26071
26072 @node Compiler and Run-Time Interfacing
26073 @section Compiler and Run-Time Interfacing
26074
26075 @noindent
26076 HP Ada provides the following qualifiers to pass options to the linker
26077 (ACS LINK):
26078 @itemize @bullet
26079 @item  @option{/WAIT} and @option{/SUBMIT}
26080
26081 @item  @option{/COMMAND}
26082
26083 @item  @option{/@r{[}NO@r{]}MAP}
26084
26085 @item  @option{/OUTPUT=@var{file-spec}}
26086
26087 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26088 @end itemize
26089
26090 @noindent
26091 To pass options to the linker, GNAT provides the following
26092 switches:
26093
26094 @itemize @bullet
26095 @item   @option{/EXECUTABLE=@var{exec-name}}
26096
26097 @item   @option{/VERBOSE}
26098
26099 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26100 @end itemize
26101
26102 @noindent
26103 For more information on these switches, see
26104 @ref{Switches for gnatlink}.
26105 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
26106 to control optimization. HP Ada also supplies the
26107 following pragmas:
26108 @itemize @bullet
26109 @item  @code{OPTIMIZE}
26110
26111 @item  @code{INLINE}
26112
26113 @item  @code{INLINE_GENERIC}
26114
26115 @item  @code{SUPPRESS_ALL}
26116
26117 @item  @code{PASSIVE}
26118 @end itemize
26119
26120 @noindent
26121 In GNAT, optimization is controlled strictly by command
26122 line parameters, as described in the corresponding section of this guide.
26123 The HP pragmas for control of optimization are
26124 recognized but ignored.
26125
26126 Note that in GNAT, the default is optimization off, whereas in HP Ada
26127 the default is that optimization is turned on.
26128
26129 @node Program Compilation and Library Management
26130 @section Program Compilation and Library Management
26131
26132 @noindent
26133 HP Ada and GNAT provide a comparable set of commands to
26134 build programs. HP Ada also provides a program library,
26135 which is a concept that does not exist on GNAT. Instead,
26136 GNAT provides directories of sources that are compiled as
26137 needed.
26138
26139 The following table summarizes
26140 the HP Ada commands and provides
26141 equivalent GNAT commands. In this table, some GNAT
26142 equivalents reflect the fact that GNAT does not use the
26143 concept of a program library. Instead, it uses a model
26144 in which collections of source and object files are used
26145 in a manner consistent with other languages like C and
26146 Fortran. Therefore, standard system file commands are used
26147 to manipulate these elements. Those GNAT commands are marked with
26148 an asterisk.
26149 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
26150
26151 @need 1500
26152 @multitable @columnfractions .35 .65
26153
26154 @item @emph{HP Ada Command}
26155 @tab @emph{GNAT Equivalent / Description}
26156
26157 @item @command{ADA}
26158 @tab @command{GNAT COMPILE}@*
26159 Invokes the compiler to compile one or more Ada source files.
26160
26161 @item @command{ACS ATTACH}@*
26162 @tab [No equivalent]@*
26163 Switches control of terminal from current process running the program
26164 library manager.
26165
26166 @item @command{ACS CHECK}
26167 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
26168 Forms the execution closure of one
26169 or more compiled units and checks completeness and currency.
26170
26171 @item @command{ACS COMPILE}
26172 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26173 Forms the execution closure of one or
26174 more specified units, checks completeness and currency,
26175 identifies units that have revised source files, compiles same,
26176 and recompiles units that are or will become obsolete.
26177 Also completes incomplete generic instantiations.
26178
26179 @item @command{ACS COPY FOREIGN}
26180 @tab Copy (*)@*
26181 Copies a foreign object file into the program library as a
26182 library unit body.
26183
26184 @item @command{ACS COPY UNIT}
26185 @tab Copy (*)@*
26186 Copies a compiled unit from one program library to another.
26187
26188 @item @command{ACS CREATE LIBRARY}
26189 @tab Create /directory (*)@*
26190 Creates a program library.
26191
26192 @item @command{ACS CREATE SUBLIBRARY}
26193 @tab Create /directory (*)@*
26194 Creates a program sublibrary.
26195
26196 @item @command{ACS DELETE LIBRARY}
26197 @tab @*
26198 Deletes a program library and its contents.
26199
26200 @item @command{ACS DELETE SUBLIBRARY}
26201 @tab @*
26202 Deletes a program sublibrary and its contents.
26203
26204 @item @command{ACS DELETE UNIT}
26205 @tab Delete file (*)@*
26206 On OpenVMS systems, deletes one or more compiled units from
26207 the current program library.
26208
26209 @item @command{ACS DIRECTORY}
26210 @tab Directory (*)@*
26211 On OpenVMS systems, lists units contained in the current
26212 program library.
26213
26214 @item @command{ACS ENTER FOREIGN}
26215 @tab Copy (*)@*
26216 Allows the import of a foreign body as an Ada library
26217 spec and enters a reference to a pointer.
26218
26219 @item @command{ACS ENTER UNIT}
26220 @tab Copy (*)@*
26221 Enters a reference (pointer) from the current program library to
26222 a unit compiled into another program library.
26223
26224 @item @command{ACS EXIT}
26225 @tab [No equivalent]@*
26226 Exits from the program library manager.
26227
26228 @item @command{ACS EXPORT}
26229 @tab Copy (*)@*
26230 Creates an object file that contains system-specific object code
26231 for one or more units. With GNAT, object files can simply be copied
26232 into the desired directory.
26233
26234 @item @command{ACS EXTRACT SOURCE}
26235 @tab Copy (*)@*
26236 Allows access to the copied source file for each Ada compilation unit
26237
26238 @item @command{ACS HELP}
26239 @tab @command{HELP GNAT}@*
26240 Provides online help.
26241
26242 @item @command{ACS LINK}
26243 @tab @command{GNAT LINK}@*
26244 Links an object file containing Ada units into an executable file.
26245
26246 @item @command{ACS LOAD}
26247 @tab Copy (*)@*
26248 Loads (partially compiles) Ada units into the program library.
26249 Allows loading a program from a collection of files into a library
26250 without knowing the relationship among units.
26251
26252 @item @command{ACS MERGE}
26253 @tab Copy (*)@*
26254 Merges into the current program library, one or more units from
26255 another library where they were modified.
26256
26257 @item @command{ACS RECOMPILE}
26258 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26259 Recompiles from   external or copied source files any obsolete
26260 unit in the closure. Also, completes any incomplete generic
26261 instantiations.
26262
26263 @item @command{ACS REENTER}
26264 @tab @command{GNAT MAKE}@*
26265 Reenters current references to units compiled after last entered
26266 with the @command{ACS ENTER UNIT} command.
26267
26268 @item @command{ACS SET LIBRARY}
26269 @tab Set default (*)@*
26270 Defines a program library to be the compilation context as well
26271 as the target library for compiler output and commands in general.
26272
26273 @item @command{ACS SET PRAGMA}
26274 @tab Edit @file{gnat.adc} (*)@*
26275 Redefines specified  values of the library characteristics
26276 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
26277 and @code{Float_Representation}.
26278
26279 @item @command{ACS SET SOURCE}
26280 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
26281 Defines the source file search list for the @command{ACS COMPILE} command.
26282
26283 @item @command{ACS SHOW LIBRARY}
26284 @tab Directory (*)@*
26285 Lists information about one or more program libraries.
26286
26287 @item @command{ACS SHOW PROGRAM}
26288 @tab [No equivalent]@*
26289 Lists information about the execution closure of one or
26290 more units in the program library.
26291
26292 @item @command{ACS SHOW SOURCE}
26293 @tab Show logical @code{ADA_INCLUDE_PATH}@*
26294 Shows the source file search used when compiling units.
26295
26296 @item @command{ACS SHOW VERSION}
26297 @tab Compile with @option{VERBOSE} option
26298 Displays the version number of the compiler and program library
26299 manager used.
26300
26301 @item @command{ACS SPAWN}
26302 @tab [No equivalent]@*
26303 Creates a subprocess of the current process (same as @command{DCL SPAWN}
26304 command).
26305
26306 @item @command{ACS VERIFY}
26307 @tab [No equivalent]@*
26308 Performs a series of consistency checks on a program library to
26309 determine whether the library structure and library files are in
26310 valid form.
26311 @end multitable
26312
26313 @noindent
26314
26315 @node Input-Output
26316 @section Input-Output
26317
26318 @noindent
26319 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
26320 Management Services (RMS) to perform operations on
26321 external files.
26322
26323 @noindent
26324 HP Ada and GNAT predefine an identical set of input-
26325 output packages. To make the use of the
26326 generic @code{TEXT_IO} operations more convenient, HP Ada
26327 provides predefined library packages that instantiate the
26328 integer and floating-point operations for the predefined
26329 integer and floating-point types as shown in the following table.
26330
26331 @multitable @columnfractions .45 .55
26332 @item @emph{Package Name} @tab Instantiation
26333
26334 @item @code{INTEGER_TEXT_IO}
26335 @tab @code{INTEGER_IO(INTEGER)}
26336
26337 @item @code{SHORT_INTEGER_TEXT_IO}
26338 @tab @code{INTEGER_IO(SHORT_INTEGER)}
26339
26340 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
26341 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
26342
26343 @item @code{FLOAT_TEXT_IO}
26344 @tab @code{FLOAT_IO(FLOAT)}
26345
26346 @item @code{LONG_FLOAT_TEXT_IO}
26347 @tab @code{FLOAT_IO(LONG_FLOAT)}
26348 @end multitable
26349
26350 @noindent
26351 The HP Ada predefined packages and their operations
26352 are implemented using OpenVMS Alpha files and input-output
26353 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
26354 Familiarity with the following is recommended:
26355 @itemize @bullet
26356 @item  RMS file organizations and access methods
26357
26358 @item  OpenVMS file specifications and directories
26359
26360 @item  OpenVMS File Definition Language (FDL)
26361 @end itemize
26362
26363 @noindent
26364 GNAT provides I/O facilities that are completely
26365 compatible with HP Ada. The distribution includes the
26366 standard HP Ada versions of all I/O packages, operating
26367 in a manner compatible with HP Ada. In particular, the
26368 following packages are by default the HP Ada (Ada 83)
26369 versions of these packages rather than the renamings
26370 suggested in Annex J of the Ada Reference Manual:
26371 @itemize @bullet
26372 @item  @code{TEXT_IO}
26373
26374 @item  @code{SEQUENTIAL_IO}
26375
26376 @item  @code{DIRECT_IO}
26377 @end itemize
26378
26379 @noindent
26380 The use of the standard child package syntax (for
26381 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
26382 packages.
26383 GNAT provides HP-compatible predefined instantiations
26384 of the @code{TEXT_IO} packages, and also
26385 provides the standard predefined instantiations required
26386 by the @cite{Ada Reference Manual}.
26387
26388 For further information on how GNAT interfaces to the file
26389 system or how I/O is implemented in programs written in
26390 mixed languages, see @ref{Implementation of the Standard I/O,,,
26391 gnat_rm, GNAT Reference Manual}.
26392 This chapter covers the following:
26393 @itemize @bullet
26394 @item  Standard I/O packages
26395
26396 @item  @code{FORM} strings
26397
26398 @item  @code{ADA.DIRECT_IO}
26399
26400 @item  @code{ADA.SEQUENTIAL_IO}
26401
26402 @item  @code{ADA.TEXT_IO}
26403
26404 @item  Stream pointer positioning
26405
26406 @item  Reading and writing non-regular files
26407
26408 @item  @code{GET_IMMEDIATE}
26409
26410 @item  Treating @code{TEXT_IO} files as streams
26411
26412 @item  Shared files
26413
26414 @item  Open modes
26415 @end itemize
26416
26417 @node Implementation Limits
26418 @section Implementation Limits
26419
26420 @noindent
26421 The following table lists implementation limits for HP Ada
26422 and GNAT systems.
26423 @multitable @columnfractions .60 .20 .20
26424 @sp 1
26425 @item  @emph{Compilation Parameter}
26426 @tab   @emph{HP Ada}
26427 @tab   @emph{GNAT}
26428 @sp 1
26429
26430 @item  In a subprogram or entry  declaration, maximum number of
26431 formal parameters that are of an unconstrained record type
26432 @tab   32
26433 @tab   No set limit
26434 @sp 1
26435
26436 @item  Maximum identifier length (number of characters)
26437 @tab   255
26438 @tab   32766
26439 @sp 1
26440
26441 @item  Maximum number of characters in a source line
26442 @tab   255
26443 @tab   32766
26444 @sp 1
26445
26446 @item  Maximum collection size   (number of bytes)
26447 @tab   2**31-1
26448 @tab   2**31-1
26449 @sp 1
26450
26451 @item  Maximum number of discriminants for a record type
26452 @tab   245
26453 @tab   No set limit
26454 @sp 1
26455
26456 @item  Maximum number of formal parameters in an entry or
26457 subprogram declaration
26458 @tab   246
26459 @tab    No set limit
26460 @sp 1
26461
26462 @item  Maximum number of dimensions in an array type
26463 @tab   255
26464 @tab   No set limit
26465 @sp 1
26466
26467 @item  Maximum number of library  units and subunits in a compilation.
26468 @tab   4095
26469 @tab   No set limit
26470 @sp 1
26471
26472 @item  Maximum number of library units and subunits in an execution.
26473 @tab   16383
26474 @tab   No set limit
26475 @sp 1
26476
26477 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
26478 or @code{PSECT_OBJECT}
26479 @tab   32757
26480 @tab   No set limit
26481 @sp 1
26482
26483 @item  Maximum number of enumeration literals in an enumeration type
26484 definition
26485 @tab   65535
26486 @tab   No set limit
26487 @sp 1
26488
26489 @item  Maximum number of lines in a source file
26490 @tab   65534
26491 @tab   No set limit
26492 @sp 1
26493
26494 @item  Maximum number of bits in any object
26495 @tab   2**31-1
26496 @tab   2**31-1
26497 @sp 1
26498
26499 @item  Maximum size of the static portion of a stack frame (approximate)
26500 @tab   2**31-1
26501 @tab   2**31-1
26502 @end multitable
26503
26504 @node Tools and Utilities
26505 @section Tools and Utilities
26506
26507 @noindent
26508 The following table lists some of the OpenVMS development tools
26509 available for HP Ada, and the corresponding tools for
26510 use with @value{EDITION} on Alpha and I64 platforms.
26511 Aside from the debugger, all the OpenVMS tools identified are part
26512 of the DECset package.
26513
26514 @iftex
26515 @c Specify table in TeX since Texinfo does a poor job
26516 @tex
26517 \smallskip
26518 \smallskip
26519 \settabs\+Language-Sensitive Editor\quad
26520    &Product with HP Ada\quad
26521    &\cr
26522 \+\it Tool
26523    &\it Product with HP Ada
26524    & \it Product with GNAT Pro\cr
26525 \smallskip
26526 \+Code Management System
26527    &HP CMS
26528    & HP CMS\cr
26529 \smallskip
26530 \+Language-Sensitive Editor
26531    &HP LSE
26532    & emacs or HP LSE (Alpha)\cr
26533 \+
26534    &
26535    & HP LSE (I64)\cr
26536 \smallskip
26537 \+Debugger
26538    &OpenVMS Debug
26539    & gdb (Alpha),\cr
26540 \+
26541    &
26542    & OpenVMS Debug (I64)\cr
26543 \smallskip
26544 \+Source Code Analyzer /
26545    &HP SCA
26546    & GNAT XREF\cr
26547 \+Cross Referencer
26548    &
26549    &\cr
26550 \smallskip
26551 \+Test Manager
26552    &HP Digital Test
26553    & HP DTM\cr
26554 \+
26555    &Manager (DTM)
26556    &\cr
26557 \smallskip
26558 \+Performance and
26559    & HP PCA
26560    & HP PCA\cr
26561 \+Coverage Analyzer
26562    &
26563    &\cr
26564 \smallskip
26565 \+Module Management
26566    & HP MMS
26567    & Not applicable\cr
26568 \+ System
26569    &
26570    &\cr
26571 \smallskip
26572 \smallskip
26573 @end tex
26574 @end iftex
26575
26576 @ifnottex
26577 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
26578 @c the TeX version above for the printed version
26579 @flushleft
26580 @c @multitable @columnfractions .3 .4 .4
26581 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
26582 @item @i{Tool}
26583 @tab @i{Tool with HP Ada}
26584 @tab @i{Tool with @value{EDITION}}
26585 @item Code Management@*System
26586 @tab HP CMS
26587 @tab HP CMS
26588 @item Language-Sensitive@*Editor
26589 @tab HP LSE
26590 @tab emacs or HP LSE (Alpha)
26591 @item
26592 @tab
26593 @tab HP LSE (I64)
26594 @item Debugger
26595 @tab OpenVMS Debug
26596 @tab gdb (Alpha),
26597 @item
26598 @tab
26599 @tab OpenVMS Debug (I64)
26600 @item Source Code Analyzer /@*Cross Referencer
26601 @tab HP SCA
26602 @tab GNAT XREF
26603 @item Test Manager
26604 @tab HP Digital Test@*Manager (DTM)
26605 @tab HP DTM
26606 @item Performance and@*Coverage Analyzer
26607 @tab HP PCA
26608 @tab HP PCA
26609 @item Module Management@*System
26610 @tab HP MMS
26611 @tab Not applicable
26612 @end multitable
26613 @end flushleft
26614 @end ifnottex
26615
26616 @end ifset
26617
26618 @c **************************************
26619 @node Platform-Specific Information for the Run-Time Libraries
26620 @appendix Platform-Specific Information for the Run-Time Libraries
26621 @cindex Tasking and threads libraries
26622 @cindex Threads libraries and tasking
26623 @cindex Run-time libraries (platform-specific information)
26624
26625 @noindent
26626 The GNAT run-time implementation may vary with respect to both the
26627 underlying threads library and the exception handling scheme.
26628 For threads support, one or more of the following are supplied:
26629 @itemize @bullet
26630 @item @b{native threads library}, a binding to the thread package from
26631 the underlying operating system
26632
26633 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
26634 POSIX thread package
26635 @end itemize
26636
26637 @noindent
26638 For exception handling, either or both of two models are supplied:
26639 @itemize @bullet
26640 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
26641 Most programs should experience a substantial speed improvement by
26642 being compiled with a ZCX run-time.
26643 This is especially true for
26644 tasking applications or applications with many exception handlers.}
26645 @cindex Zero-Cost Exceptions
26646 @cindex ZCX (Zero-Cost Exceptions)
26647 which uses binder-generated tables that
26648 are interrogated at run time to locate a handler
26649
26650 @item @b{setjmp / longjmp} (``SJLJ''),
26651 @cindex setjmp/longjmp Exception Model
26652 @cindex SJLJ (setjmp/longjmp Exception Model)
26653 which uses dynamically-set data to establish
26654 the set of handlers
26655 @end itemize
26656
26657 @noindent
26658 This appendix summarizes which combinations of threads and exception support
26659 are supplied on various GNAT platforms.
26660 It then shows how to select a particular library either
26661 permanently or temporarily,
26662 explains the properties of (and tradeoffs among) the various threads
26663 libraries, and provides some additional
26664 information about several specific platforms.
26665
26666 @menu
26667 * Summary of Run-Time Configurations::
26668 * Specifying a Run-Time Library::
26669 * Choosing the Scheduling Policy::
26670 * Solaris-Specific Considerations::
26671 * Linux-Specific Considerations::
26672 * AIX-Specific Considerations::
26673 * Irix-Specific Considerations::
26674 * RTX-Specific Considerations::
26675 @end menu
26676
26677 @node Summary of Run-Time Configurations
26678 @section Summary of Run-Time Configurations
26679
26680 @multitable @columnfractions .30 .70
26681 @item @b{alpha-openvms}
26682 @item @code{@ @ }@i{rts-native (default)}
26683 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26684 @item @code{@ @ @ @ }Exceptions @tab ZCX
26685 @*
26686 @item @b{alpha-tru64}
26687 @item @code{@ @ }@i{rts-native (default)}
26688 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26689 @item @code{@ @ @ @ }Exceptions @tab ZCX
26690 @*
26691 @item @code{@ @ }@i{rts-sjlj}
26692 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26693 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26694 @*
26695 @item @b{ia64-hp_linux}
26696 @item @code{@ @ }@i{rts-native (default)}
26697 @item @code{@ @ @ @ }Tasking    @tab pthread library
26698 @item @code{@ @ @ @ }Exceptions @tab ZCX
26699 @*
26700 @item @b{ia64-hpux}
26701 @item @code{@ @ }@i{rts-native (default)}
26702 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26703 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26704 @*
26705 @item @b{ia64-openvms}
26706 @item @code{@ @ }@i{rts-native (default)}
26707 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26708 @item @code{@ @ @ @ }Exceptions @tab ZCX
26709 @*
26710 @item @b{ia64-sgi_linux}
26711 @item @code{@ @ }@i{rts-native (default)}
26712 @item @code{@ @ @ @ }Tasking    @tab pthread library
26713 @item @code{@ @ @ @ }Exceptions @tab ZCX
26714 @*
26715 @item @b{mips-irix}
26716 @item @code{@ @ }@i{rts-native (default)}
26717 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
26718 @item @code{@ @ @ @ }Exceptions @tab ZCX
26719 @*
26720 @item @b{pa-hpux}
26721 @item @code{@ @ }@i{rts-native (default)}
26722 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26723 @item @code{@ @ @ @ }Exceptions @tab ZCX
26724 @*
26725 @item @code{@ @ }@i{rts-sjlj}
26726 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26727 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26728 @*
26729 @item @b{ppc-aix}
26730 @item @code{@ @ }@i{rts-native (default)}
26731 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
26732 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26733 @*
26734 @item @b{ppc-darwin}
26735 @item @code{@ @ }@i{rts-native (default)}
26736 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
26737 @item @code{@ @ @ @ }Exceptions @tab ZCX
26738 @*
26739 @item @b{sparc-solaris}  @tab
26740 @item @code{@ @ }@i{rts-native (default)}
26741 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26742 @item @code{@ @ @ @ }Exceptions @tab ZCX
26743 @*
26744 @item @code{@ @ }@i{rts-pthread}
26745 @item @code{@ @ @ @ }Tasking    @tab pthread library
26746 @item @code{@ @ @ @ }Exceptions @tab ZCX
26747 @*
26748 @item @code{@ @ }@i{rts-sjlj}
26749 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26750 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26751 @*
26752 @item @b{sparc64-solaris}  @tab
26753 @item @code{@ @ }@i{rts-native (default)}
26754 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26755 @item @code{@ @ @ @ }Exceptions @tab ZCX
26756 @*
26757 @item @b{x86-linux}
26758 @item @code{@ @ }@i{rts-native (default)}
26759 @item @code{@ @ @ @ }Tasking    @tab pthread library
26760 @item @code{@ @ @ @ }Exceptions @tab ZCX
26761 @*
26762 @item @code{@ @ }@i{rts-sjlj}
26763 @item @code{@ @ @ @ }Tasking    @tab pthread library
26764 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26765 @*
26766 @item @b{x86-lynx}
26767 @item @code{@ @ }@i{rts-native (default)}
26768 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
26769 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26770 @*
26771 @item @b{x86-solaris}
26772 @item @code{@ @ }@i{rts-native (default)}
26773 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
26774 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26775 @*
26776 @item @b{x86-windows}
26777 @item @code{@ @ }@i{rts-native (default)}
26778 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
26779 @item @code{@ @ @ @ }Exceptions @tab ZCX
26780 @*
26781 @item @code{@ @ }@i{rts-sjlj (default)}
26782 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
26783 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26784 @*
26785 @item @b{x86-windows-rtx}
26786 @item @code{@ @ }@i{rts-rtx-rtss (default)}
26787 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
26788 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26789 @*
26790 @item @code{@ @ }@i{rts-rtx-w32}
26791 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
26792 @item @code{@ @ @ @ }Exceptions @tab ZCX
26793 @*
26794 @item @b{x86_64-linux}
26795 @item @code{@ @ }@i{rts-native (default)}
26796 @item @code{@ @ @ @ }Tasking    @tab pthread library
26797 @item @code{@ @ @ @ }Exceptions @tab ZCX
26798 @*
26799 @item @code{@ @ }@i{rts-sjlj}
26800 @item @code{@ @ @ @ }Tasking    @tab pthread library
26801 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26802 @*
26803 @end multitable
26804
26805 @node Specifying a Run-Time Library
26806 @section Specifying a Run-Time Library
26807
26808 @noindent
26809 The @file{adainclude} subdirectory containing the sources of the GNAT
26810 run-time library, and the @file{adalib} subdirectory containing the
26811 @file{ALI} files and the static and/or shared GNAT library, are located
26812 in the gcc target-dependent area:
26813
26814 @smallexample
26815 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
26816 @end smallexample
26817
26818 @noindent
26819 As indicated above, on some platforms several run-time libraries are supplied.
26820 These libraries are installed in the target dependent area and
26821 contain a complete source and binary subdirectory. The detailed description
26822 below explains the differences between the different libraries in terms of
26823 their thread support.
26824
26825 The default run-time library (when GNAT is installed) is @emph{rts-native}.
26826 This default run time is selected by the means of soft links.
26827 For example on x86-linux:
26828
26829 @smallexample
26830 @group
26831  $(target-dir)
26832      |
26833      +--- adainclude----------+
26834      |                        |
26835      +--- adalib-----------+  |
26836      |                     |  |
26837      +--- rts-native       |  |
26838      |    |                |  |
26839      |    +--- adainclude <---+
26840      |    |                |
26841      |    +--- adalib <----+
26842      |
26843      +--- rts-sjlj
26844           |
26845           +--- adainclude
26846           |
26847           +--- adalib
26848 @end group
26849 @end smallexample
26850
26851 @noindent
26852 If the @i{rts-sjlj} library is to be selected on a permanent basis,
26853 these soft links can be modified with the following commands:
26854
26855 @smallexample
26856 $ cd $target
26857 $ rm -f adainclude adalib
26858 $ ln -s rts-sjlj/adainclude adainclude
26859 $ ln -s rts-sjlj/adalib adalib
26860 @end smallexample
26861
26862 @noindent
26863 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
26864 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
26865 @file{$target/ada_object_path}.
26866
26867 Selecting another run-time library temporarily can be
26868 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
26869 @cindex @option{--RTS} option
26870
26871 @node Choosing the Scheduling Policy
26872 @section Choosing the Scheduling Policy
26873
26874 @noindent
26875 When using a POSIX threads implementation, you have a choice of several
26876 scheduling policies: @code{SCHED_FIFO},
26877 @cindex @code{SCHED_FIFO} scheduling policy
26878 @code{SCHED_RR}
26879 @cindex @code{SCHED_RR} scheduling policy
26880 and @code{SCHED_OTHER}.
26881 @cindex @code{SCHED_OTHER} scheduling policy
26882 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
26883 or @code{SCHED_RR} requires special (e.g., root) privileges.
26884
26885 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
26886 @code{SCHED_FIFO},
26887 @cindex @code{SCHED_FIFO} scheduling policy
26888 you can use one of the following:
26889
26890 @itemize @bullet
26891 @item
26892 @code{pragma Time_Slice (0.0)}
26893 @cindex pragma Time_Slice
26894 @item
26895 the corresponding binder option @option{-T0}
26896 @cindex @option{-T0} option
26897 @item
26898 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
26899 @cindex pragma Task_Dispatching_Policy
26900 @end itemize
26901
26902 @noindent
26903 To specify @code{SCHED_RR},
26904 @cindex @code{SCHED_RR} scheduling policy
26905 you should use @code{pragma Time_Slice} with a
26906 value greater than @code{0.0}, or else use the corresponding @option{-T}
26907 binder option.
26908
26909 @node Solaris-Specific Considerations
26910 @section Solaris-Specific Considerations
26911 @cindex Solaris Sparc threads libraries
26912
26913 @noindent
26914 This section addresses some topics related to the various threads libraries
26915 on Sparc Solaris.
26916
26917 @menu
26918 * Solaris Threads Issues::
26919 @end menu
26920
26921 @node Solaris Threads Issues
26922 @subsection Solaris Threads Issues
26923
26924 @noindent
26925 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
26926 library based on POSIX threads --- @emph{rts-pthread}.
26927 @cindex rts-pthread threads library
26928 This run-time library has the advantage of being mostly shared across all
26929 POSIX-compliant thread implementations, and it also provides under
26930 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
26931 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
26932 and @code{PTHREAD_PRIO_PROTECT}
26933 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
26934 semantics that can be selected using the predefined pragma
26935 @code{Locking_Policy}
26936 @cindex pragma Locking_Policy (under rts-pthread)
26937 with respectively
26938 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
26939 @cindex @code{Inheritance_Locking} (under rts-pthread)
26940 @cindex @code{Ceiling_Locking} (under rts-pthread)
26941
26942 As explained above, the native run-time library is based on the Solaris thread
26943 library (@code{libthread}) and is the default library.
26944
26945 When the Solaris threads library is used (this is the default), programs
26946 compiled with GNAT can automatically take advantage of
26947 and can thus execute on multiple processors.
26948 The user can alternatively specify a processor on which the program should run
26949 to emulate a single-processor system. The multiprocessor / uniprocessor choice
26950 is made by
26951 setting the environment variable @env{GNAT_PROCESSOR}
26952 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
26953 to one of the following:
26954
26955 @table @code
26956 @item -2
26957 Use the default configuration (run the program on all
26958 available processors) - this is the same as having @code{GNAT_PROCESSOR}
26959 unset
26960
26961 @item -1
26962 Let the run-time implementation choose one processor and run the program on
26963 that processor
26964
26965 @item 0 .. Last_Proc
26966 Run the program on the specified processor.
26967 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
26968 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
26969 @end table
26970
26971 @node Linux-Specific Considerations
26972 @section Linux-Specific Considerations
26973 @cindex Linux threads libraries
26974
26975 @noindent
26976 On GNU/Linux without NPTL support (usually system with GNU C Library
26977 older than 2.3), the signal model is not POSIX compliant, which means
26978 that to send a signal to the process, you need to send the signal to all
26979 threads, e.g.@: by using @code{killpg()}.
26980
26981 @node AIX-Specific Considerations
26982 @section AIX-Specific Considerations
26983 @cindex AIX resolver library
26984
26985 @noindent
26986 On AIX, the resolver library initializes some internal structure on
26987 the first call to @code{get*by*} functions, which are used to implement
26988 @code{GNAT.Sockets.Get_Host_By_Name} and
26989 @code{GNAT.Sockets.Get_Host_By_Address}.
26990 If such initialization occurs within an Ada task, and the stack size for
26991 the task is the default size, a stack overflow may occur.
26992
26993 To avoid this overflow, the user should either ensure that the first call
26994 to @code{GNAT.Sockets.Get_Host_By_Name} or
26995 @code{GNAT.Sockets.Get_Host_By_Addrss}
26996 occurs in the environment task, or use @code{pragma Storage_Size} to
26997 specify a sufficiently large size for the stack of the task that contains
26998 this call.
26999
27000 @node Irix-Specific Considerations
27001 @section Irix-Specific Considerations
27002 @cindex Irix libraries
27003
27004 @noindent
27005 The GCC support libraries coming with the Irix compiler have moved to
27006 their canonical place with respect to the general Irix ABI related
27007 conventions. Running applications built with the default shared GNAT
27008 run-time now requires the LD_LIBRARY_PATH environment variable to
27009 include this location. A possible way to achieve this is to issue the
27010 following command line on a bash prompt:
27011
27012 @smallexample
27013 @group
27014 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
27015 @end group
27016 @end smallexample
27017
27018 @node RTX-Specific Considerations
27019 @section RTX-Specific Considerations
27020 @cindex RTX libraries
27021
27022 @noindent
27023 The Real-time Extension (RTX) to Windows is based on the Windows Win32
27024 API. Applications can be built to work in two different modes:
27025
27026 @itemize @bullet
27027 @item
27028 Windows executables that run in Ring 3 to utilize memory protection
27029 (@emph{rts-rtx-w32}).
27030
27031 @item
27032 Real-time subsystem (RTSS) executables that run in Ring 0, where
27033 performance can be optimized with RTSS applications taking precedent
27034 over all Windows applications (@emph{rts-rtx-rtss}).
27035
27036 @end itemize
27037
27038 @c *******************************
27039 @node Example of Binder Output File
27040 @appendix Example of Binder Output File
27041
27042 @noindent
27043 This Appendix displays the source code for @command{gnatbind}'s output
27044 file generated for a simple ``Hello World'' program.
27045 Comments have been added for clarification purposes.
27046
27047 @smallexample @c adanocomment
27048 @iftex
27049 @leftskip=0cm
27050 @end iftex
27051 --  The package is called Ada_Main unless this name is actually used
27052 --  as a unit name in the partition, in which case some other unique
27053 --  name is used.
27054
27055 with System;
27056 package ada_main is
27057
27058    Elab_Final_Code : Integer;
27059    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
27060
27061    --  The main program saves the parameters (argument count,
27062    --  argument values, environment pointer) in global variables
27063    --  for later access by other units including
27064    --  Ada.Command_Line.
27065
27066    gnat_argc : Integer;
27067    gnat_argv : System.Address;
27068    gnat_envp : System.Address;
27069
27070    --  The actual variables are stored in a library routine. This
27071    --  is useful for some shared library situations, where there
27072    --  are problems if variables are not in the library.
27073
27074    pragma Import (C, gnat_argc);
27075    pragma Import (C, gnat_argv);
27076    pragma Import (C, gnat_envp);
27077
27078    --  The exit status is similarly an external location
27079
27080    gnat_exit_status : Integer;
27081    pragma Import (C, gnat_exit_status);
27082
27083    GNAT_Version : constant String :=
27084                     "GNAT Version: 6.0.0w (20061115)";
27085    pragma Export (C, GNAT_Version, "__gnat_version");
27086
27087    --  This is the generated adafinal routine that performs
27088    --  finalization at the end of execution. In the case where
27089    --  Ada is the main program, this main program makes a call
27090    --  to adafinal at program termination.
27091
27092    procedure adafinal;
27093    pragma Export (C, adafinal, "adafinal");
27094
27095    --  This is the generated adainit routine that performs
27096    --  initialization at the start of execution. In the case
27097    --  where Ada is the main program, this main program makes
27098    --  a call to adainit at program startup.
27099
27100    procedure adainit;
27101    pragma Export (C, adainit, "adainit");
27102
27103    --  This routine is called at the start of execution. It is
27104    --  a dummy routine that is used by the debugger to breakpoint
27105    --  at the start of execution.
27106
27107    procedure Break_Start;
27108    pragma Import (C, Break_Start, "__gnat_break_start");
27109
27110    --  This is the actual generated main program (it would be
27111    --  suppressed if the no main program switch were used). As
27112    --  required by standard system conventions, this program has
27113    --  the external name main.
27114
27115    function main
27116      (argc : Integer;
27117       argv : System.Address;
27118       envp : System.Address)
27119       return Integer;
27120    pragma Export (C, main, "main");
27121
27122    --  The following set of constants give the version
27123    --  identification values for every unit in the bound
27124    --  partition. This identification is computed from all
27125    --  dependent semantic units, and corresponds to the
27126    --  string that would be returned by use of the
27127    --  Body_Version or Version attributes.
27128
27129    type Version_32 is mod 2 ** 32;
27130    u00001 : constant Version_32 := 16#7880BEB3#;
27131    u00002 : constant Version_32 := 16#0D24CBD0#;
27132    u00003 : constant Version_32 := 16#3283DBEB#;
27133    u00004 : constant Version_32 := 16#2359F9ED#;
27134    u00005 : constant Version_32 := 16#664FB847#;
27135    u00006 : constant Version_32 := 16#68E803DF#;
27136    u00007 : constant Version_32 := 16#5572E604#;
27137    u00008 : constant Version_32 := 16#46B173D8#;
27138    u00009 : constant Version_32 := 16#156A40CF#;
27139    u00010 : constant Version_32 := 16#033DABE0#;
27140    u00011 : constant Version_32 := 16#6AB38FEA#;
27141    u00012 : constant Version_32 := 16#22B6217D#;
27142    u00013 : constant Version_32 := 16#68A22947#;
27143    u00014 : constant Version_32 := 16#18CC4A56#;
27144    u00015 : constant Version_32 := 16#08258E1B#;
27145    u00016 : constant Version_32 := 16#367D5222#;
27146    u00017 : constant Version_32 := 16#20C9ECA4#;
27147    u00018 : constant Version_32 := 16#50D32CB6#;
27148    u00019 : constant Version_32 := 16#39A8BB77#;
27149    u00020 : constant Version_32 := 16#5CF8FA2B#;
27150    u00021 : constant Version_32 := 16#2F1EB794#;
27151    u00022 : constant Version_32 := 16#31AB6444#;
27152    u00023 : constant Version_32 := 16#1574B6E9#;
27153    u00024 : constant Version_32 := 16#5109C189#;
27154    u00025 : constant Version_32 := 16#56D770CD#;
27155    u00026 : constant Version_32 := 16#02F9DE3D#;
27156    u00027 : constant Version_32 := 16#08AB6B2C#;
27157    u00028 : constant Version_32 := 16#3FA37670#;
27158    u00029 : constant Version_32 := 16#476457A0#;
27159    u00030 : constant Version_32 := 16#731E1B6E#;
27160    u00031 : constant Version_32 := 16#23C2E789#;
27161    u00032 : constant Version_32 := 16#0F1BD6A1#;
27162    u00033 : constant Version_32 := 16#7C25DE96#;
27163    u00034 : constant Version_32 := 16#39ADFFA2#;
27164    u00035 : constant Version_32 := 16#571DE3E7#;
27165    u00036 : constant Version_32 := 16#5EB646AB#;
27166    u00037 : constant Version_32 := 16#4249379B#;
27167    u00038 : constant Version_32 := 16#0357E00A#;
27168    u00039 : constant Version_32 := 16#3784FB72#;
27169    u00040 : constant Version_32 := 16#2E723019#;
27170    u00041 : constant Version_32 := 16#623358EA#;
27171    u00042 : constant Version_32 := 16#107F9465#;
27172    u00043 : constant Version_32 := 16#6843F68A#;
27173    u00044 : constant Version_32 := 16#63305874#;
27174    u00045 : constant Version_32 := 16#31E56CE1#;
27175    u00046 : constant Version_32 := 16#02917970#;
27176    u00047 : constant Version_32 := 16#6CCBA70E#;
27177    u00048 : constant Version_32 := 16#41CD4204#;
27178    u00049 : constant Version_32 := 16#572E3F58#;
27179    u00050 : constant Version_32 := 16#20729FF5#;
27180    u00051 : constant Version_32 := 16#1D4F93E8#;
27181    u00052 : constant Version_32 := 16#30B2EC3D#;
27182    u00053 : constant Version_32 := 16#34054F96#;
27183    u00054 : constant Version_32 := 16#5A199860#;
27184    u00055 : constant Version_32 := 16#0E7F912B#;
27185    u00056 : constant Version_32 := 16#5760634A#;
27186    u00057 : constant Version_32 := 16#5D851835#;
27187
27188    --  The following Export pragmas export the version numbers
27189    --  with symbolic names ending in B (for body) or S
27190    --  (for spec) so that they can be located in a link. The
27191    --  information provided here is sufficient to track down
27192    --  the exact versions of units used in a given build.
27193
27194    pragma Export (C, u00001, "helloB");
27195    pragma Export (C, u00002, "system__standard_libraryB");
27196    pragma Export (C, u00003, "system__standard_libraryS");
27197    pragma Export (C, u00004, "adaS");
27198    pragma Export (C, u00005, "ada__text_ioB");
27199    pragma Export (C, u00006, "ada__text_ioS");
27200    pragma Export (C, u00007, "ada__exceptionsB");
27201    pragma Export (C, u00008, "ada__exceptionsS");
27202    pragma Export (C, u00009, "gnatS");
27203    pragma Export (C, u00010, "gnat__heap_sort_aB");
27204    pragma Export (C, u00011, "gnat__heap_sort_aS");
27205    pragma Export (C, u00012, "systemS");
27206    pragma Export (C, u00013, "system__exception_tableB");
27207    pragma Export (C, u00014, "system__exception_tableS");
27208    pragma Export (C, u00015, "gnat__htableB");
27209    pragma Export (C, u00016, "gnat__htableS");
27210    pragma Export (C, u00017, "system__exceptionsS");
27211    pragma Export (C, u00018, "system__machine_state_operationsB");
27212    pragma Export (C, u00019, "system__machine_state_operationsS");
27213    pragma Export (C, u00020, "system__machine_codeS");
27214    pragma Export (C, u00021, "system__storage_elementsB");
27215    pragma Export (C, u00022, "system__storage_elementsS");
27216    pragma Export (C, u00023, "system__secondary_stackB");
27217    pragma Export (C, u00024, "system__secondary_stackS");
27218    pragma Export (C, u00025, "system__parametersB");
27219    pragma Export (C, u00026, "system__parametersS");
27220    pragma Export (C, u00027, "system__soft_linksB");
27221    pragma Export (C, u00028, "system__soft_linksS");
27222    pragma Export (C, u00029, "system__stack_checkingB");
27223    pragma Export (C, u00030, "system__stack_checkingS");
27224    pragma Export (C, u00031, "system__tracebackB");
27225    pragma Export (C, u00032, "system__tracebackS");
27226    pragma Export (C, u00033, "ada__streamsS");
27227    pragma Export (C, u00034, "ada__tagsB");
27228    pragma Export (C, u00035, "ada__tagsS");
27229    pragma Export (C, u00036, "system__string_opsB");
27230    pragma Export (C, u00037, "system__string_opsS");
27231    pragma Export (C, u00038, "interfacesS");
27232    pragma Export (C, u00039, "interfaces__c_streamsB");
27233    pragma Export (C, u00040, "interfaces__c_streamsS");
27234    pragma Export (C, u00041, "system__file_ioB");
27235    pragma Export (C, u00042, "system__file_ioS");
27236    pragma Export (C, u00043, "ada__finalizationB");
27237    pragma Export (C, u00044, "ada__finalizationS");
27238    pragma Export (C, u00045, "system__finalization_rootB");
27239    pragma Export (C, u00046, "system__finalization_rootS");
27240    pragma Export (C, u00047, "system__finalization_implementationB");
27241    pragma Export (C, u00048, "system__finalization_implementationS");
27242    pragma Export (C, u00049, "system__string_ops_concat_3B");
27243    pragma Export (C, u00050, "system__string_ops_concat_3S");
27244    pragma Export (C, u00051, "system__stream_attributesB");
27245    pragma Export (C, u00052, "system__stream_attributesS");
27246    pragma Export (C, u00053, "ada__io_exceptionsS");
27247    pragma Export (C, u00054, "system__unsigned_typesS");
27248    pragma Export (C, u00055, "system__file_control_blockS");
27249    pragma Export (C, u00056, "ada__finalization__list_controllerB");
27250    pragma Export (C, u00057, "ada__finalization__list_controllerS");
27251
27252    -- BEGIN ELABORATION ORDER
27253    -- ada (spec)
27254    -- gnat (spec)
27255    -- gnat.heap_sort_a (spec)
27256    -- gnat.heap_sort_a (body)
27257    -- gnat.htable (spec)
27258    -- gnat.htable (body)
27259    -- interfaces (spec)
27260    -- system (spec)
27261    -- system.machine_code (spec)
27262    -- system.parameters (spec)
27263    -- system.parameters (body)
27264    -- interfaces.c_streams (spec)
27265    -- interfaces.c_streams (body)
27266    -- system.standard_library (spec)
27267    -- ada.exceptions (spec)
27268    -- system.exception_table (spec)
27269    -- system.exception_table (body)
27270    -- ada.io_exceptions (spec)
27271    -- system.exceptions (spec)
27272    -- system.storage_elements (spec)
27273    -- system.storage_elements (body)
27274    -- system.machine_state_operations (spec)
27275    -- system.machine_state_operations (body)
27276    -- system.secondary_stack (spec)
27277    -- system.stack_checking (spec)
27278    -- system.soft_links (spec)
27279    -- system.soft_links (body)
27280    -- system.stack_checking (body)
27281    -- system.secondary_stack (body)
27282    -- system.standard_library (body)
27283    -- system.string_ops (spec)
27284    -- system.string_ops (body)
27285    -- ada.tags (spec)
27286    -- ada.tags (body)
27287    -- ada.streams (spec)
27288    -- system.finalization_root (spec)
27289    -- system.finalization_root (body)
27290    -- system.string_ops_concat_3 (spec)
27291    -- system.string_ops_concat_3 (body)
27292    -- system.traceback (spec)
27293    -- system.traceback (body)
27294    -- ada.exceptions (body)
27295    -- system.unsigned_types (spec)
27296    -- system.stream_attributes (spec)
27297    -- system.stream_attributes (body)
27298    -- system.finalization_implementation (spec)
27299    -- system.finalization_implementation (body)
27300    -- ada.finalization (spec)
27301    -- ada.finalization (body)
27302    -- ada.finalization.list_controller (spec)
27303    -- ada.finalization.list_controller (body)
27304    -- system.file_control_block (spec)
27305    -- system.file_io (spec)
27306    -- system.file_io (body)
27307    -- ada.text_io (spec)
27308    -- ada.text_io (body)
27309    -- hello (body)
27310    -- END ELABORATION ORDER
27311
27312 end ada_main;
27313
27314 --  The following source file name pragmas allow the generated file
27315 --  names to be unique for different main programs. They are needed
27316 --  since the package name will always be Ada_Main.
27317
27318 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
27319 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
27320
27321 --  Generated package body for Ada_Main starts here
27322
27323 package body ada_main is
27324
27325    --  The actual finalization is performed by calling the
27326    --  library routine in System.Standard_Library.Adafinal
27327
27328    procedure Do_Finalize;
27329    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
27330
27331    -------------
27332    -- adainit --
27333    -------------
27334
27335 @findex adainit
27336    procedure adainit is
27337
27338       --  These booleans are set to True once the associated unit has
27339       --  been elaborated. It is also used to avoid elaborating the
27340       --  same unit twice.
27341
27342       E040 : Boolean;
27343       pragma Import (Ada, E040, "interfaces__c_streams_E");
27344
27345       E008 : Boolean;
27346       pragma Import (Ada, E008, "ada__exceptions_E");
27347
27348       E014 : Boolean;
27349       pragma Import (Ada, E014, "system__exception_table_E");
27350
27351       E053 : Boolean;
27352       pragma Import (Ada, E053, "ada__io_exceptions_E");
27353
27354       E017 : Boolean;
27355       pragma Import (Ada, E017, "system__exceptions_E");
27356
27357       E024 : Boolean;
27358       pragma Import (Ada, E024, "system__secondary_stack_E");
27359
27360       E030 : Boolean;
27361       pragma Import (Ada, E030, "system__stack_checking_E");
27362
27363       E028 : Boolean;
27364       pragma Import (Ada, E028, "system__soft_links_E");
27365
27366       E035 : Boolean;
27367       pragma Import (Ada, E035, "ada__tags_E");
27368
27369       E033 : Boolean;
27370       pragma Import (Ada, E033, "ada__streams_E");
27371
27372       E046 : Boolean;
27373       pragma Import (Ada, E046, "system__finalization_root_E");
27374
27375       E048 : Boolean;
27376       pragma Import (Ada, E048, "system__finalization_implementation_E");
27377
27378       E044 : Boolean;
27379       pragma Import (Ada, E044, "ada__finalization_E");
27380
27381       E057 : Boolean;
27382       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
27383
27384       E055 : Boolean;
27385       pragma Import (Ada, E055, "system__file_control_block_E");
27386
27387       E042 : Boolean;
27388       pragma Import (Ada, E042, "system__file_io_E");
27389
27390       E006 : Boolean;
27391       pragma Import (Ada, E006, "ada__text_io_E");
27392
27393       --  Set_Globals is a library routine that stores away the
27394       --  value of the indicated set of global values in global
27395       --  variables within the library.
27396
27397       procedure Set_Globals
27398         (Main_Priority            : Integer;
27399          Time_Slice_Value         : Integer;
27400          WC_Encoding              : Character;
27401          Locking_Policy           : Character;
27402          Queuing_Policy           : Character;
27403          Task_Dispatching_Policy  : Character;
27404          Adafinal                 : System.Address;
27405          Unreserve_All_Interrupts : Integer;
27406          Exception_Tracebacks     : Integer);
27407 @findex __gnat_set_globals
27408       pragma Import (C, Set_Globals, "__gnat_set_globals");
27409
27410       --  SDP_Table_Build is a library routine used to build the
27411       --  exception tables. See unit Ada.Exceptions in files
27412       --  a-except.ads/adb for full details of how zero cost
27413       --  exception handling works. This procedure, the call to
27414       --  it, and the two following tables are all omitted if the
27415       --  build is in longjmp/setjmp exception mode.
27416
27417 @findex SDP_Table_Build
27418 @findex Zero Cost Exceptions
27419       procedure SDP_Table_Build
27420         (SDP_Addresses   : System.Address;
27421          SDP_Count       : Natural;
27422          Elab_Addresses  : System.Address;
27423          Elab_Addr_Count : Natural);
27424       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
27425
27426       --  Table of Unit_Exception_Table addresses. Used for zero
27427       --  cost exception handling to build the top level table.
27428
27429       ST : aliased constant array (1 .. 23) of System.Address := (
27430         Hello'UET_Address,
27431         Ada.Text_Io'UET_Address,
27432         Ada.Exceptions'UET_Address,
27433         Gnat.Heap_Sort_A'UET_Address,
27434         System.Exception_Table'UET_Address,
27435         System.Machine_State_Operations'UET_Address,
27436         System.Secondary_Stack'UET_Address,
27437         System.Parameters'UET_Address,
27438         System.Soft_Links'UET_Address,
27439         System.Stack_Checking'UET_Address,
27440         System.Traceback'UET_Address,
27441         Ada.Streams'UET_Address,
27442         Ada.Tags'UET_Address,
27443         System.String_Ops'UET_Address,
27444         Interfaces.C_Streams'UET_Address,
27445         System.File_Io'UET_Address,
27446         Ada.Finalization'UET_Address,
27447         System.Finalization_Root'UET_Address,
27448         System.Finalization_Implementation'UET_Address,
27449         System.String_Ops_Concat_3'UET_Address,
27450         System.Stream_Attributes'UET_Address,
27451         System.File_Control_Block'UET_Address,
27452         Ada.Finalization.List_Controller'UET_Address);
27453
27454       --  Table of addresses of elaboration routines. Used for
27455       --  zero cost exception handling to make sure these
27456       --  addresses are included in the top level procedure
27457       --  address table.
27458
27459       EA : aliased constant array (1 .. 23) of System.Address := (
27460         adainit'Code_Address,
27461         Do_Finalize'Code_Address,
27462         Ada.Exceptions'Elab_Spec'Address,
27463         System.Exceptions'Elab_Spec'Address,
27464         Interfaces.C_Streams'Elab_Spec'Address,
27465         System.Exception_Table'Elab_Body'Address,
27466         Ada.Io_Exceptions'Elab_Spec'Address,
27467         System.Stack_Checking'Elab_Spec'Address,
27468         System.Soft_Links'Elab_Body'Address,
27469         System.Secondary_Stack'Elab_Body'Address,
27470         Ada.Tags'Elab_Spec'Address,
27471         Ada.Tags'Elab_Body'Address,
27472         Ada.Streams'Elab_Spec'Address,
27473         System.Finalization_Root'Elab_Spec'Address,
27474         Ada.Exceptions'Elab_Body'Address,
27475         System.Finalization_Implementation'Elab_Spec'Address,
27476         System.Finalization_Implementation'Elab_Body'Address,
27477         Ada.Finalization'Elab_Spec'Address,
27478         Ada.Finalization.List_Controller'Elab_Spec'Address,
27479         System.File_Control_Block'Elab_Spec'Address,
27480         System.File_Io'Elab_Body'Address,
27481         Ada.Text_Io'Elab_Spec'Address,
27482         Ada.Text_Io'Elab_Body'Address);
27483
27484    --  Start of processing for adainit
27485
27486    begin
27487
27488       --  Call SDP_Table_Build to build the top level procedure
27489       --  table for zero cost exception handling (omitted in
27490       --  longjmp/setjmp mode).
27491
27492       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
27493
27494       --  Call Set_Globals to record various information for
27495       --  this partition.  The values are derived by the binder
27496       --  from information stored in the ali files by the compiler.
27497
27498 @findex __gnat_set_globals
27499       Set_Globals
27500         (Main_Priority            => -1,
27501          --  Priority of main program, -1 if no pragma Priority used
27502
27503          Time_Slice_Value         => -1,
27504          --  Time slice from Time_Slice pragma, -1 if none used
27505
27506          WC_Encoding              => 'b',
27507          --  Wide_Character encoding used, default is brackets
27508
27509          Locking_Policy           => ' ',
27510          --  Locking_Policy used, default of space means not
27511          --  specified, otherwise it is the first character of
27512          --  the policy name.
27513
27514          Queuing_Policy           => ' ',
27515          --  Queuing_Policy used, default of space means not
27516          --  specified, otherwise it is the first character of
27517          --  the policy name.
27518
27519          Task_Dispatching_Policy  => ' ',
27520          --  Task_Dispatching_Policy used, default of space means
27521          --  not specified, otherwise first character of the
27522          --  policy name.
27523
27524          Adafinal                 => System.Null_Address,
27525          --  Address of Adafinal routine, not used anymore
27526
27527          Unreserve_All_Interrupts => 0,
27528          --  Set true if pragma Unreserve_All_Interrupts was used
27529
27530          Exception_Tracebacks     => 0);
27531          --  Indicates if exception tracebacks are enabled
27532
27533       Elab_Final_Code := 1;
27534
27535       --  Now we have the elaboration calls for all units in the partition.
27536       --  The Elab_Spec and Elab_Body attributes generate references to the
27537       --  implicit elaboration procedures generated by the compiler for
27538       --  each unit that requires elaboration.
27539
27540       if not E040 then
27541          Interfaces.C_Streams'Elab_Spec;
27542       end if;
27543       E040 := True;
27544       if not E008 then
27545          Ada.Exceptions'Elab_Spec;
27546       end if;
27547       if not E014 then
27548          System.Exception_Table'Elab_Body;
27549          E014 := True;
27550       end if;
27551       if not E053 then
27552          Ada.Io_Exceptions'Elab_Spec;
27553          E053 := True;
27554       end if;
27555       if not E017 then
27556          System.Exceptions'Elab_Spec;
27557          E017 := True;
27558       end if;
27559       if not E030 then
27560          System.Stack_Checking'Elab_Spec;
27561       end if;
27562       if not E028 then
27563          System.Soft_Links'Elab_Body;
27564          E028 := True;
27565       end if;
27566       E030 := True;
27567       if not E024 then
27568          System.Secondary_Stack'Elab_Body;
27569          E024 := True;
27570       end if;
27571       if not E035 then
27572          Ada.Tags'Elab_Spec;
27573       end if;
27574       if not E035 then
27575          Ada.Tags'Elab_Body;
27576          E035 := True;
27577       end if;
27578       if not E033 then
27579          Ada.Streams'Elab_Spec;
27580          E033 := True;
27581       end if;
27582       if not E046 then
27583          System.Finalization_Root'Elab_Spec;
27584       end if;
27585       E046 := True;
27586       if not E008 then
27587          Ada.Exceptions'Elab_Body;
27588          E008 := True;
27589       end if;
27590       if not E048 then
27591          System.Finalization_Implementation'Elab_Spec;
27592       end if;
27593       if not E048 then
27594          System.Finalization_Implementation'Elab_Body;
27595          E048 := True;
27596       end if;
27597       if not E044 then
27598          Ada.Finalization'Elab_Spec;
27599       end if;
27600       E044 := True;
27601       if not E057 then
27602          Ada.Finalization.List_Controller'Elab_Spec;
27603       end if;
27604       E057 := True;
27605       if not E055 then
27606          System.File_Control_Block'Elab_Spec;
27607          E055 := True;
27608       end if;
27609       if not E042 then
27610          System.File_Io'Elab_Body;
27611          E042 := True;
27612       end if;
27613       if not E006 then
27614          Ada.Text_Io'Elab_Spec;
27615       end if;
27616       if not E006 then
27617          Ada.Text_Io'Elab_Body;
27618          E006 := True;
27619       end if;
27620
27621       Elab_Final_Code := 0;
27622    end adainit;
27623
27624    --------------
27625    -- adafinal --
27626    --------------
27627
27628 @findex adafinal
27629    procedure adafinal is
27630    begin
27631       Do_Finalize;
27632    end adafinal;
27633
27634    ----------
27635    -- main --
27636    ----------
27637
27638    --  main is actually a function, as in the ANSI C standard,
27639    --  defined to return the exit status. The three parameters
27640    --  are the argument count, argument values and environment
27641    --  pointer.
27642
27643 @findex Main Program
27644    function main
27645      (argc : Integer;
27646       argv : System.Address;
27647       envp : System.Address)
27648       return Integer
27649    is
27650       --  The initialize routine performs low level system
27651       --  initialization using a standard library routine which
27652       --  sets up signal handling and performs any other
27653       --  required setup. The routine can be found in file
27654       --  a-init.c.
27655
27656 @findex __gnat_initialize
27657       procedure initialize;
27658       pragma Import (C, initialize, "__gnat_initialize");
27659
27660       --  The finalize routine performs low level system
27661       --  finalization using a standard library routine. The
27662       --  routine is found in file a-final.c and in the standard
27663       --  distribution is a dummy routine that does nothing, so
27664       --  really this is a hook for special user finalization.
27665
27666 @findex __gnat_finalize
27667       procedure finalize;
27668       pragma Import (C, finalize, "__gnat_finalize");
27669
27670       --  We get to the main program of the partition by using
27671       --  pragma Import because if we try to with the unit and
27672       --  call it Ada style, then not only do we waste time
27673       --  recompiling it, but also, we don't really know the right
27674       --  switches (e.g.@: identifier character set) to be used
27675       --  to compile it.
27676
27677       procedure Ada_Main_Program;
27678       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
27679
27680    --  Start of processing for main
27681
27682    begin
27683       --  Save global variables
27684
27685       gnat_argc := argc;
27686       gnat_argv := argv;
27687       gnat_envp := envp;
27688
27689       --  Call low level system initialization
27690
27691       Initialize;
27692
27693       --  Call our generated Ada initialization routine
27694
27695       adainit;
27696
27697       --  This is the point at which we want the debugger to get
27698       --  control
27699
27700       Break_Start;
27701
27702       --  Now we call the main program of the partition
27703
27704       Ada_Main_Program;
27705
27706       --  Perform Ada finalization
27707
27708       adafinal;
27709
27710       --  Perform low level system finalization
27711
27712       Finalize;
27713
27714       --  Return the proper exit status
27715       return (gnat_exit_status);
27716    end;
27717
27718 --  This section is entirely comments, so it has no effect on the
27719 --  compilation of the Ada_Main package. It provides the list of
27720 --  object files and linker options, as well as some standard
27721 --  libraries needed for the link. The gnatlink utility parses
27722 --  this b~hello.adb file to read these comment lines to generate
27723 --  the appropriate command line arguments for the call to the
27724 --  system linker. The BEGIN/END lines are used for sentinels for
27725 --  this parsing operation.
27726
27727 --  The exact file names will of course depend on the environment,
27728 --  host/target and location of files on the host system.
27729
27730 @findex Object file list
27731 -- BEGIN Object file/option list
27732    --   ./hello.o
27733    --   -L./
27734    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
27735    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
27736 -- END Object file/option list
27737
27738 end ada_main;
27739 @end smallexample
27740
27741 @noindent
27742 The Ada code in the above example is exactly what is generated by the
27743 binder. We have added comments to more clearly indicate the function
27744 of each part of the generated @code{Ada_Main} package.
27745
27746 The code is standard Ada in all respects, and can be processed by any
27747 tools that handle Ada. In particular, it is possible to use the debugger
27748 in Ada mode to debug the generated @code{Ada_Main} package. For example,
27749 suppose that for reasons that you do not understand, your program is crashing
27750 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
27751 you can place a breakpoint on the call:
27752
27753 @smallexample @c ada
27754 Ada.Text_Io'Elab_Body;
27755 @end smallexample
27756
27757 @noindent
27758 and trace the elaboration routine for this package to find out where
27759 the problem might be (more usually of course you would be debugging
27760 elaboration code in your own application).
27761
27762 @node Elaboration Order Handling in GNAT
27763 @appendix Elaboration Order Handling in GNAT
27764 @cindex Order of elaboration
27765 @cindex Elaboration control
27766
27767 @menu
27768 * Elaboration Code::
27769 * Checking the Elaboration Order::
27770 * Controlling the Elaboration Order::
27771 * Controlling Elaboration in GNAT - Internal Calls::
27772 * Controlling Elaboration in GNAT - External Calls::
27773 * Default Behavior in GNAT - Ensuring Safety::
27774 * Treatment of Pragma Elaborate::
27775 * Elaboration Issues for Library Tasks::
27776 * Mixing Elaboration Models::
27777 * What to Do If the Default Elaboration Behavior Fails::
27778 * Elaboration for Access-to-Subprogram Values::
27779 * Summary of Procedures for Elaboration Control::
27780 * Other Elaboration Order Considerations::
27781 @end menu
27782
27783 @noindent
27784 This chapter describes the handling of elaboration code in Ada and
27785 in GNAT, and discusses how the order of elaboration of program units can
27786 be controlled in GNAT, either automatically or with explicit programming
27787 features.
27788
27789 @node Elaboration Code
27790 @section Elaboration Code
27791
27792 @noindent
27793 Ada provides rather general mechanisms for executing code at elaboration
27794 time, that is to say before the main program starts executing. Such code arises
27795 in three contexts:
27796
27797 @table @asis
27798 @item Initializers for variables.
27799 Variables declared at the library level, in package specs or bodies, can
27800 require initialization that is performed at elaboration time, as in:
27801 @smallexample @c ada
27802 @cartouche
27803 Sqrt_Half : Float := Sqrt (0.5);
27804 @end cartouche
27805 @end smallexample
27806
27807 @item Package initialization code
27808 Code in a @code{BEGIN-END} section at the outer level of a package body is
27809 executed as part of the package body elaboration code.
27810
27811 @item Library level task allocators
27812 Tasks that are declared using task allocators at the library level
27813 start executing immediately and hence can execute at elaboration time.
27814 @end table
27815
27816 @noindent
27817 Subprogram calls are possible in any of these contexts, which means that
27818 any arbitrary part of the program may be executed as part of the elaboration
27819 code. It is even possible to write a program which does all its work at
27820 elaboration time, with a null main program, although stylistically this
27821 would usually be considered an inappropriate way to structure
27822 a program.
27823
27824 An important concern arises in the context of elaboration code:
27825 we have to be sure that it is executed in an appropriate order. What we
27826 have is a series of elaboration code sections, potentially one section
27827 for each unit in the program. It is important that these execute
27828 in the correct order. Correctness here means that, taking the above
27829 example of the declaration of @code{Sqrt_Half},
27830 if some other piece of
27831 elaboration code references @code{Sqrt_Half},
27832 then it must run after the
27833 section of elaboration code that contains the declaration of
27834 @code{Sqrt_Half}.
27835
27836 There would never be any order of elaboration problem if we made a rule
27837 that whenever you @code{with} a unit, you must elaborate both the spec and body
27838 of that unit before elaborating the unit doing the @code{with}'ing:
27839
27840 @smallexample @c ada
27841 @group
27842 @cartouche
27843 with Unit_1;
27844 package Unit_2 is @dots{}
27845 @end cartouche
27846 @end group
27847 @end smallexample
27848
27849 @noindent
27850 would require that both the body and spec of @code{Unit_1} be elaborated
27851 before the spec of @code{Unit_2}. However, a rule like that would be far too
27852 restrictive. In particular, it would make it impossible to have routines
27853 in separate packages that were mutually recursive.
27854
27855 You might think that a clever enough compiler could look at the actual
27856 elaboration code and determine an appropriate correct order of elaboration,
27857 but in the general case, this is not possible. Consider the following
27858 example.
27859
27860 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
27861 that references
27862 the variable @code{Sqrt_1}, which is declared in the elaboration code
27863 of the body of @code{Unit_1}:
27864
27865 @smallexample @c ada
27866 @cartouche
27867 Sqrt_1 : Float := Sqrt (0.1);
27868 @end cartouche
27869 @end smallexample
27870
27871 @noindent
27872 The elaboration code of the body of @code{Unit_1} also contains:
27873
27874 @smallexample @c ada
27875 @group
27876 @cartouche
27877 if expression_1 = 1 then
27878    Q := Unit_2.Func_2;
27879 end if;
27880 @end cartouche
27881 @end group
27882 @end smallexample
27883
27884 @noindent
27885 @code{Unit_2} is exactly parallel,
27886 it has a procedure @code{Func_2} that references
27887 the variable @code{Sqrt_2}, which is declared in the elaboration code of
27888 the body @code{Unit_2}:
27889
27890 @smallexample @c ada
27891 @cartouche
27892 Sqrt_2 : Float := Sqrt (0.1);
27893 @end cartouche
27894 @end smallexample
27895
27896 @noindent
27897 The elaboration code of the body of @code{Unit_2} also contains:
27898
27899 @smallexample @c ada
27900 @group
27901 @cartouche
27902 if expression_2 = 2 then
27903    Q := Unit_1.Func_1;
27904 end if;
27905 @end cartouche
27906 @end group
27907 @end smallexample
27908
27909 @noindent
27910 Now the question is, which of the following orders of elaboration is
27911 acceptable:
27912
27913 @smallexample
27914 @group
27915 Spec of Unit_1
27916 Spec of Unit_2
27917 Body of Unit_1
27918 Body of Unit_2
27919 @end group
27920 @end smallexample
27921
27922 @noindent
27923 or
27924
27925 @smallexample
27926 @group
27927 Spec of Unit_2
27928 Spec of Unit_1
27929 Body of Unit_2
27930 Body of Unit_1
27931 @end group
27932 @end smallexample
27933
27934 @noindent
27935 If you carefully analyze the flow here, you will see that you cannot tell
27936 at compile time the answer to this question.
27937 If @code{expression_1} is not equal to 1,
27938 and @code{expression_2} is not equal to 2,
27939 then either order is acceptable, because neither of the function calls is
27940 executed. If both tests evaluate to true, then neither order is acceptable
27941 and in fact there is no correct order.
27942
27943 If one of the two expressions is true, and the other is false, then one
27944 of the above orders is correct, and the other is incorrect. For example,
27945 if @code{expression_1} /= 1 and @code{expression_2} = 2,
27946 then the call to @code{Func_1}
27947 will occur, but not the call to @code{Func_2.}
27948 This means that it is essential
27949 to elaborate the body of @code{Unit_1} before
27950 the body of @code{Unit_2}, so the first
27951 order of elaboration is correct and the second is wrong.
27952
27953 By making @code{expression_1} and @code{expression_2}
27954 depend on input data, or perhaps
27955 the time of day, we can make it impossible for the compiler or binder
27956 to figure out which of these expressions will be true, and hence it
27957 is impossible to guarantee a safe order of elaboration at run time.
27958
27959 @node Checking the Elaboration Order
27960 @section Checking the Elaboration Order
27961
27962 @noindent
27963 In some languages that involve the same kind of elaboration problems,
27964 e.g.@: Java and C++, the programmer is expected to worry about these
27965 ordering problems himself, and it is common to
27966 write a program in which an incorrect elaboration order  gives
27967 surprising results, because it references variables before they
27968 are initialized.
27969 Ada is designed to be a safe language, and a programmer-beware approach is
27970 clearly not sufficient. Consequently, the language provides three lines
27971 of defense:
27972
27973 @table @asis
27974 @item Standard rules
27975 Some standard rules restrict the possible choice of elaboration
27976 order. In particular, if you @code{with} a unit, then its spec is always
27977 elaborated before the unit doing the @code{with}. Similarly, a parent
27978 spec is always elaborated before the child spec, and finally
27979 a spec is always elaborated before its corresponding body.
27980
27981 @item Dynamic elaboration checks
27982 @cindex Elaboration checks
27983 @cindex Checks, elaboration
27984 Dynamic checks are made at run time, so that if some entity is accessed
27985 before it is elaborated (typically  by means of a subprogram call)
27986 then the exception (@code{Program_Error}) is raised.
27987
27988 @item Elaboration control
27989 Facilities are provided for the programmer to specify the desired order
27990 of elaboration.
27991 @end table
27992
27993 Let's look at these facilities in more detail. First, the rules for
27994 dynamic checking. One possible rule would be simply to say that the
27995 exception is raised if you access a variable which has not yet been
27996 elaborated. The trouble with this approach is that it could require
27997 expensive checks on every variable reference. Instead Ada has two
27998 rules which are a little more restrictive, but easier to check, and
27999 easier to state:
28000
28001 @table @asis
28002 @item Restrictions on calls
28003 A subprogram can only be called at elaboration time if its body
28004 has been elaborated. The rules for elaboration given above guarantee
28005 that the spec of the subprogram has been elaborated before the
28006 call, but not the body. If this rule is violated, then the
28007 exception @code{Program_Error} is raised.
28008
28009 @item Restrictions on instantiations
28010 A generic unit can only be instantiated if the body of the generic
28011 unit has been elaborated. Again, the rules for elaboration given above
28012 guarantee that the spec of the generic unit has been elaborated
28013 before the instantiation, but not the body. If this rule is
28014 violated, then the exception @code{Program_Error} is raised.
28015 @end table
28016
28017 @noindent
28018 The idea is that if the body has been elaborated, then any variables
28019 it references must have been elaborated; by checking for the body being
28020 elaborated we guarantee that none of its references causes any
28021 trouble. As we noted above, this is a little too restrictive, because a
28022 subprogram that has no non-local references in its body may in fact be safe
28023 to call. However, it really would be unsafe to rely on this, because
28024 it would mean that the caller was aware of details of the implementation
28025 in the body. This goes against the basic tenets of Ada.
28026
28027 A plausible implementation can be described as follows.
28028 A Boolean variable is associated with each subprogram
28029 and each generic unit. This variable is initialized to False, and is set to
28030 True at the point body is elaborated. Every call or instantiation checks the
28031 variable, and raises @code{Program_Error} if the variable is False.
28032
28033 Note that one might think that it would be good enough to have one Boolean
28034 variable for each package, but that would not deal with cases of trying
28035 to call a body in the same package as the call
28036 that has not been elaborated yet.
28037 Of course a compiler may be able to do enough analysis to optimize away
28038 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
28039 does such optimizations, but still the easiest conceptual model is to
28040 think of there being one variable per subprogram.
28041
28042 @node Controlling the Elaboration Order
28043 @section Controlling the Elaboration Order
28044
28045 @noindent
28046 In the previous section we discussed the rules in Ada which ensure
28047 that @code{Program_Error} is raised if an incorrect elaboration order is
28048 chosen. This prevents erroneous executions, but we need mechanisms to
28049 specify a correct execution and avoid the exception altogether.
28050 To achieve this, Ada provides a number of features for controlling
28051 the order of elaboration. We discuss these features in this section.
28052
28053 First, there are several ways of indicating to the compiler that a given
28054 unit has no elaboration problems:
28055
28056 @table @asis
28057 @item packages that do not require a body
28058 A library package that does not require a body does not permit
28059 a body (this rule was introduced in Ada 95).
28060 Thus if we have a such a package, as in:
28061
28062 @smallexample @c ada
28063 @group
28064 @cartouche
28065 package Definitions is
28066    generic
28067       type m is new integer;
28068    package Subp is
28069       type a is array (1 .. 10) of m;
28070       type b is array (1 .. 20) of m;
28071    end Subp;
28072 end Definitions;
28073 @end cartouche
28074 @end group
28075 @end smallexample
28076
28077 @noindent
28078 A package that @code{with}'s @code{Definitions} may safely instantiate
28079 @code{Definitions.Subp} because the compiler can determine that there
28080 definitely is no package body to worry about in this case
28081
28082 @item pragma Pure
28083 @cindex pragma Pure
28084 @findex Pure
28085 Places sufficient restrictions on a unit to guarantee that
28086 no call to any subprogram in the unit can result in an
28087 elaboration problem. This means that the compiler does not need
28088 to worry about the point of elaboration of such units, and in
28089 particular, does not need to check any calls to any subprograms
28090 in this unit.
28091
28092 @item pragma Preelaborate
28093 @findex Preelaborate
28094 @cindex pragma Preelaborate
28095 This pragma places slightly less stringent restrictions on a unit than
28096 does pragma Pure,
28097 but these restrictions are still sufficient to ensure that there
28098 are no elaboration problems with any calls to the unit.
28099
28100 @item pragma Elaborate_Body
28101 @findex Elaborate_Body
28102 @cindex pragma Elaborate_Body
28103 This pragma requires that the body of a unit be elaborated immediately
28104 after its spec. Suppose a unit @code{A} has such a pragma,
28105 and unit @code{B} does
28106 a @code{with} of unit @code{A}. Recall that the standard rules require
28107 the spec of unit @code{A}
28108 to be elaborated before the @code{with}'ing unit; given the pragma in
28109 @code{A}, we also know that the body of @code{A}
28110 will be elaborated before @code{B}, so
28111 that calls to @code{A} are safe and do not need a check.
28112 @end table
28113
28114 @noindent
28115 Note that,
28116 unlike pragma @code{Pure} and pragma @code{Preelaborate},
28117 the use of
28118 @code{Elaborate_Body} does not guarantee that the program is
28119 free of elaboration problems, because it may not be possible
28120 to satisfy the requested elaboration order.
28121 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
28122 If a programmer
28123 marks @code{Unit_1} as @code{Elaborate_Body},
28124 and not @code{Unit_2,} then the order of
28125 elaboration will be:
28126
28127 @smallexample
28128 @group
28129 Spec of Unit_2
28130 Spec of Unit_1
28131 Body of Unit_1
28132 Body of Unit_2
28133 @end group
28134 @end smallexample
28135
28136 @noindent
28137 Now that means that the call to @code{Func_1} in @code{Unit_2}
28138 need not be checked,
28139 it must be safe. But the call to @code{Func_2} in
28140 @code{Unit_1} may still fail if
28141 @code{Expression_1} is equal to 1,
28142 and the programmer must still take
28143 responsibility for this not being the case.
28144
28145 If all units carry a pragma @code{Elaborate_Body}, then all problems are
28146 eliminated, except for calls entirely within a body, which are
28147 in any case fully under programmer control. However, using the pragma
28148 everywhere is not always possible.
28149 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
28150 we marked both of them as having pragma @code{Elaborate_Body}, then
28151 clearly there would be no possible elaboration order.
28152
28153 The above pragmas allow a server to guarantee safe use by clients, and
28154 clearly this is the preferable approach. Consequently a good rule
28155 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
28156 and if this is not possible,
28157 mark them as @code{Elaborate_Body} if possible.
28158 As we have seen, there are situations where neither of these
28159 three pragmas can be used.
28160 So we also provide methods for clients to control the
28161 order of elaboration of the servers on which they depend:
28162
28163 @table @asis
28164 @item pragma Elaborate (unit)
28165 @findex Elaborate
28166 @cindex pragma Elaborate
28167 This pragma is placed in the context clause, after a @code{with} clause,
28168 and it requires that the body of the named unit be elaborated before
28169 the unit in which the pragma occurs. The idea is to use this pragma
28170 if the current unit calls at elaboration time, directly or indirectly,
28171 some subprogram in the named unit.
28172
28173 @item pragma Elaborate_All (unit)
28174 @findex Elaborate_All
28175 @cindex pragma Elaborate_All
28176 This is a stronger version of the Elaborate pragma. Consider the
28177 following example:
28178
28179 @smallexample
28180 Unit A @code{with}'s unit B and calls B.Func in elab code
28181 Unit B @code{with}'s unit C, and B.Func calls C.Func
28182 @end smallexample
28183
28184 @noindent
28185 Now if we put a pragma @code{Elaborate (B)}
28186 in unit @code{A}, this ensures that the
28187 body of @code{B} is elaborated before the call, but not the
28188 body of @code{C}, so
28189 the call to @code{C.Func} could still cause @code{Program_Error} to
28190 be raised.
28191
28192 The effect of a pragma @code{Elaborate_All} is stronger, it requires
28193 not only that the body of the named unit be elaborated before the
28194 unit doing the @code{with}, but also the bodies of all units that the
28195 named unit uses, following @code{with} links transitively. For example,
28196 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
28197 then it requires
28198 not only that the body of @code{B} be elaborated before @code{A},
28199 but also the
28200 body of @code{C}, because @code{B} @code{with}'s @code{C}.
28201 @end table
28202
28203 @noindent
28204 We are now in a position to give a usage rule in Ada for avoiding
28205 elaboration problems, at least if dynamic dispatching and access to
28206 subprogram values are not used. We will handle these cases separately
28207 later.
28208
28209 The rule is simple. If a unit has elaboration code that can directly or
28210 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
28211 a generic package in a @code{with}'ed unit,
28212 then if the @code{with}'ed unit does not have
28213 pragma @code{Pure} or @code{Preelaborate}, then the client should have
28214 a pragma @code{Elaborate_All}
28215 for the @code{with}'ed unit. By following this rule a client is
28216 assured that calls can be made without risk of an exception.
28217
28218 For generic subprogram instantiations, the rule can be relaxed to
28219 require only a pragma @code{Elaborate} since elaborating the body
28220 of a subprogram cannot cause any transitive elaboration (we are
28221 not calling the subprogram in this case, just elaborating its
28222 declaration).
28223
28224 If this rule is not followed, then a program may be in one of four
28225 states:
28226
28227 @table @asis
28228 @item No order exists
28229 No order of elaboration exists which follows the rules, taking into
28230 account any @code{Elaborate}, @code{Elaborate_All},
28231 or @code{Elaborate_Body} pragmas. In
28232 this case, an Ada compiler must diagnose the situation at bind
28233 time, and refuse to build an executable program.
28234
28235 @item One or more orders exist, all incorrect
28236 One or more acceptable elaboration orders exist, and all of them
28237 generate an elaboration order problem. In this case, the binder
28238 can build an executable program, but @code{Program_Error} will be raised
28239 when the program is run.
28240
28241 @item Several orders exist, some right, some incorrect
28242 One or more acceptable elaboration orders exists, and some of them
28243 work, and some do not. The programmer has not controlled
28244 the order of elaboration, so the binder may or may not pick one of
28245 the correct orders, and the program may or may not raise an
28246 exception when it is run. This is the worst case, because it means
28247 that the program may fail when moved to another compiler, or even
28248 another version of the same compiler.
28249
28250 @item One or more orders exists, all correct
28251 One ore more acceptable elaboration orders exist, and all of them
28252 work. In this case the program runs successfully. This state of
28253 affairs can be guaranteed by following the rule we gave above, but
28254 may be true even if the rule is not followed.
28255 @end table
28256
28257 @noindent
28258 Note that one additional advantage of following our rules on the use
28259 of @code{Elaborate} and @code{Elaborate_All}
28260 is that the program continues to stay in the ideal (all orders OK) state
28261 even if maintenance
28262 changes some bodies of some units. Conversely, if a program that does
28263 not follow this rule happens to be safe at some point, this state of affairs
28264 may deteriorate silently as a result of maintenance changes.
28265
28266 You may have noticed that the above discussion did not mention
28267 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
28268 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
28269 code in the body makes calls to some other unit, so it is still necessary
28270 to use @code{Elaborate_All} on such units.
28271
28272 @node Controlling Elaboration in GNAT - Internal Calls
28273 @section Controlling Elaboration in GNAT - Internal Calls
28274
28275 @noindent
28276 In the case of internal calls, i.e., calls within a single package, the
28277 programmer has full control over the order of elaboration, and it is up
28278 to the programmer to elaborate declarations in an appropriate order. For
28279 example writing:
28280
28281 @smallexample @c ada
28282 @group
28283 @cartouche
28284 function One return Float;
28285
28286 Q : Float := One;
28287
28288 function One return Float is
28289 begin
28290      return 1.0;
28291 end One;
28292 @end cartouche
28293 @end group
28294 @end smallexample
28295
28296 @noindent
28297 will obviously raise @code{Program_Error} at run time, because function
28298 One will be called before its body is elaborated. In this case GNAT will
28299 generate a warning that the call will raise @code{Program_Error}:
28300
28301 @smallexample
28302 @group
28303 @cartouche
28304  1. procedure y is
28305  2.    function One return Float;
28306  3.
28307  4.    Q : Float := One;
28308                     |
28309     >>> warning: cannot call "One" before body is elaborated
28310     >>> warning: Program_Error will be raised at run time
28311
28312  5.
28313  6.    function One return Float is
28314  7.    begin
28315  8.         return 1.0;
28316  9.    end One;
28317 10.
28318 11. begin
28319 12.    null;
28320 13. end;
28321 @end cartouche
28322 @end group
28323 @end smallexample
28324
28325 @noindent
28326 Note that in this particular case, it is likely that the call is safe, because
28327 the function @code{One} does not access any global variables.
28328 Nevertheless in Ada, we do not want the validity of the check to depend on
28329 the contents of the body (think about the separate compilation case), so this
28330 is still wrong, as we discussed in the previous sections.
28331
28332 The error is easily corrected by rearranging the declarations so that the
28333 body of @code{One} appears before the declaration containing the call
28334 (note that in Ada 95 and Ada 2005,
28335 declarations can appear in any order, so there is no restriction that
28336 would prevent this reordering, and if we write:
28337
28338 @smallexample @c ada
28339 @group
28340 @cartouche
28341 function One return Float;
28342
28343 function One return Float is
28344 begin
28345      return 1.0;
28346 end One;
28347
28348 Q : Float := One;
28349 @end cartouche
28350 @end group
28351 @end smallexample
28352
28353 @noindent
28354 then all is well, no warning is generated, and no
28355 @code{Program_Error} exception
28356 will be raised.
28357 Things are more complicated when a chain of subprograms is executed:
28358
28359 @smallexample @c ada
28360 @group
28361 @cartouche
28362 function A return Integer;
28363 function B return Integer;
28364 function C return Integer;
28365
28366 function B return Integer is begin return A; end;
28367 function C return Integer is begin return B; end;
28368
28369 X : Integer := C;
28370
28371 function A return Integer is begin return 1; end;
28372 @end cartouche
28373 @end group
28374 @end smallexample
28375
28376 @noindent
28377 Now the call to @code{C}
28378 at elaboration time in the declaration of @code{X} is correct, because
28379 the body of @code{C} is already elaborated,
28380 and the call to @code{B} within the body of
28381 @code{C} is correct, but the call
28382 to @code{A} within the body of @code{B} is incorrect, because the body
28383 of @code{A} has not been elaborated, so @code{Program_Error}
28384 will be raised on the call to @code{A}.
28385 In this case GNAT will generate a
28386 warning that @code{Program_Error} may be
28387 raised at the point of the call. Let's look at the warning:
28388
28389 @smallexample
28390 @group
28391 @cartouche
28392  1. procedure x is
28393  2.    function A return Integer;
28394  3.    function B return Integer;
28395  4.    function C return Integer;
28396  5.
28397  6.    function B return Integer is begin return A; end;
28398                                                     |
28399     >>> warning: call to "A" before body is elaborated may
28400                  raise Program_Error
28401     >>> warning: "B" called at line 7
28402     >>> warning: "C" called at line 9
28403
28404  7.    function C return Integer is begin return B; end;
28405  8.
28406  9.    X : Integer := C;
28407 10.
28408 11.    function A return Integer is begin return 1; end;
28409 12.
28410 13. begin
28411 14.    null;
28412 15. end;
28413 @end cartouche
28414 @end group
28415 @end smallexample
28416
28417 @noindent
28418 Note that the message here says ``may raise'', instead of the direct case,
28419 where the message says ``will be raised''. That's because whether
28420 @code{A} is
28421 actually called depends in general on run-time flow of control.
28422 For example, if the body of @code{B} said
28423
28424 @smallexample @c ada
28425 @group
28426 @cartouche
28427 function B return Integer is
28428 begin
28429    if some-condition-depending-on-input-data then
28430       return A;
28431    else
28432       return 1;
28433    end if;
28434 end B;
28435 @end cartouche
28436 @end group
28437 @end smallexample
28438
28439 @noindent
28440 then we could not know until run time whether the incorrect call to A would
28441 actually occur, so @code{Program_Error} might
28442 or might not be raised. It is possible for a compiler to
28443 do a better job of analyzing bodies, to
28444 determine whether or not @code{Program_Error}
28445 might be raised, but it certainly
28446 couldn't do a perfect job (that would require solving the halting problem
28447 and is provably impossible), and because this is a warning anyway, it does
28448 not seem worth the effort to do the analysis. Cases in which it
28449 would be relevant are rare.
28450
28451 In practice, warnings of either of the forms given
28452 above will usually correspond to
28453 real errors, and should be examined carefully and eliminated.
28454 In the rare case where a warning is bogus, it can be suppressed by any of
28455 the following methods:
28456
28457 @itemize @bullet
28458 @item
28459 Compile with the @option{-gnatws} switch set
28460
28461 @item
28462 Suppress @code{Elaboration_Check} for the called subprogram
28463
28464 @item
28465 Use pragma @code{Warnings_Off} to turn warnings off for the call
28466 @end itemize
28467
28468 @noindent
28469 For the internal elaboration check case,
28470 GNAT by default generates the
28471 necessary run-time checks to ensure
28472 that @code{Program_Error} is raised if any
28473 call fails an elaboration check. Of course this can only happen if a
28474 warning has been issued as described above. The use of pragma
28475 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
28476 some of these checks, meaning that it may be possible (but is not
28477 guaranteed) for a program to be able to call a subprogram whose body
28478 is not yet elaborated, without raising a @code{Program_Error} exception.
28479
28480 @node Controlling Elaboration in GNAT - External Calls
28481 @section Controlling Elaboration in GNAT - External Calls
28482
28483 @noindent
28484 The previous section discussed the case in which the execution of a
28485 particular thread of elaboration code occurred entirely within a
28486 single unit. This is the easy case to handle, because a programmer
28487 has direct and total control over the order of elaboration, and
28488 furthermore, checks need only be generated in cases which are rare
28489 and which the compiler can easily detect.
28490 The situation is more complex when separate compilation is taken into account.
28491 Consider the following:
28492
28493 @smallexample @c ada
28494 @cartouche
28495 @group
28496 package Math is
28497    function Sqrt (Arg : Float) return Float;
28498 end Math;
28499
28500 package body Math is
28501    function Sqrt (Arg : Float) return Float is
28502    begin
28503          @dots{}
28504    end Sqrt;
28505 end Math;
28506 @end group
28507 @group
28508 with Math;
28509 package Stuff is
28510    X : Float := Math.Sqrt (0.5);
28511 end Stuff;
28512
28513 with Stuff;
28514 procedure Main is
28515 begin
28516    @dots{}
28517 end Main;
28518 @end group
28519 @end cartouche
28520 @end smallexample
28521
28522 @noindent
28523 where @code{Main} is the main program. When this program is executed, the
28524 elaboration code must first be executed, and one of the jobs of the
28525 binder is to determine the order in which the units of a program are
28526 to be elaborated. In this case we have four units: the spec and body
28527 of @code{Math},
28528 the spec of @code{Stuff} and the body of @code{Main}).
28529 In what order should the four separate sections of elaboration code
28530 be executed?
28531
28532 There are some restrictions in the order of elaboration that the binder
28533 can choose. In particular, if unit U has a @code{with}
28534 for a package @code{X}, then you
28535 are assured that the spec of @code{X}
28536 is elaborated before U , but you are
28537 not assured that the body of @code{X}
28538 is elaborated before U.
28539 This means that in the above case, the binder is allowed to choose the
28540 order:
28541
28542 @smallexample
28543 spec of Math
28544 spec of Stuff
28545 body of Math
28546 body of Main
28547 @end smallexample
28548
28549 @noindent
28550 but that's not good, because now the call to @code{Math.Sqrt}
28551 that happens during
28552 the elaboration of the @code{Stuff}
28553 spec happens before the body of @code{Math.Sqrt} is
28554 elaborated, and hence causes @code{Program_Error} exception to be raised.
28555 At first glance, one might say that the binder is misbehaving, because
28556 obviously you want to elaborate the body of something you @code{with}
28557 first, but
28558 that is not a general rule that can be followed in all cases. Consider
28559
28560 @smallexample @c ada
28561 @group
28562 @cartouche
28563 package X is @dots{}
28564
28565 package Y is @dots{}
28566
28567 with X;
28568 package body Y is @dots{}
28569
28570 with Y;
28571 package body X is @dots{}
28572 @end cartouche
28573 @end group
28574 @end smallexample
28575
28576 @noindent
28577 This is a common arrangement, and, apart from the order of elaboration
28578 problems that might arise in connection with elaboration code, this works fine.
28579 A rule that says that you must first elaborate the body of anything you
28580 @code{with} cannot work in this case:
28581 the body of @code{X} @code{with}'s @code{Y},
28582 which means you would have to
28583 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
28584 which means
28585 you have to elaborate the body of @code{X} first, but @dots{} and we have a
28586 loop that cannot be broken.
28587
28588 It is true that the binder can in many cases guess an order of elaboration
28589 that is unlikely to cause a @code{Program_Error}
28590 exception to be raised, and it tries to do so (in the
28591 above example of @code{Math/Stuff/Spec}, the GNAT binder will
28592 by default
28593 elaborate the body of @code{Math} right after its spec, so all will be well).
28594
28595 However, a program that blindly relies on the binder to be helpful can
28596 get into trouble, as we discussed in the previous sections, so
28597 GNAT
28598 provides a number of facilities for assisting the programmer in
28599 developing programs that are robust with respect to elaboration order.
28600
28601 @node Default Behavior in GNAT - Ensuring Safety
28602 @section Default Behavior in GNAT - Ensuring Safety
28603
28604 @noindent
28605 The default behavior in GNAT ensures elaboration safety. In its
28606 default mode GNAT implements the
28607 rule we previously described as the right approach. Let's restate it:
28608
28609 @itemize
28610 @item
28611 @emph{If a unit has elaboration code that can directly or indirectly make a
28612 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
28613 package in a @code{with}'ed unit, then if the @code{with}'ed unit
28614 does not have pragma @code{Pure} or
28615 @code{Preelaborate}, then the client should have an
28616 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
28617
28618 @emph{In the case of instantiating a generic subprogram, it is always
28619 sufficient to have only an @code{Elaborate} pragma for the
28620 @code{with}'ed unit.}
28621 @end itemize
28622
28623 @noindent
28624 By following this rule a client is assured that calls and instantiations
28625 can be made without risk of an exception.
28626
28627 In this mode GNAT traces all calls that are potentially made from
28628 elaboration code, and puts in any missing implicit @code{Elaborate}
28629 and @code{Elaborate_All} pragmas.
28630 The advantage of this approach is that no elaboration problems
28631 are possible if the binder can find an elaboration order that is
28632 consistent with these implicit @code{Elaborate} and
28633 @code{Elaborate_All} pragmas. The
28634 disadvantage of this approach is that no such order may exist.
28635
28636 If the binder does not generate any diagnostics, then it means that it has
28637 found an elaboration order that is guaranteed to be safe. However, the binder
28638 may still be relying on implicitly generated @code{Elaborate} and
28639 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
28640 guaranteed.
28641
28642 If it is important to guarantee portability, then the compilations should
28643 use the
28644 @option{-gnatwl}
28645 (warn on elaboration problems) switch. This will cause warning messages
28646 to be generated indicating the missing @code{Elaborate} and
28647 @code{Elaborate_All} pragmas.
28648 Consider the following source program:
28649
28650 @smallexample @c ada
28651 @group
28652 @cartouche
28653 with k;
28654 package j is
28655   m : integer := k.r;
28656 end;
28657 @end cartouche
28658 @end group
28659 @end smallexample
28660
28661 @noindent
28662 where it is clear that there
28663 should be a pragma @code{Elaborate_All}
28664 for unit @code{k}. An implicit pragma will be generated, and it is
28665 likely that the binder will be able to honor it. However, if you want
28666 to port this program to some other Ada compiler than GNAT.
28667 it is safer to include the pragma explicitly in the source. If this
28668 unit is compiled with the
28669 @option{-gnatwl}
28670 switch, then the compiler outputs a warning:
28671
28672 @smallexample
28673 @group
28674 @cartouche
28675 1. with k;
28676 2. package j is
28677 3.   m : integer := k.r;
28678                      |
28679    >>> warning: call to "r" may raise Program_Error
28680    >>> warning: missing pragma Elaborate_All for "k"
28681
28682 4. end;
28683 @end cartouche
28684 @end group
28685 @end smallexample
28686
28687 @noindent
28688 and these warnings can be used as a guide for supplying manually
28689 the missing pragmas. It is usually a bad idea to use this warning
28690 option during development. That's because it will warn you when
28691 you need to put in a pragma, but cannot warn you when it is time
28692 to take it out. So the use of pragma @code{Elaborate_All} may lead to
28693 unnecessary dependencies and even false circularities.
28694
28695 This default mode is more restrictive than the Ada Reference
28696 Manual, and it is possible to construct programs which will compile
28697 using the dynamic model described there, but will run into a
28698 circularity using the safer static model we have described.
28699
28700 Of course any Ada compiler must be able to operate in a mode
28701 consistent with the requirements of the Ada Reference Manual,
28702 and in particular must have the capability of implementing the
28703 standard dynamic model of elaboration with run-time checks.
28704
28705 In GNAT, this standard mode can be achieved either by the use of
28706 the @option{-gnatE} switch on the compiler (@command{gcc} or
28707 @command{gnatmake}) command, or by the use of the configuration pragma:
28708
28709 @smallexample @c ada
28710 pragma Elaboration_Checks (DYNAMIC);
28711 @end smallexample
28712
28713 @noindent
28714 Either approach will cause the unit affected to be compiled using the
28715 standard dynamic run-time elaboration checks described in the Ada
28716 Reference Manual. The static model is generally preferable, since it
28717 is clearly safer to rely on compile and link time checks rather than
28718 run-time checks. However, in the case of legacy code, it may be
28719 difficult to meet the requirements of the static model. This
28720 issue is further discussed in
28721 @ref{What to Do If the Default Elaboration Behavior Fails}.
28722
28723 Note that the static model provides a strict subset of the allowed
28724 behavior and programs of the Ada Reference Manual, so if you do
28725 adhere to the static model and no circularities exist,
28726 then you are assured that your program will
28727 work using the dynamic model, providing that you remove any
28728 pragma Elaborate statements from the source.
28729
28730 @node Treatment of Pragma Elaborate
28731 @section Treatment of Pragma Elaborate
28732 @cindex Pragma Elaborate
28733
28734 @noindent
28735 The use of @code{pragma Elaborate}
28736 should generally be avoided in Ada 95 and Ada 2005 programs,
28737 since there is no guarantee that transitive calls
28738 will be properly handled. Indeed at one point, this pragma was placed
28739 in Annex J (Obsolescent Features), on the grounds that it is never useful.
28740
28741 Now that's a bit restrictive. In practice, the case in which
28742 @code{pragma Elaborate} is useful is when the caller knows that there
28743 are no transitive calls, or that the called unit contains all necessary
28744 transitive @code{pragma Elaborate} statements, and legacy code often
28745 contains such uses.
28746
28747 Strictly speaking the static mode in GNAT should ignore such pragmas,
28748 since there is no assurance at compile time that the necessary safety
28749 conditions are met. In practice, this would cause GNAT to be incompatible
28750 with correctly written Ada 83 code that had all necessary
28751 @code{pragma Elaborate} statements in place. Consequently, we made the
28752 decision that GNAT in its default mode will believe that if it encounters
28753 a @code{pragma Elaborate} then the programmer knows what they are doing,
28754 and it will trust that no elaboration errors can occur.
28755
28756 The result of this decision is two-fold. First to be safe using the
28757 static mode, you should remove all @code{pragma Elaborate} statements.
28758 Second, when fixing circularities in existing code, you can selectively
28759 use @code{pragma Elaborate} statements to convince the static mode of
28760 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
28761 statement.
28762
28763 When using the static mode with @option{-gnatwl}, any use of
28764 @code{pragma Elaborate} will generate a warning about possible
28765 problems.
28766
28767 @node Elaboration Issues for Library Tasks
28768 @section Elaboration Issues for Library Tasks
28769 @cindex Library tasks, elaboration issues
28770 @cindex Elaboration of library tasks
28771
28772 @noindent
28773 In this section we examine special elaboration issues that arise for
28774 programs that declare library level tasks.
28775
28776 Generally the model of execution of an Ada program is that all units are
28777 elaborated, and then execution of the program starts. However, the
28778 declaration of library tasks definitely does not fit this model. The
28779 reason for this is that library tasks start as soon as they are declared
28780 (more precisely, as soon as the statement part of the enclosing package
28781 body is reached), that is to say before elaboration
28782 of the program is complete. This means that if such a task calls a
28783 subprogram, or an entry in another task, the callee may or may not be
28784 elaborated yet, and in the standard
28785 Reference Manual model of dynamic elaboration checks, you can even
28786 get timing dependent Program_Error exceptions, since there can be
28787 a race between the elaboration code and the task code.
28788
28789 The static model of elaboration in GNAT seeks to avoid all such
28790 dynamic behavior, by being conservative, and the conservative
28791 approach in this particular case is to assume that all the code
28792 in a task body is potentially executed at elaboration time if
28793 a task is declared at the library level.
28794
28795 This can definitely result in unexpected circularities. Consider
28796 the following example
28797
28798 @smallexample @c ada
28799 package Decls is
28800   task Lib_Task is
28801      entry Start;
28802   end Lib_Task;
28803
28804   type My_Int is new Integer;
28805
28806   function Ident (M : My_Int) return My_Int;
28807 end Decls;
28808
28809 with Utils;
28810 package body Decls is
28811   task body Lib_Task is
28812   begin
28813      accept Start;
28814      Utils.Put_Val (2);
28815   end Lib_Task;
28816
28817   function Ident (M : My_Int) return My_Int is
28818   begin
28819      return M;
28820   end Ident;
28821 end Decls;
28822
28823 with Decls;
28824 package Utils is
28825   procedure Put_Val (Arg : Decls.My_Int);
28826 end Utils;
28827
28828 with Text_IO;
28829 package body Utils is
28830   procedure Put_Val (Arg : Decls.My_Int) is
28831   begin
28832      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28833   end Put_Val;
28834 end Utils;
28835
28836 with Decls;
28837 procedure Main is
28838 begin
28839    Decls.Lib_Task.Start;
28840 end;
28841 @end smallexample
28842
28843 @noindent
28844 If the above example is compiled in the default static elaboration
28845 mode, then a circularity occurs. The circularity comes from the call
28846 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
28847 this call occurs in elaboration code, we need an implicit pragma
28848 @code{Elaborate_All} for @code{Utils}. This means that not only must
28849 the spec and body of @code{Utils} be elaborated before the body
28850 of @code{Decls}, but also the spec and body of any unit that is
28851 @code{with'ed} by the body of @code{Utils} must also be elaborated before
28852 the body of @code{Decls}. This is the transitive implication of
28853 pragma @code{Elaborate_All} and it makes sense, because in general
28854 the body of @code{Put_Val} might have a call to something in a
28855 @code{with'ed} unit.
28856
28857 In this case, the body of Utils (actually its spec) @code{with's}
28858 @code{Decls}. Unfortunately this means that the body of @code{Decls}
28859 must be elaborated before itself, in case there is a call from the
28860 body of @code{Utils}.
28861
28862 Here is the exact chain of events we are worrying about:
28863
28864 @enumerate
28865 @item
28866 In the body of @code{Decls} a call is made from within the body of a library
28867 task to a subprogram in the package @code{Utils}. Since this call may
28868 occur at elaboration time (given that the task is activated at elaboration
28869 time), we have to assume the worst, i.e., that the
28870 call does happen at elaboration time.
28871
28872 @item
28873 This means that the body and spec of @code{Util} must be elaborated before
28874 the body of @code{Decls} so that this call does not cause an access before
28875 elaboration.
28876
28877 @item
28878 Within the body of @code{Util}, specifically within the body of
28879 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
28880 by this package.
28881
28882 @item
28883 One such @code{with}'ed package is package @code{Decls}, so there
28884 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
28885 In fact there is such a call in this example, but we would have to
28886 assume that there was such a call even if it were not there, since
28887 we are not supposed to write the body of @code{Decls} knowing what
28888 is in the body of @code{Utils}; certainly in the case of the
28889 static elaboration model, the compiler does not know what is in
28890 other bodies and must assume the worst.
28891
28892 @item
28893 This means that the spec and body of @code{Decls} must also be
28894 elaborated before we elaborate the unit containing the call, but
28895 that unit is @code{Decls}! This means that the body of @code{Decls}
28896 must be elaborated before itself, and that's a circularity.
28897 @end enumerate
28898
28899 @noindent
28900 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
28901 the body of @code{Decls} you will get a true Ada Reference Manual
28902 circularity that makes the program illegal.
28903
28904 In practice, we have found that problems with the static model of
28905 elaboration in existing code often arise from library tasks, so
28906 we must address this particular situation.
28907
28908 Note that if we compile and run the program above, using the dynamic model of
28909 elaboration (that is to say use the @option{-gnatE} switch),
28910 then it compiles, binds,
28911 links, and runs, printing the expected result of 2. Therefore in some sense
28912 the circularity here is only apparent, and we need to capture
28913 the properties of this program that  distinguish it from other library-level
28914 tasks that have real elaboration problems.
28915
28916 We have four possible answers to this question:
28917
28918 @itemize @bullet
28919
28920 @item
28921 Use the dynamic model of elaboration.
28922
28923 If we use the @option{-gnatE} switch, then as noted above, the program works.
28924 Why is this? If we examine the task body, it is apparent that the task cannot
28925 proceed past the
28926 @code{accept} statement until after elaboration has been completed, because
28927 the corresponding entry call comes from the main program, not earlier.
28928 This is why the dynamic model works here. But that's really giving
28929 up on a precise analysis, and we prefer to take this approach only if we cannot
28930 solve the
28931 problem in any other manner. So let us examine two ways to reorganize
28932 the program to avoid the potential elaboration problem.
28933
28934 @item
28935 Split library tasks into separate packages.
28936
28937 Write separate packages, so that library tasks are isolated from
28938 other declarations as much as possible. Let us look at a variation on
28939 the above program.
28940
28941 @smallexample @c ada
28942 package Decls1 is
28943   task Lib_Task is
28944      entry Start;
28945   end Lib_Task;
28946 end Decls1;
28947
28948 with Utils;
28949 package body Decls1 is
28950   task body Lib_Task is
28951   begin
28952      accept Start;
28953      Utils.Put_Val (2);
28954   end Lib_Task;
28955 end Decls1;
28956
28957 package Decls2 is
28958   type My_Int is new Integer;
28959   function Ident (M : My_Int) return My_Int;
28960 end Decls2;
28961
28962 with Utils;
28963 package body Decls2 is
28964   function Ident (M : My_Int) return My_Int is
28965   begin
28966      return M;
28967   end Ident;
28968 end Decls2;
28969
28970 with Decls2;
28971 package Utils is
28972   procedure Put_Val (Arg : Decls2.My_Int);
28973 end Utils;
28974
28975 with Text_IO;
28976 package body Utils is
28977   procedure Put_Val (Arg : Decls2.My_Int) is
28978   begin
28979      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
28980   end Put_Val;
28981 end Utils;
28982
28983 with Decls1;
28984 procedure Main is
28985 begin
28986    Decls1.Lib_Task.Start;
28987 end;
28988 @end smallexample
28989
28990 @noindent
28991 All we have done is to split @code{Decls} into two packages, one
28992 containing the library task, and one containing everything else. Now
28993 there is no cycle, and the program compiles, binds, links and executes
28994 using the default static model of elaboration.
28995
28996 @item
28997 Declare separate task types.
28998
28999 A significant part of the problem arises because of the use of the
29000 single task declaration form. This means that the elaboration of
29001 the task type, and the elaboration of the task itself (i.e.@: the
29002 creation of the task) happen at the same time. A good rule
29003 of style in Ada is to always create explicit task types. By
29004 following the additional step of placing task objects in separate
29005 packages from the task type declaration, many elaboration problems
29006 are avoided. Here is another modified example of the example program:
29007
29008 @smallexample @c ada
29009 package Decls is
29010   task type Lib_Task_Type is
29011      entry Start;
29012   end Lib_Task_Type;
29013
29014   type My_Int is new Integer;
29015
29016   function Ident (M : My_Int) return My_Int;
29017 end Decls;
29018
29019 with Utils;
29020 package body Decls is
29021   task body Lib_Task_Type is
29022   begin
29023      accept Start;
29024      Utils.Put_Val (2);
29025   end Lib_Task_Type;
29026
29027   function Ident (M : My_Int) return My_Int is
29028   begin
29029      return M;
29030   end Ident;
29031 end Decls;
29032
29033 with Decls;
29034 package Utils is
29035   procedure Put_Val (Arg : Decls.My_Int);
29036 end Utils;
29037
29038 with Text_IO;
29039 package body Utils is
29040   procedure Put_Val (Arg : Decls.My_Int) is
29041   begin
29042      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
29043   end Put_Val;
29044 end Utils;
29045
29046 with Decls;
29047 package Declst is
29048    Lib_Task : Decls.Lib_Task_Type;
29049 end Declst;
29050
29051 with Declst;
29052 procedure Main is
29053 begin
29054    Declst.Lib_Task.Start;
29055 end;
29056 @end smallexample
29057
29058 @noindent
29059 What we have done here is to replace the @code{task} declaration in
29060 package @code{Decls} with a @code{task type} declaration. Then we
29061 introduce a separate package @code{Declst} to contain the actual
29062 task object. This separates the elaboration issues for
29063 the @code{task type}
29064 declaration, which causes no trouble, from the elaboration issues
29065 of the task object, which is also unproblematic, since it is now independent
29066 of the elaboration of  @code{Utils}.
29067 This separation of concerns also corresponds to
29068 a generally sound engineering principle of separating declarations
29069 from instances. This version of the program also compiles, binds, links,
29070 and executes, generating the expected output.
29071
29072 @item
29073 Use No_Entry_Calls_In_Elaboration_Code restriction.
29074 @cindex No_Entry_Calls_In_Elaboration_Code
29075
29076 The previous two approaches described how a program can be restructured
29077 to avoid the special problems caused by library task bodies. in practice,
29078 however, such restructuring may be difficult to apply to existing legacy code,
29079 so we must consider solutions that do not require massive rewriting.
29080
29081 Let us consider more carefully why our original sample program works
29082 under the dynamic model of elaboration. The reason is that the code
29083 in the task body blocks immediately on the @code{accept}
29084 statement. Now of course there is nothing to prohibit elaboration
29085 code from making entry calls (for example from another library level task),
29086 so we cannot tell in isolation that
29087 the task will not execute the accept statement  during elaboration.
29088
29089 However, in practice it is very unusual to see elaboration code
29090 make any entry calls, and the pattern of tasks starting
29091 at elaboration time and then immediately blocking on @code{accept} or
29092 @code{select} statements is very common. What this means is that
29093 the compiler is being too pessimistic when it analyzes the
29094 whole package body as though it might be executed at elaboration
29095 time.
29096
29097 If we know that the elaboration code contains no entry calls, (a very safe
29098 assumption most of the time, that could almost be made the default
29099 behavior), then we can compile all units of the program under control
29100 of the following configuration pragma:
29101
29102 @smallexample
29103 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
29104 @end smallexample
29105
29106 @noindent
29107 This pragma can be placed in the @file{gnat.adc} file in the usual
29108 manner. If we take our original unmodified program and compile it
29109 in the presence of a @file{gnat.adc} containing the above pragma,
29110 then once again, we can compile, bind, link, and execute, obtaining
29111 the expected result. In the presence of this pragma, the compiler does
29112 not trace calls in a task body, that appear after the first @code{accept}
29113 or @code{select} statement, and therefore does not report a potential
29114 circularity in the original program.
29115
29116 The compiler will check to the extent it can that the above
29117 restriction is not violated, but it is not always possible to do a
29118 complete check at compile time, so it is important to use this
29119 pragma only if the stated restriction is in fact met, that is to say
29120 no task receives an entry call before elaboration of all units is completed.
29121
29122 @end itemize
29123
29124 @node Mixing Elaboration Models
29125 @section Mixing Elaboration Models
29126 @noindent
29127 So far, we have assumed that the entire program is either compiled
29128 using the dynamic model or static model, ensuring consistency. It
29129 is possible to mix the two models, but rules have to be followed
29130 if this mixing is done to ensure that elaboration checks are not
29131 omitted.
29132
29133 The basic rule is that @emph{a unit compiled with the static model cannot
29134 be @code{with'ed} by a unit compiled with the dynamic model}. The
29135 reason for this is that in the static model, a unit assumes that
29136 its clients guarantee to use (the equivalent of) pragma
29137 @code{Elaborate_All} so that no elaboration checks are required
29138 in inner subprograms, and this assumption is violated if the
29139 client is compiled with dynamic checks.
29140
29141 The precise rule is as follows. A unit that is compiled with dynamic
29142 checks can only @code{with} a unit that meets at least one of the
29143 following criteria:
29144
29145 @itemize @bullet
29146
29147 @item
29148 The @code{with'ed} unit is itself compiled with dynamic elaboration
29149 checks (that is with the @option{-gnatE} switch.
29150
29151 @item
29152 The @code{with'ed} unit is an internal GNAT implementation unit from
29153 the System, Interfaces, Ada, or GNAT hierarchies.
29154
29155 @item
29156 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
29157
29158 @item
29159 The @code{with'ing} unit (that is the client) has an explicit pragma
29160 @code{Elaborate_All} for the @code{with'ed} unit.
29161
29162 @end itemize
29163
29164 @noindent
29165 If this rule is violated, that is if a unit with dynamic elaboration
29166 checks @code{with's} a unit that does not meet one of the above four
29167 criteria, then the binder (@code{gnatbind}) will issue a warning
29168 similar to that in the following example:
29169
29170 @smallexample
29171 warning: "x.ads" has dynamic elaboration checks and with's
29172 warning:   "y.ads" which has static elaboration checks
29173 @end smallexample
29174
29175 @noindent
29176 These warnings indicate that the rule has been violated, and that as a result
29177 elaboration checks may be missed in the resulting executable file.
29178 This warning may be suppressed using the @option{-ws} binder switch
29179 in the usual manner.
29180
29181 One useful application of this mixing rule is in the case of a subsystem
29182 which does not itself @code{with} units from the remainder of the
29183 application. In this case, the entire subsystem can be compiled with
29184 dynamic checks to resolve a circularity in the subsystem, while
29185 allowing the main application that uses this subsystem to be compiled
29186 using the more reliable default static model.
29187
29188 @node What to Do If the Default Elaboration Behavior Fails
29189 @section What to Do If the Default Elaboration Behavior Fails
29190
29191 @noindent
29192 If the binder cannot find an acceptable order, it outputs detailed
29193 diagnostics. For example:
29194 @smallexample
29195 @group
29196 @iftex
29197 @leftskip=0cm
29198 @end iftex
29199 error: elaboration circularity detected
29200 info:   "proc (body)" must be elaborated before "pack (body)"
29201 info:     reason: Elaborate_All probably needed in unit "pack (body)"
29202 info:     recompile "pack (body)" with -gnatwl
29203 info:                             for full details
29204 info:       "proc (body)"
29205 info:         is needed by its spec:
29206 info:       "proc (spec)"
29207 info:         which is withed by:
29208 info:       "pack (body)"
29209 info:  "pack (body)" must be elaborated before "proc (body)"
29210 info:     reason: pragma Elaborate in unit "proc (body)"
29211 @end group
29212
29213 @end smallexample
29214
29215 @noindent
29216 In this case we have a cycle that the binder cannot break. On the one
29217 hand, there is an explicit pragma Elaborate in @code{proc} for
29218 @code{pack}. This means that the body of @code{pack} must be elaborated
29219 before the body of @code{proc}. On the other hand, there is elaboration
29220 code in @code{pack} that calls a subprogram in @code{proc}. This means
29221 that for maximum safety, there should really be a pragma
29222 Elaborate_All in @code{pack} for @code{proc} which would require that
29223 the body of @code{proc} be elaborated before the body of
29224 @code{pack}. Clearly both requirements cannot be satisfied.
29225 Faced with a circularity of this kind, you have three different options.
29226
29227 @table @asis
29228 @item Fix the program
29229 The most desirable option from the point of view of long-term maintenance
29230 is to rearrange the program so that the elaboration problems are avoided.
29231 One useful technique is to place the elaboration code into separate
29232 child packages. Another is to move some of the initialization code to
29233 explicitly called subprograms, where the program controls the order
29234 of initialization explicitly. Although this is the most desirable option,
29235 it may be impractical and involve too much modification, especially in
29236 the case of complex legacy code.
29237
29238 @item Perform dynamic checks
29239 If the compilations are done using the
29240 @option{-gnatE}
29241 (dynamic elaboration check) switch, then GNAT behaves in a quite different
29242 manner. Dynamic checks are generated for all calls that could possibly result
29243 in raising an exception. With this switch, the compiler does not generate
29244 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
29245 exactly as specified in the @cite{Ada Reference Manual}.
29246 The binder will generate
29247 an executable program that may or may not raise @code{Program_Error}, and then
29248 it is the programmer's job to ensure that it does not raise an exception. Note
29249 that it is important to compile all units with the switch, it cannot be used
29250 selectively.
29251
29252 @item Suppress checks
29253 The drawback of dynamic checks is that they generate a
29254 significant overhead at run time, both in space and time. If you
29255 are absolutely sure that your program cannot raise any elaboration
29256 exceptions, and you still want to use the dynamic elaboration model,
29257 then you can use the configuration pragma
29258 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
29259 example this pragma could be placed in the @file{gnat.adc} file.
29260
29261 @item Suppress checks selectively
29262 When you know that certain calls or instantiations in elaboration code cannot
29263 possibly lead to an elaboration error, and the binder nevertheless complains
29264 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
29265 elaboration circularities, it is possible to remove those warnings locally and
29266 obtain a program that will bind. Clearly this can be unsafe, and it is the
29267 responsibility of the programmer to make sure that the resulting program has no
29268 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
29269 used with different granularity to suppress warnings and break elaboration
29270 circularities:
29271
29272 @itemize @bullet
29273 @item
29274 Place the pragma that names the called subprogram in the declarative part
29275 that contains the call.
29276
29277 @item
29278 Place the pragma in the declarative part, without naming an entity. This
29279 disables warnings on all calls in the corresponding  declarative region.
29280
29281 @item
29282 Place the pragma in the package spec that declares the called subprogram,
29283 and name the subprogram. This disables warnings on all elaboration calls to
29284 that subprogram.
29285
29286 @item
29287 Place the pragma in the package spec that declares the called subprogram,
29288 without naming any entity. This disables warnings on all elaboration calls to
29289 all subprograms declared in this spec.
29290
29291 @item Use Pragma Elaborate
29292 As previously described in section @xref{Treatment of Pragma Elaborate},
29293 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
29294 that no elaboration checks are required on calls to the designated unit.
29295 There may be cases in which the caller knows that no transitive calls
29296 can occur, so that a @code{pragma Elaborate} will be sufficient in a
29297 case where @code{pragma Elaborate_All} would cause a circularity.
29298 @end itemize
29299
29300 @noindent
29301 These five cases are listed in order of decreasing safety, and therefore
29302 require increasing programmer care in their application. Consider the
29303 following program:
29304
29305 @smallexample @c adanocomment
29306 package Pack1 is
29307   function F1 return Integer;
29308   X1 : Integer;
29309 end Pack1;
29310
29311 package Pack2 is
29312   function F2 return Integer;
29313   function Pure (x : integer) return integer;
29314   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
29315   --  pragma Suppress (Elaboration_Check);              -- (4)
29316 end Pack2;
29317
29318 with Pack2;
29319 package body Pack1 is
29320   function F1 return Integer is
29321   begin
29322     return 100;
29323   end F1;
29324   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
29325 begin
29326   declare
29327     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
29328     --  pragma Suppress(Elaboration_Check);             -- (2)
29329   begin
29330     X1 := Pack2.F2 + 1;                --  Elab. call (2)
29331   end;
29332 end Pack1;
29333
29334 with Pack1;
29335 package body Pack2 is
29336   function F2 return Integer is
29337   begin
29338      return Pack1.F1;
29339   end F2;
29340   function Pure (x : integer) return integer is
29341   begin
29342      return x ** 3 - 3 * x;
29343   end;
29344 end Pack2;
29345
29346 with Pack1, Ada.Text_IO;
29347 procedure Proc3 is
29348 begin
29349   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
29350 end Proc3;
29351 @end smallexample
29352 In the absence of any pragmas, an attempt to bind this program produces
29353 the following diagnostics:
29354 @smallexample
29355 @group
29356 @iftex
29357 @leftskip=.5cm
29358 @end iftex
29359 error: elaboration circularity detected
29360 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
29361 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
29362 info:       recompile "pack1 (body)" with -gnatwl for full details
29363 info:          "pack1 (body)"
29364 info:             must be elaborated along with its spec:
29365 info:          "pack1 (spec)"
29366 info:             which is withed by:
29367 info:          "pack2 (body)"
29368 info:             which must be elaborated along with its spec:
29369 info:          "pack2 (spec)"
29370 info:             which is withed by:
29371 info:          "pack1 (body)"
29372 @end group
29373 @end smallexample
29374 The sources of the circularity are the two calls to @code{Pack2.Pure} and
29375 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
29376 F2 is safe, even though F2 calls F1, because the call appears after the
29377 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
29378 remove the warning on the call. It is also possible to use pragma (2)
29379 because there are no other potentially unsafe calls in the block.
29380
29381 @noindent
29382 The call to @code{Pure} is safe because this function does not depend on the
29383 state of @code{Pack2}. Therefore any call to this function is safe, and it
29384 is correct to place pragma (3) in the corresponding package spec.
29385
29386 @noindent
29387 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
29388 warnings on all calls to functions declared therein. Note that this is not
29389 necessarily safe, and requires more detailed examination of the subprogram
29390 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
29391 be already elaborated.
29392 @end table
29393
29394 @noindent
29395 It is hard to generalize on which of these four approaches should be
29396 taken. Obviously if it is possible to fix the program so that the default
29397 treatment works, this is preferable, but this may not always be practical.
29398 It is certainly simple enough to use
29399 @option{-gnatE}
29400 but the danger in this case is that, even if the GNAT binder
29401 finds a correct elaboration order, it may not always do so,
29402 and certainly a binder from another Ada compiler might not. A
29403 combination of testing and analysis (for which the warnings generated
29404 with the
29405 @option{-gnatwl}
29406 switch can be useful) must be used to ensure that the program is free
29407 of errors. One switch that is useful in this testing is the
29408 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
29409 switch for
29410 @code{gnatbind}.
29411 Normally the binder tries to find an order that has the best chance
29412 of avoiding elaboration problems. However, if this switch is used, the binder
29413 plays a devil's advocate role, and tries to choose the order that
29414 has the best chance of failing. If your program works even with this
29415 switch, then it has a better chance of being error free, but this is still
29416 not a guarantee.
29417
29418 For an example of this approach in action, consider the C-tests (executable
29419 tests) from the ACVC suite. If these are compiled and run with the default
29420 treatment, then all but one of them succeed without generating any error
29421 diagnostics from the binder. However, there is one test that fails, and
29422 this is not surprising, because the whole point of this test is to ensure
29423 that the compiler can handle cases where it is impossible to determine
29424 a correct order statically, and it checks that an exception is indeed
29425 raised at run time.
29426
29427 This one test must be compiled and run using the
29428 @option{-gnatE}
29429 switch, and then it passes. Alternatively, the entire suite can
29430 be run using this switch. It is never wrong to run with the dynamic
29431 elaboration switch if your code is correct, and we assume that the
29432 C-tests are indeed correct (it is less efficient, but efficiency is
29433 not a factor in running the ACVC tests.)
29434
29435 @node Elaboration for Access-to-Subprogram Values
29436 @section Elaboration for Access-to-Subprogram Values
29437 @cindex Access-to-subprogram
29438
29439 @noindent
29440 Access-to-subprogram types (introduced in Ada 95) complicate
29441 the handling of elaboration. The trouble is that it becomes
29442 impossible to tell at compile time which procedure
29443 is being called. This means that it is not possible for the binder
29444 to analyze the elaboration requirements in this case.
29445
29446 If at the point at which the access value is created
29447 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
29448 the body of the subprogram is
29449 known to have been elaborated, then the access value is safe, and its use
29450 does not require a check. This may be achieved by appropriate arrangement
29451 of the order of declarations if the subprogram is in the current unit,
29452 or, if the subprogram is in another unit, by using pragma
29453 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
29454 on the referenced unit.
29455
29456 If the referenced body is not known to have been elaborated at the point
29457 the access value is created, then any use of the access value must do a
29458 dynamic check, and this dynamic check will fail and raise a
29459 @code{Program_Error} exception if the body has not been elaborated yet.
29460 GNAT will generate the necessary checks, and in addition, if the
29461 @option{-gnatwl}
29462 switch is set, will generate warnings that such checks are required.
29463
29464 The use of dynamic dispatching for tagged types similarly generates
29465 a requirement for dynamic checks, and premature calls to any primitive
29466 operation of a tagged type before the body of the operation has been
29467 elaborated, will result in the raising of @code{Program_Error}.
29468
29469 @node Summary of Procedures for Elaboration Control
29470 @section Summary of Procedures for Elaboration Control
29471 @cindex Elaboration control
29472
29473 @noindent
29474 First, compile your program with the default options, using none of
29475 the special elaboration control switches. If the binder successfully
29476 binds your program, then you can be confident that, apart from issues
29477 raised by the use of access-to-subprogram types and dynamic dispatching,
29478 the program is free of elaboration errors. If it is important that the
29479 program be portable, then use the
29480 @option{-gnatwl}
29481 switch to generate warnings about missing @code{Elaborate} or
29482 @code{Elaborate_All} pragmas, and supply the missing pragmas.
29483
29484 If the program fails to bind using the default static elaboration
29485 handling, then you can fix the program to eliminate the binder
29486 message, or recompile the entire program with the
29487 @option{-gnatE} switch to generate dynamic elaboration checks,
29488 and, if you are sure there really are no elaboration problems,
29489 use a global pragma @code{Suppress (Elaboration_Check)}.
29490
29491 @node Other Elaboration Order Considerations
29492 @section Other Elaboration Order Considerations
29493 @noindent
29494 This section has been entirely concerned with the issue of finding a valid
29495 elaboration order, as defined by the Ada Reference Manual. In a case
29496 where several elaboration orders are valid, the task is to find one
29497 of the possible valid elaboration orders (and the static model in GNAT
29498 will ensure that this is achieved).
29499
29500 The purpose of the elaboration rules in the Ada Reference Manual is to
29501 make sure that no entity is accessed before it has been elaborated. For
29502 a subprogram, this means that the spec and body must have been elaborated
29503 before the subprogram is called. For an object, this means that the object
29504 must have been elaborated before its value is read or written. A violation
29505 of either of these two requirements is an access before elaboration order,
29506 and this section has been all about avoiding such errors.
29507
29508 In the case where more than one order of elaboration is possible, in the
29509 sense that access before elaboration errors are avoided, then any one of
29510 the orders is ``correct'' in the sense that it meets the requirements of
29511 the Ada Reference Manual, and no such error occurs.
29512
29513 However, it may be the case for a given program, that there are
29514 constraints on the order of elaboration that come not from consideration
29515 of avoiding elaboration errors, but rather from extra-lingual logic
29516 requirements. Consider this example:
29517
29518 @smallexample @c ada
29519 with Init_Constants;
29520 package Constants is
29521    X : Integer := 0;
29522    Y : Integer := 0;
29523 end Constants;
29524
29525 package Init_Constants is
29526    procedure P; -- require a body
29527 end Init_Constants;
29528
29529 with Constants;
29530 package body Init_Constants is
29531    procedure P is begin null; end;
29532 begin
29533    Constants.X := 3;
29534    Constants.Y := 4;
29535 end Init_Constants;
29536
29537 with Constants;
29538 package Calc is
29539    Z : Integer := Constants.X + Constants.Y;
29540 end Calc;
29541
29542 with Calc;
29543 with Text_IO; use Text_IO;
29544 procedure Main is
29545 begin
29546    Put_Line (Calc.Z'Img);
29547 end Main;
29548 @end smallexample
29549
29550 @noindent
29551 In this example, there is more than one valid order of elaboration. For
29552 example both the following are correct orders:
29553
29554 @smallexample
29555 Init_Constants spec
29556 Constants spec
29557 Calc spec
29558 Init_Constants body
29559 Main body
29560
29561   and
29562
29563 Init_Constants spec
29564 Init_Constants body
29565 Constants spec
29566 Calc spec
29567 Main body
29568 @end smallexample
29569
29570 @noindent
29571 There is no language rule to prefer one or the other, both are correct
29572 from an order of elaboration point of view. But the programmatic effects
29573 of the two orders are very different. In the first, the elaboration routine
29574 of @code{Calc} initializes @code{Z} to zero, and then the main program
29575 runs with this value of zero. But in the second order, the elaboration
29576 routine of @code{Calc} runs after the body of Init_Constants has set
29577 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
29578 runs.
29579
29580 One could perhaps by applying pretty clever non-artificial intelligence
29581 to the situation guess that it is more likely that the second order of
29582 elaboration is the one desired, but there is no formal linguistic reason
29583 to prefer one over the other. In fact in this particular case, GNAT will
29584 prefer the second order, because of the rule that bodies are elaborated
29585 as soon as possible, but it's just luck that this is what was wanted
29586 (if indeed the second order was preferred).
29587
29588 If the program cares about the order of elaboration routines in a case like
29589 this, it is important to specify the order required. In this particular
29590 case, that could have been achieved by adding to the spec of Calc:
29591
29592 @smallexample @c ada
29593 pragma Elaborate_All (Constants);
29594 @end smallexample
29595
29596 @noindent
29597 which requires that the body (if any) and spec of @code{Constants},
29598 as well as the body and spec of any unit @code{with}'ed by
29599 @code{Constants} be elaborated before @code{Calc} is elaborated.
29600
29601 Clearly no automatic method can always guess which alternative you require,
29602 and if you are working with legacy code that had constraints of this kind
29603 which were not properly specified by adding @code{Elaborate} or
29604 @code{Elaborate_All} pragmas, then indeed it is possible that two different
29605 compilers can choose different orders.
29606
29607 However, GNAT does attempt to diagnose the common situation where there
29608 are uninitialized variables in the visible part of a package spec, and the
29609 corresponding package body has an elaboration block that directly or
29610 indirectly initialized one or more of these variables. This is the situation
29611 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
29612 a warning that suggests this addition if it detects this situation.
29613
29614 The @code{gnatbind}
29615 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
29616 out problems. This switch causes bodies to be elaborated as late as possible
29617 instead of as early as possible. In the example above, it would have forced
29618 the choice of the first elaboration order. If you get different results
29619 when using this switch, and particularly if one set of results is right,
29620 and one is wrong as far as you are concerned, it shows that you have some
29621 missing @code{Elaborate} pragmas. For the example above, we have the
29622 following output:
29623
29624 @smallexample
29625 gnatmake -f -q main
29626 main
29627  7
29628 gnatmake -f -q main -bargs -p
29629 main
29630  0
29631 @end smallexample
29632
29633 @noindent
29634 It is of course quite unlikely that both these results are correct, so
29635 it is up to you in a case like this to investigate the source of the
29636 difference, by looking at the two elaboration orders that are chosen,
29637 and figuring out which is correct, and then adding the necessary
29638 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
29639
29640
29641
29642 @c *******************************
29643 @node Conditional Compilation
29644 @appendix Conditional Compilation
29645 @c *******************************
29646 @cindex Conditional compilation
29647
29648 @noindent
29649 It is often necessary to arrange for a single source program
29650 to serve multiple purposes, where it is compiled in different
29651 ways to achieve these different goals. Some examples of the
29652 need for this feature are
29653
29654 @itemize @bullet
29655 @item  Adapting a program to a different hardware environment
29656 @item  Adapting a program to a different target architecture
29657 @item  Turning debugging features on and off
29658 @item  Arranging for a program to compile with different compilers
29659 @end itemize
29660
29661 @noindent
29662 In C, or C++, the typical approach would be to use the preprocessor
29663 that is defined as part of the language. The Ada language does not
29664 contain such a feature. This is not an oversight, but rather a very
29665 deliberate design decision, based on the experience that overuse of
29666 the preprocessing features in C and C++ can result in programs that
29667 are extremely difficult to maintain. For example, if we have ten
29668 switches that can be on or off, this means that there are a thousand
29669 separate programs, any one of which might not even be syntactically
29670 correct, and even if syntactically correct, the resulting program
29671 might not work correctly. Testing all combinations can quickly become
29672 impossible.
29673
29674 Nevertheless, the need to tailor programs certainly exists, and in
29675 this Appendix we will discuss how this can
29676 be achieved using Ada in general, and GNAT in particular.
29677
29678 @menu
29679 * Use of Boolean Constants::
29680 * Debugging - A Special Case::
29681 * Conditionalizing Declarations::
29682 * Use of Alternative Implementations::
29683 * Preprocessing::
29684 @end menu
29685
29686 @node Use of Boolean Constants
29687 @section Use of Boolean Constants
29688
29689 @noindent
29690 In the case where the difference is simply which code
29691 sequence is executed, the cleanest solution is to use Boolean
29692 constants to control which code is executed.
29693
29694 @smallexample @c ada
29695 @group
29696 FP_Initialize_Required : constant Boolean := True;
29697 @dots{}
29698 if FP_Initialize_Required then
29699 @dots{}
29700 end if;
29701 @end group
29702 @end smallexample
29703
29704 @noindent
29705 Not only will the code inside the @code{if} statement not be executed if
29706 the constant Boolean is @code{False}, but it will also be completely
29707 deleted from the program.
29708 However, the code is only deleted after the @code{if} statement
29709 has been checked for syntactic and semantic correctness.
29710 (In contrast, with preprocessors the code is deleted before the
29711 compiler ever gets to see it, so it is not checked until the switch
29712 is turned on.)
29713 @cindex Preprocessors (contrasted with conditional compilation)
29714
29715 Typically the Boolean constants will be in a separate package,
29716 something like:
29717
29718 @smallexample @c ada
29719 @group
29720 package Config is
29721    FP_Initialize_Required : constant Boolean := True;
29722    Reset_Available        : constant Boolean := False;
29723    @dots{}
29724 end Config;
29725 @end group
29726 @end smallexample
29727
29728 @noindent
29729 The @code{Config} package exists in multiple forms for the various targets,
29730 with an appropriate script selecting the version of @code{Config} needed.
29731 Then any other unit requiring conditional compilation can do a @code{with}
29732 of @code{Config} to make the constants visible.
29733
29734
29735 @node Debugging - A Special Case
29736 @section Debugging - A Special Case
29737
29738 @noindent
29739 A common use of conditional code is to execute statements (for example
29740 dynamic checks, or output of intermediate results) under control of a
29741 debug switch, so that the debugging behavior can be turned on and off.
29742 This can be done using a Boolean constant to control whether the code
29743 is active:
29744
29745 @smallexample @c ada
29746 @group
29747 if Debugging then
29748    Put_Line ("got to the first stage!");
29749 end if;
29750 @end group
29751 @end smallexample
29752
29753 @noindent
29754 or
29755
29756 @smallexample @c ada
29757 @group
29758 if Debugging and then Temperature > 999.0 then
29759    raise Temperature_Crazy;
29760 end if;
29761 @end group
29762 @end smallexample
29763
29764 @noindent
29765 Since this is a common case, there are special features to deal with
29766 this in a convenient manner. For the case of tests, Ada 2005 has added
29767 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
29768 @cindex pragma @code{Assert}
29769 on the @code{Assert} pragma that has always been available in GNAT, so this
29770 feature may be used with GNAT even if you are not using Ada 2005 features.
29771 The use of pragma @code{Assert} is described in
29772 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
29773 example, the last test could be written:
29774
29775 @smallexample @c ada
29776 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
29777 @end smallexample
29778
29779 @noindent
29780 or simply
29781
29782 @smallexample @c ada
29783 pragma Assert (Temperature <= 999.0);
29784 @end smallexample
29785
29786 @noindent
29787 In both cases, if assertions are active and the temperature is excessive,
29788 the exception @code{Assert_Failure} will be raised, with the given string in
29789 the first case or a string indicating the location of the pragma in the second
29790 case used as the exception message.
29791
29792 You can turn assertions on and off by using the @code{Assertion_Policy}
29793 pragma.
29794 @cindex pragma @code{Assertion_Policy}
29795 This is an Ada 2005 pragma which is implemented in all modes by
29796 GNAT, but only in the latest versions of GNAT which include Ada 2005
29797 capability. Alternatively, you can use the @option{-gnata} switch
29798 @cindex @option{-gnata} switch
29799 to enable assertions from the command line (this is recognized by all versions
29800 of GNAT).
29801
29802 For the example above with the @code{Put_Line}, the GNAT-specific pragma
29803 @code{Debug} can be used:
29804 @cindex pragma @code{Debug}
29805
29806 @smallexample @c ada
29807 pragma Debug (Put_Line ("got to the first stage!"));
29808 @end smallexample
29809
29810 @noindent
29811 If debug pragmas are enabled, the argument, which must be of the form of
29812 a procedure call, is executed (in this case, @code{Put_Line} will be called).
29813 Only one call can be present, but of course a special debugging procedure
29814 containing any code you like can be included in the program and then
29815 called in a pragma @code{Debug} argument as needed.
29816
29817 One advantage of pragma @code{Debug} over the @code{if Debugging then}
29818 construct is that pragma @code{Debug} can appear in declarative contexts,
29819 such as at the very beginning of a procedure, before local declarations have
29820 been elaborated.
29821
29822 Debug pragmas are enabled using either the @option{-gnata} switch that also
29823 controls assertions, or with a separate Debug_Policy pragma.
29824 @cindex pragma @code{Debug_Policy}
29825 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
29826 in Ada 95 and Ada 83 programs as well), and is analogous to
29827 pragma @code{Assertion_Policy} to control assertions.
29828
29829 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
29830 and thus they can appear in @file{gnat.adc} if you are not using a
29831 project file, or in the file designated to contain configuration pragmas
29832 in a project file.
29833 They then apply to all subsequent compilations. In practice the use of
29834 the @option{-gnata} switch is often the most convenient method of controlling
29835 the status of these pragmas.
29836
29837 Note that a pragma is not a statement, so in contexts where a statement
29838 sequence is required, you can't just write a pragma on its own. You have
29839 to add a @code{null} statement.
29840
29841 @smallexample @c ada
29842 @group
29843 if @dots{} then
29844    @dots{} -- some statements
29845 else
29846    pragma Assert (Num_Cases < 10);
29847    null;
29848 end if;
29849 @end group
29850 @end smallexample
29851
29852
29853 @node Conditionalizing Declarations
29854 @section Conditionalizing Declarations
29855
29856 @noindent
29857 In some cases, it may be necessary to conditionalize declarations to meet
29858 different requirements. For example we might want a bit string whose length
29859 is set to meet some hardware message requirement.
29860
29861 In some cases, it may be possible to do this using declare blocks controlled
29862 by conditional constants:
29863
29864 @smallexample @c ada
29865 @group
29866 if Small_Machine then
29867    declare
29868       X : Bit_String (1 .. 10);
29869    begin
29870       @dots{}
29871    end;
29872 else
29873    declare
29874       X : Large_Bit_String (1 .. 1000);
29875    begin
29876       @dots{}
29877    end;
29878 end if;
29879 @end group
29880 @end smallexample
29881
29882 @noindent
29883 Note that in this approach, both declarations are analyzed by the
29884 compiler so this can only be used where both declarations are legal,
29885 even though one of them will not be used.
29886
29887 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
29888 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
29889 that are parameterized by these constants. For example
29890
29891 @smallexample @c ada
29892 @group
29893 for Rec use
29894   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
29895 end record;
29896 @end group
29897 @end smallexample
29898
29899 @noindent
29900 If @code{Bits_Per_Word} is set to 32, this generates either
29901
29902 @smallexample @c ada
29903 @group
29904 for Rec use
29905   Field1 at 0 range 0 .. 32;
29906 end record;
29907 @end group
29908 @end smallexample
29909
29910 @noindent
29911 for the big endian case, or
29912
29913 @smallexample @c ada
29914 @group
29915 for Rec use record
29916   Field1 at 0 range 10 .. 32;
29917 end record;
29918 @end group
29919 @end smallexample
29920
29921 @noindent
29922 for the little endian case. Since a powerful subset of Ada expression
29923 notation is usable for creating static constants, clever use of this
29924 feature can often solve quite difficult problems in conditionalizing
29925 compilation (note incidentally that in Ada 95, the little endian
29926 constant was introduced as @code{System.Default_Bit_Order}, so you do not
29927 need to define this one yourself).
29928
29929
29930 @node Use of Alternative Implementations
29931 @section Use of Alternative Implementations
29932
29933 @noindent
29934 In some cases, none of the approaches described above are adequate. This
29935 can occur for example if the set of declarations required is radically
29936 different for two different configurations.
29937
29938 In this situation, the official Ada way of dealing with conditionalizing
29939 such code is to write separate units for the different cases. As long as
29940 this does not result in excessive duplication of code, this can be done
29941 without creating maintenance problems. The approach is to share common
29942 code as far as possible, and then isolate the code and declarations
29943 that are different. Subunits are often a convenient method for breaking
29944 out a piece of a unit that is to be conditionalized, with separate files
29945 for different versions of the subunit for different targets, where the
29946 build script selects the right one to give to the compiler.
29947 @cindex Subunits (and conditional compilation)
29948
29949 As an example, consider a situation where a new feature in Ada 2005
29950 allows something to be done in a really nice way. But your code must be able
29951 to compile with an Ada 95 compiler. Conceptually you want to say:
29952
29953 @smallexample @c ada
29954 @group
29955 if Ada_2005 then
29956    @dots{} neat Ada 2005 code
29957 else
29958    @dots{} not quite as neat Ada 95 code
29959 end if;
29960 @end group
29961 @end smallexample
29962
29963 @noindent
29964 where @code{Ada_2005} is a Boolean constant.
29965
29966 But this won't work when @code{Ada_2005} is set to @code{False},
29967 since the @code{then} clause will be illegal for an Ada 95 compiler.
29968 (Recall that although such unreachable code would eventually be deleted
29969 by the compiler, it still needs to be legal.  If it uses features
29970 introduced in Ada 2005, it will be illegal in Ada 95.)
29971
29972 So instead we write
29973
29974 @smallexample @c ada
29975 procedure Insert is separate;
29976 @end smallexample
29977
29978 @noindent
29979 Then we have two files for the subunit @code{Insert}, with the two sets of
29980 code.
29981 If the package containing this is called @code{File_Queries}, then we might
29982 have two files
29983
29984 @itemize @bullet
29985 @item    @file{file_queries-insert-2005.adb}
29986 @item    @file{file_queries-insert-95.adb}
29987 @end itemize
29988
29989 @noindent
29990 and the build script renames the appropriate file to
29991
29992 @smallexample
29993 file_queries-insert.adb
29994 @end smallexample
29995
29996 @noindent
29997 and then carries out the compilation.
29998
29999 This can also be done with project files' naming schemes. For example:
30000
30001 @smallexample @c project
30002 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
30003 @end smallexample
30004
30005 @noindent
30006 Note also that with project files it is desirable to use a different extension
30007 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
30008 conflict may arise through another commonly used feature: to declare as part
30009 of the project a set of directories containing all the sources obeying the
30010 default naming scheme.
30011
30012 The use of alternative units is certainly feasible in all situations,
30013 and for example the Ada part of the GNAT run-time is conditionalized
30014 based on the target architecture using this approach. As a specific example,
30015 consider the implementation of the AST feature in VMS. There is one
30016 spec:
30017
30018 @smallexample
30019 s-asthan.ads
30020 @end smallexample
30021
30022 @noindent
30023 which is the same for all architectures, and three bodies:
30024
30025 @table @file
30026 @item    s-asthan.adb
30027 used for all non-VMS operating systems
30028 @item    s-asthan-vms-alpha.adb
30029 used for VMS on the Alpha
30030 @item    s-asthan-vms-ia64.adb
30031 used for VMS on the ia64
30032 @end table
30033
30034 @noindent
30035 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
30036 this operating system feature is not available, and the two remaining
30037 versions interface with the corresponding versions of VMS to provide
30038 VMS-compatible AST handling. The GNAT build script knows the architecture
30039 and operating system, and automatically selects the right version,
30040 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
30041
30042 Another style for arranging alternative implementations is through Ada's
30043 access-to-subprogram facility.
30044 In case some functionality is to be conditionally included,
30045 you can declare an access-to-procedure variable @code{Ref} that is initialized
30046 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
30047 when appropriate.
30048 In some library package, set @code{Ref} to @code{Proc'Access} for some
30049 procedure @code{Proc} that performs the relevant processing.
30050 The initialization only occurs if the library package is included in the
30051 program.
30052 The same idea can also be implemented using tagged types and dispatching
30053 calls.
30054
30055
30056 @node Preprocessing
30057 @section Preprocessing
30058 @cindex Preprocessing
30059
30060 @noindent
30061 Although it is quite possible to conditionalize code without the use of
30062 C-style preprocessing, as described earlier in this section, it is
30063 nevertheless convenient in some cases to use the C approach. Moreover,
30064 older Ada compilers have often provided some preprocessing capability,
30065 so legacy code may depend on this approach, even though it is not
30066 standard.
30067
30068 To accommodate such use, GNAT provides a preprocessor (modeled to a large
30069 extent on the various preprocessors that have been used
30070 with legacy code on other compilers, to enable easier transition).
30071
30072 The preprocessor may be used in two separate modes. It can be used quite
30073 separately from the compiler, to generate a separate output source file
30074 that is then fed to the compiler as a separate step. This is the
30075 @code{gnatprep} utility, whose use is fully described in
30076 @ref{Preprocessing Using gnatprep}.
30077 @cindex @code{gnatprep}
30078
30079 The preprocessing language allows such constructs as
30080
30081 @smallexample
30082 @group
30083 #if DEBUG or PRIORITY > 4 then
30084    bunch of declarations
30085 #else
30086    completely different bunch of declarations
30087 #end if;
30088 @end group
30089 @end smallexample
30090
30091 @noindent
30092 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
30093 defined either on the command line or in a separate file.
30094
30095 The other way of running the preprocessor is even closer to the C style and
30096 often more convenient. In this approach the preprocessing is integrated into
30097 the compilation process. The compiler is fed the preprocessor input which
30098 includes @code{#if} lines etc, and then the compiler carries out the
30099 preprocessing internally and processes the resulting output.
30100 For more details on this approach, see @ref{Integrated Preprocessing}.
30101
30102
30103 @c *******************************
30104 @node Inline Assembler
30105 @appendix Inline Assembler
30106 @c *******************************
30107
30108 @noindent
30109 If you need to write low-level software that interacts directly
30110 with the hardware, Ada provides two ways to incorporate assembly
30111 language code into your program.  First, you can import and invoke
30112 external routines written in assembly language, an Ada feature fully
30113 supported by GNAT@.  However, for small sections of code it may be simpler
30114 or more efficient to include assembly language statements directly
30115 in your Ada source program, using the facilities of the implementation-defined
30116 package @code{System.Machine_Code}, which incorporates the gcc
30117 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
30118 including the following:
30119
30120 @itemize @bullet
30121 @item No need to use non-Ada tools
30122 @item Consistent interface over different targets
30123 @item Automatic usage of the proper calling conventions
30124 @item Access to Ada constants and variables
30125 @item Definition of intrinsic routines
30126 @item Possibility of inlining a subprogram comprising assembler code
30127 @item Code optimizer can take Inline Assembler code into account
30128 @end itemize
30129
30130 This chapter presents a series of examples to show you how to use
30131 the Inline Assembler.  Although it focuses on the Intel x86,
30132 the general approach applies also to other processors.
30133 It is assumed that you are familiar with Ada
30134 and with assembly language programming.
30135
30136 @menu
30137 * Basic Assembler Syntax::
30138 * A Simple Example of Inline Assembler::
30139 * Output Variables in Inline Assembler::
30140 * Input Variables in Inline Assembler::
30141 * Inlining Inline Assembler Code::
30142 * Other Asm Functionality::
30143 @end menu
30144
30145 @c ---------------------------------------------------------------------------
30146 @node Basic Assembler Syntax
30147 @section Basic Assembler Syntax
30148
30149 @noindent
30150 The assembler used by GNAT and gcc is based not on the Intel assembly
30151 language, but rather on a language that descends from the AT&T Unix
30152 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
30153 The following table summarizes the main features of @emph{as} syntax
30154 and points out the differences from the Intel conventions.
30155 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
30156 pre-processor) documentation for further information.
30157
30158 @table @asis
30159 @item Register names
30160 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
30161 @*
30162 Intel: No extra punctuation; for example @code{eax}
30163
30164 @item Immediate operand
30165 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
30166 @*
30167 Intel: No extra punctuation; for example @code{4}
30168
30169 @item Address
30170 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
30171 @*
30172 Intel: No extra punctuation; for example @code{loc}
30173
30174 @item Memory contents
30175 gcc / @emph{as}: No extra punctuation; for example @code{loc}
30176 @*
30177 Intel: Square brackets; for example @code{[loc]}
30178
30179 @item Register contents
30180 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
30181 @*
30182 Intel: Square brackets; for example @code{[eax]}
30183
30184 @item Hexadecimal numbers
30185 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
30186 @*
30187 Intel: Trailing ``h''; for example @code{A0h}
30188
30189 @item Operand size
30190 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
30191 a 16-bit word
30192 @*
30193 Intel: Implicit, deduced by assembler; for example @code{mov}
30194
30195 @item Instruction repetition
30196 gcc / @emph{as}: Split into two lines; for example
30197 @*
30198 @code{rep}
30199 @*
30200 @code{stosl}
30201 @*
30202 Intel: Keep on one line; for example @code{rep stosl}
30203
30204 @item Order of operands
30205 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
30206 @*
30207 Intel: Destination first; for example @code{mov eax, 4}
30208 @end table
30209
30210 @c ---------------------------------------------------------------------------
30211 @node A Simple Example of Inline Assembler
30212 @section A Simple Example of Inline Assembler
30213
30214 @noindent
30215 The following example will generate a single assembly language statement,
30216 @code{nop}, which does nothing.  Despite its lack of run-time effect,
30217 the example will be useful in illustrating the basics of
30218 the Inline Assembler facility.
30219
30220 @smallexample @c ada
30221 @group
30222 with System.Machine_Code; use System.Machine_Code;
30223 procedure Nothing is
30224 begin
30225    Asm ("nop");
30226 end Nothing;
30227 @end group
30228 @end smallexample
30229
30230 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
30231 here it takes one parameter, a @emph{template string} that must be a static
30232 expression and that will form the generated instruction.
30233 @code{Asm} may be regarded as a compile-time procedure that parses
30234 the template string and additional parameters (none here),
30235 from which it generates a sequence of assembly language instructions.
30236
30237 The examples in this chapter will illustrate several of the forms
30238 for invoking @code{Asm}; a complete specification of the syntax
30239 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
30240 Manual}.
30241
30242 Under the standard GNAT conventions, the @code{Nothing} procedure
30243 should be in a file named @file{nothing.adb}.
30244 You can build the executable in the usual way:
30245 @smallexample
30246 gnatmake nothing
30247 @end smallexample
30248 However, the interesting aspect of this example is not its run-time behavior
30249 but rather the generated assembly code.
30250 To see this output, invoke the compiler as follows:
30251 @smallexample
30252    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
30253 @end smallexample
30254 where the options are:
30255
30256 @table @code
30257 @item -c
30258 compile only (no bind or link)
30259 @item -S
30260 generate assembler listing
30261 @item -fomit-frame-pointer
30262 do not set up separate stack frames
30263 @item -gnatp
30264 do not add runtime checks
30265 @end table
30266
30267 This gives a human-readable assembler version of the code. The resulting
30268 file will have the same name as the Ada source file, but with a @code{.s}
30269 extension. In our example, the file @file{nothing.s} has the following
30270 contents:
30271
30272 @smallexample
30273 @group
30274 .file "nothing.adb"
30275 gcc2_compiled.:
30276 ___gnu_compiled_ada:
30277 .text
30278    .align 4
30279 .globl __ada_nothing
30280 __ada_nothing:
30281 #APP
30282    nop
30283 #NO_APP
30284    jmp L1
30285    .align 2,0x90
30286 L1:
30287    ret
30288 @end group
30289 @end smallexample
30290
30291 The assembly code you included is clearly indicated by
30292 the compiler, between the @code{#APP} and @code{#NO_APP}
30293 delimiters. The character before the 'APP' and 'NOAPP'
30294 can differ on different targets. For example, GNU/Linux uses '#APP' while
30295 on NT you will see '/APP'.
30296
30297 If you make a mistake in your assembler code (such as using the
30298 wrong size modifier, or using a wrong operand for the instruction) GNAT
30299 will report this error in a temporary file, which will be deleted when
30300 the compilation is finished.  Generating an assembler file will help
30301 in such cases, since you can assemble this file separately using the
30302 @emph{as} assembler that comes with gcc.
30303
30304 Assembling the file using the command
30305
30306 @smallexample
30307 as @file{nothing.s}
30308 @end smallexample
30309 @noindent
30310 will give you error messages whose lines correspond to the assembler
30311 input file, so you can easily find and correct any mistakes you made.
30312 If there are no errors, @emph{as} will generate an object file
30313 @file{nothing.out}.
30314
30315 @c ---------------------------------------------------------------------------
30316 @node Output Variables in Inline Assembler
30317 @section Output Variables in Inline Assembler
30318
30319 @noindent
30320 The examples in this section, showing how to access the processor flags,
30321 illustrate how to specify the destination operands for assembly language
30322 statements.
30323
30324 @smallexample @c ada
30325 @group
30326 with Interfaces; use Interfaces;
30327 with Ada.Text_IO; use Ada.Text_IO;
30328 with System.Machine_Code; use System.Machine_Code;
30329 procedure Get_Flags is
30330    Flags : Unsigned_32;
30331    use ASCII;
30332 begin
30333    Asm ("pushfl"          & LF & HT & -- push flags on stack
30334         "popl %%eax"      & LF & HT & -- load eax with flags
30335         "movl %%eax, %0",             -- store flags in variable
30336         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30337    Put_Line ("Flags register:" & Flags'Img);
30338 end Get_Flags;
30339 @end group
30340 @end smallexample
30341
30342 In order to have a nicely aligned assembly listing, we have separated
30343 multiple assembler statements in the Asm template string with linefeed
30344 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
30345 The resulting section of the assembly output file is:
30346
30347 @smallexample
30348 @group
30349 #APP
30350    pushfl
30351    popl %eax
30352    movl %eax, -40(%ebp)
30353 #NO_APP
30354 @end group
30355 @end smallexample
30356
30357 It would have been legal to write the Asm invocation as:
30358
30359 @smallexample
30360 Asm ("pushfl popl %%eax movl %%eax, %0")
30361 @end smallexample
30362
30363 but in the generated assembler file, this would come out as:
30364
30365 @smallexample
30366 #APP
30367    pushfl popl %eax movl %eax, -40(%ebp)
30368 #NO_APP
30369 @end smallexample
30370
30371 which is not so convenient for the human reader.
30372
30373 We use Ada comments
30374 at the end of each line to explain what the assembler instructions
30375 actually do.  This is a useful convention.
30376
30377 When writing Inline Assembler instructions, you need to precede each register
30378 and variable name with a percent sign.  Since the assembler already requires
30379 a percent sign at the beginning of a register name, you need two consecutive
30380 percent signs for such names in the Asm template string, thus @code{%%eax}.
30381 In the generated assembly code, one of the percent signs will be stripped off.
30382
30383 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
30384 variables: operands you later define using @code{Input} or @code{Output}
30385 parameters to @code{Asm}.
30386 An output variable is illustrated in
30387 the third statement in the Asm template string:
30388 @smallexample
30389 movl %%eax, %0
30390 @end smallexample
30391 The intent is to store the contents of the eax register in a variable that can
30392 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
30393 necessarily work, since the compiler might optimize by using a register
30394 to hold Flags, and the expansion of the @code{movl} instruction would not be
30395 aware of this optimization.  The solution is not to store the result directly
30396 but rather to advise the compiler to choose the correct operand form;
30397 that is the purpose of the @code{%0} output variable.
30398
30399 Information about the output variable is supplied in the @code{Outputs}
30400 parameter to @code{Asm}:
30401 @smallexample
30402 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30403 @end smallexample
30404
30405 The output is defined by the @code{Asm_Output} attribute of the target type;
30406 the general format is
30407 @smallexample
30408 Type'Asm_Output (constraint_string, variable_name)
30409 @end smallexample
30410
30411 The constraint string directs the compiler how
30412 to store/access the associated variable.  In the example
30413 @smallexample
30414 Unsigned_32'Asm_Output ("=m", Flags);
30415 @end smallexample
30416 the @code{"m"} (memory) constraint tells the compiler that the variable
30417 @code{Flags} should be stored in a memory variable, thus preventing
30418 the optimizer from keeping it in a register.  In contrast,
30419 @smallexample
30420 Unsigned_32'Asm_Output ("=r", Flags);
30421 @end smallexample
30422 uses the @code{"r"} (register) constraint, telling the compiler to
30423 store the variable in a register.
30424
30425 If the constraint is preceded by the equal character (@strong{=}), it tells
30426 the compiler that the variable will be used to store data into it.
30427
30428 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
30429 allowing the optimizer to choose whatever it deems best.
30430
30431 There are a fairly large number of constraints, but the ones that are
30432 most useful (for the Intel x86 processor) are the following:
30433
30434 @table @code
30435 @item =
30436 output constraint
30437 @item g
30438 global (i.e.@: can be stored anywhere)
30439 @item m
30440 in memory
30441 @item I
30442 a constant
30443 @item a
30444 use eax
30445 @item b
30446 use ebx
30447 @item c
30448 use ecx
30449 @item d
30450 use edx
30451 @item S
30452 use esi
30453 @item D
30454 use edi
30455 @item r
30456 use one of eax, ebx, ecx or edx
30457 @item q
30458 use one of eax, ebx, ecx, edx, esi or edi
30459 @end table
30460
30461 The full set of constraints is described in the gcc and @emph{as}
30462 documentation; note that it is possible to combine certain constraints
30463 in one constraint string.
30464
30465 You specify the association of an output variable with an assembler operand
30466 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
30467 integer.  Thus in
30468 @smallexample @c ada
30469 @group
30470 Asm ("pushfl"          & LF & HT & -- push flags on stack
30471      "popl %%eax"      & LF & HT & -- load eax with flags
30472      "movl %%eax, %0",             -- store flags in variable
30473      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30474 @end group
30475 @end smallexample
30476 @noindent
30477 @code{%0} will be replaced in the expanded code by the appropriate operand,
30478 whatever
30479 the compiler decided for the @code{Flags} variable.
30480
30481 In general, you may have any number of output variables:
30482 @itemize @bullet
30483 @item
30484 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
30485 @item
30486 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
30487 of @code{Asm_Output} attributes
30488 @end itemize
30489
30490 For example:
30491 @smallexample @c ada
30492 @group
30493 Asm ("movl %%eax, %0" & LF & HT &
30494      "movl %%ebx, %1" & LF & HT &
30495      "movl %%ecx, %2",
30496      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
30497                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
30498                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
30499 @end group
30500 @end smallexample
30501 @noindent
30502 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
30503 in the Ada program.
30504
30505 As a variation on the @code{Get_Flags} example, we can use the constraints
30506 string to direct the compiler to store the eax register into the @code{Flags}
30507 variable, instead of including the store instruction explicitly in the
30508 @code{Asm} template string:
30509
30510 @smallexample @c ada
30511 @group
30512 with Interfaces; use Interfaces;
30513 with Ada.Text_IO; use Ada.Text_IO;
30514 with System.Machine_Code; use System.Machine_Code;
30515 procedure Get_Flags_2 is
30516    Flags : Unsigned_32;
30517    use ASCII;
30518 begin
30519    Asm ("pushfl"      & LF & HT & -- push flags on stack
30520         "popl %%eax",             -- save flags in eax
30521         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
30522    Put_Line ("Flags register:" & Flags'Img);
30523 end Get_Flags_2;
30524 @end group
30525 @end smallexample
30526
30527 @noindent
30528 The @code{"a"} constraint tells the compiler that the @code{Flags}
30529 variable will come from the eax register. Here is the resulting code:
30530
30531 @smallexample
30532 @group
30533 #APP
30534    pushfl
30535    popl %eax
30536 #NO_APP
30537    movl %eax,-40(%ebp)
30538 @end group
30539 @end smallexample
30540
30541 @noindent
30542 The compiler generated the store of eax into Flags after
30543 expanding the assembler code.
30544
30545 Actually, there was no need to pop the flags into the eax register;
30546 more simply, we could just pop the flags directly into the program variable:
30547
30548 @smallexample @c ada
30549 @group
30550 with Interfaces; use Interfaces;
30551 with Ada.Text_IO; use Ada.Text_IO;
30552 with System.Machine_Code; use System.Machine_Code;
30553 procedure Get_Flags_3 is
30554    Flags : Unsigned_32;
30555    use ASCII;
30556 begin
30557    Asm ("pushfl"  & LF & HT & -- push flags on stack
30558         "pop %0",             -- save flags in Flags
30559         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30560    Put_Line ("Flags register:" & Flags'Img);
30561 end Get_Flags_3;
30562 @end group
30563 @end smallexample
30564
30565 @c ---------------------------------------------------------------------------
30566 @node Input Variables in Inline Assembler
30567 @section Input Variables in Inline Assembler
30568
30569 @noindent
30570 The example in this section illustrates how to specify the source operands
30571 for assembly language statements.
30572 The program simply increments its input value by 1:
30573
30574 @smallexample @c ada
30575 @group
30576 with Interfaces; use Interfaces;
30577 with Ada.Text_IO; use Ada.Text_IO;
30578 with System.Machine_Code; use System.Machine_Code;
30579 procedure Increment is
30580
30581    function Incr (Value : Unsigned_32) return Unsigned_32 is
30582       Result : Unsigned_32;
30583    begin
30584       Asm ("incl %0",
30585            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30586            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30587       return Result;
30588    end Incr;
30589
30590    Value : Unsigned_32;
30591
30592 begin
30593    Value := 5;
30594    Put_Line ("Value before is" & Value'Img);
30595    Value := Incr (Value);
30596    Put_Line ("Value after is" & Value'Img);
30597 end Increment;
30598 @end group
30599 @end smallexample
30600
30601 The @code{Outputs} parameter to @code{Asm} specifies
30602 that the result will be in the eax register and that it is to be stored
30603 in the @code{Result} variable.
30604
30605 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
30606 but with an @code{Asm_Input} attribute.
30607 The @code{"="} constraint, indicating an output value, is not present.
30608
30609 You can have multiple input variables, in the same way that you can have more
30610 than one output variable.
30611
30612 The parameter count (%0, %1) etc, now starts at the first input
30613 statement, and continues with the output statements.
30614 When both parameters use the same variable, the
30615 compiler will treat them as the same %n operand, which is the case here.
30616
30617 Just as the @code{Outputs} parameter causes the register to be stored into the
30618 target variable after execution of the assembler statements, so does the
30619 @code{Inputs} parameter cause its variable to be loaded into the register
30620 before execution of the assembler statements.
30621
30622 Thus the effect of the @code{Asm} invocation is:
30623 @enumerate
30624 @item load the 32-bit value of @code{Value} into eax
30625 @item execute the @code{incl %eax} instruction
30626 @item store the contents of eax into the @code{Result} variable
30627 @end enumerate
30628
30629 The resulting assembler file (with @option{-O2} optimization) contains:
30630 @smallexample
30631 @group
30632 _increment__incr.1:
30633    subl $4,%esp
30634    movl 8(%esp),%eax
30635 #APP
30636    incl %eax
30637 #NO_APP
30638    movl %eax,%edx
30639    movl %ecx,(%esp)
30640    addl $4,%esp
30641    ret
30642 @end group
30643 @end smallexample
30644
30645 @c ---------------------------------------------------------------------------
30646 @node Inlining Inline Assembler Code
30647 @section Inlining Inline Assembler Code
30648
30649 @noindent
30650 For a short subprogram such as the @code{Incr} function in the previous
30651 section, the overhead of the call and return (creating / deleting the stack
30652 frame) can be significant, compared to the amount of code in the subprogram
30653 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
30654 which directs the compiler to expand invocations of the subprogram at the
30655 point(s) of call, instead of setting up a stack frame for out-of-line calls.
30656 Here is the resulting program:
30657
30658 @smallexample @c ada
30659 @group
30660 with Interfaces; use Interfaces;
30661 with Ada.Text_IO; use Ada.Text_IO;
30662 with System.Machine_Code; use System.Machine_Code;
30663 procedure Increment_2 is
30664
30665    function Incr (Value : Unsigned_32) return Unsigned_32 is
30666       Result : Unsigned_32;
30667    begin
30668       Asm ("incl %0",
30669            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30670            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30671       return Result;
30672    end Incr;
30673    pragma Inline (Increment);
30674
30675    Value : Unsigned_32;
30676
30677 begin
30678    Value := 5;
30679    Put_Line ("Value before is" & Value'Img);
30680    Value := Increment (Value);
30681    Put_Line ("Value after is" & Value'Img);
30682 end Increment_2;
30683 @end group
30684 @end smallexample
30685
30686 Compile the program with both optimization (@option{-O2}) and inlining
30687 (@option{-gnatn}) enabled.
30688
30689 The @code{Incr} function is still compiled as usual, but at the
30690 point in @code{Increment} where our function used to be called:
30691
30692 @smallexample
30693 @group
30694 pushl %edi
30695 call _increment__incr.1
30696 @end group
30697 @end smallexample
30698
30699 @noindent
30700 the code for the function body directly appears:
30701
30702 @smallexample
30703 @group
30704 movl %esi,%eax
30705 #APP
30706    incl %eax
30707 #NO_APP
30708    movl %eax,%edx
30709 @end group
30710 @end smallexample
30711
30712 @noindent
30713 thus saving the overhead of stack frame setup and an out-of-line call.
30714
30715 @c ---------------------------------------------------------------------------
30716 @node Other Asm Functionality
30717 @section Other @code{Asm} Functionality
30718
30719 @noindent
30720 This section describes two important parameters to the @code{Asm}
30721 procedure: @code{Clobber}, which identifies register usage;
30722 and @code{Volatile}, which inhibits unwanted optimizations.
30723
30724 @menu
30725 * The Clobber Parameter::
30726 * The Volatile Parameter::
30727 @end menu
30728
30729 @c ---------------------------------------------------------------------------
30730 @node The Clobber Parameter
30731 @subsection The @code{Clobber} Parameter
30732
30733 @noindent
30734 One of the dangers of intermixing assembly language and a compiled language
30735 such as Ada is that the compiler needs to be aware of which registers are
30736 being used by the assembly code.  In some cases, such as the earlier examples,
30737 the constraint string is sufficient to indicate register usage (e.g.,
30738 @code{"a"} for
30739 the eax register).  But more generally, the compiler needs an explicit
30740 identification of the registers that are used by the Inline Assembly
30741 statements.
30742
30743 Using a register that the compiler doesn't know about
30744 could be a side effect of an instruction (like @code{mull}
30745 storing its result in both eax and edx).
30746 It can also arise from explicit register usage in your
30747 assembly code; for example:
30748 @smallexample
30749 @group
30750 Asm ("movl %0, %%ebx" & LF & HT &
30751      "movl %%ebx, %1",
30752      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30753      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
30754 @end group
30755 @end smallexample
30756 @noindent
30757 where the compiler (since it does not analyze the @code{Asm} template string)
30758 does not know you are using the ebx register.
30759
30760 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
30761 to identify the registers that will be used by your assembly code:
30762
30763 @smallexample
30764 @group
30765 Asm ("movl %0, %%ebx" & LF & HT &
30766      "movl %%ebx, %1",
30767      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30768      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30769      Clobber => "ebx");
30770 @end group
30771 @end smallexample
30772
30773 The Clobber parameter is a static string expression specifying the
30774 register(s) you are using.  Note that register names are @emph{not} prefixed
30775 by a percent sign. Also, if more than one register is used then their names
30776 are separated by commas; e.g., @code{"eax, ebx"}
30777
30778 The @code{Clobber} parameter has several additional uses:
30779 @enumerate
30780 @item Use ``register'' name @code{cc} to indicate that flags might have changed
30781 @item Use ``register'' name @code{memory} if you changed a memory location
30782 @end enumerate
30783
30784 @c ---------------------------------------------------------------------------
30785 @node The Volatile Parameter
30786 @subsection The @code{Volatile} Parameter
30787 @cindex Volatile parameter
30788
30789 @noindent
30790 Compiler optimizations in the presence of Inline Assembler may sometimes have
30791 unwanted effects.  For example, when an @code{Asm} invocation with an input
30792 variable is inside a loop, the compiler might move the loading of the input
30793 variable outside the loop, regarding it as a one-time initialization.
30794
30795 If this effect is not desired, you can disable such optimizations by setting
30796 the @code{Volatile} parameter to @code{True}; for example:
30797
30798 @smallexample @c ada
30799 @group
30800 Asm ("movl %0, %%ebx" & LF & HT &
30801      "movl %%ebx, %1",
30802      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
30803      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
30804      Clobber  => "ebx",
30805      Volatile => True);
30806 @end group
30807 @end smallexample
30808
30809 By default, @code{Volatile} is set to @code{False} unless there is no
30810 @code{Outputs} parameter.
30811
30812 Although setting @code{Volatile} to @code{True} prevents unwanted
30813 optimizations, it will also disable other optimizations that might be
30814 important for efficiency. In general, you should set @code{Volatile}
30815 to @code{True} only if the compiler's optimizations have created
30816 problems.
30817 @c END OF INLINE ASSEMBLER CHAPTER
30818 @c ===============================
30819
30820 @c ***********************************
30821 @c * Compatibility and Porting Guide *
30822 @c ***********************************
30823 @node Compatibility and Porting Guide
30824 @appendix Compatibility and Porting Guide
30825
30826 @noindent
30827 This chapter describes the compatibility issues that may arise between
30828 GNAT and other Ada compilation systems (including those for Ada 83),
30829 and shows how GNAT can expedite porting
30830 applications developed in other Ada environments.
30831
30832 @menu
30833 * Compatibility with Ada 83::
30834 * Compatibility between Ada 95 and Ada 2005::
30835 * Implementation-dependent characteristics::
30836 * Compatibility with Other Ada Systems::
30837 * Representation Clauses::
30838 @ifclear vms
30839 @c Brief section is only in non-VMS version
30840 @c Full chapter is in VMS version
30841 * Compatibility with HP Ada 83::
30842 @end ifclear
30843 @ifset vms
30844 * Transitioning to 64-Bit GNAT for OpenVMS::
30845 @end ifset
30846 @end menu
30847
30848 @node Compatibility with Ada 83
30849 @section Compatibility with Ada 83
30850 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
30851
30852 @noindent
30853 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
30854 particular, the design intention was that the difficulties associated
30855 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
30856 that occur when moving from one Ada 83 system to another.
30857
30858 However, there are a number of points at which there are minor
30859 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
30860 full details of these issues,
30861 and should be consulted for a complete treatment.
30862 In practice the
30863 following subsections treat the most likely issues to be encountered.
30864
30865 @menu
30866 * Legal Ada 83 programs that are illegal in Ada 95::
30867 * More deterministic semantics::
30868 * Changed semantics::
30869 * Other language compatibility issues::
30870 @end menu
30871
30872 @node Legal Ada 83 programs that are illegal in Ada 95
30873 @subsection Legal Ada 83 programs that are illegal in Ada 95
30874
30875 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
30876 Ada 95 and thus also in Ada 2005:
30877
30878 @table @emph
30879 @item Character literals
30880 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
30881 @code{Wide_Character} as a new predefined character type, some uses of
30882 character literals that were legal in Ada 83 are illegal in Ada 95.
30883 For example:
30884 @smallexample @c ada
30885    for Char in 'A' .. 'Z' loop @dots{} end loop;
30886 @end smallexample
30887
30888 @noindent
30889 The problem is that @code{'A'} and @code{'Z'} could be from either
30890 @code{Character} or @code{Wide_Character}.  The simplest correction
30891 is to make the type explicit; e.g.:
30892 @smallexample @c ada
30893    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
30894 @end smallexample
30895
30896 @item New reserved words
30897 The identifiers @code{abstract}, @code{aliased}, @code{protected},
30898 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
30899 Existing Ada 83 code using any of these identifiers must be edited to
30900 use some alternative name.
30901
30902 @item Freezing rules
30903 The rules in Ada 95 are slightly different with regard to the point at
30904 which entities are frozen, and representation pragmas and clauses are
30905 not permitted past the freeze point.  This shows up most typically in
30906 the form of an error message complaining that a representation item
30907 appears too late, and the appropriate corrective action is to move
30908 the item nearer to the declaration of the entity to which it refers.
30909
30910 A particular case is that representation pragmas
30911 @ifset vms
30912 (including the
30913 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
30914 @end ifset
30915 cannot be applied to a subprogram body.  If necessary, a separate subprogram
30916 declaration must be introduced to which the pragma can be applied.
30917
30918 @item Optional bodies for library packages
30919 In Ada 83, a package that did not require a package body was nevertheless
30920 allowed to have one.  This lead to certain surprises in compiling large
30921 systems (situations in which the body could be unexpectedly ignored by the
30922 binder).  In Ada 95, if a package does not require a body then it is not
30923 permitted to have a body.  To fix this problem, simply remove a redundant
30924 body if it is empty, or, if it is non-empty, introduce a dummy declaration
30925 into the spec that makes the body required.  One approach is to add a private
30926 part to the package declaration (if necessary), and define a parameterless
30927 procedure called @code{Requires_Body}, which must then be given a dummy
30928 procedure body in the package body, which then becomes required.
30929 Another approach (assuming that this does not introduce elaboration
30930 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
30931 since one effect of this pragma is to require the presence of a package body.
30932
30933 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
30934 In Ada 95, the exception @code{Numeric_Error} is a renaming of
30935 @code{Constraint_Error}.
30936 This means that it is illegal to have separate exception handlers for
30937 the two exceptions.  The fix is simply to remove the handler for the
30938 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
30939 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
30940
30941 @item Indefinite subtypes in generics
30942 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
30943 as the actual for a generic formal private type, but then the instantiation
30944 would be illegal if there were any instances of declarations of variables
30945 of this type in the generic body.  In Ada 95, to avoid this clear violation
30946 of the methodological principle known as the ``contract model'',
30947 the generic declaration explicitly indicates whether
30948 or not such instantiations are permitted.  If a generic formal parameter
30949 has explicit unknown discriminants, indicated by using @code{(<>)} after the
30950 type name, then it can be instantiated with indefinite types, but no
30951 stand-alone variables can be declared of this type.  Any attempt to declare
30952 such a variable will result in an illegality at the time the generic is
30953 declared.  If the @code{(<>)} notation is not used, then it is illegal
30954 to instantiate the generic with an indefinite type.
30955 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
30956 It will show up as a compile time error, and
30957 the fix is usually simply to add the @code{(<>)} to the generic declaration.
30958 @end table
30959
30960 @node More deterministic semantics
30961 @subsection More deterministic semantics
30962
30963 @table @emph
30964 @item Conversions
30965 Conversions from real types to integer types round away from 0.  In Ada 83
30966 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
30967 implementation freedom was intended to support unbiased rounding in
30968 statistical applications, but in practice it interfered with portability.
30969 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
30970 is required.  Numeric code may be affected by this change in semantics.
30971 Note, though, that this issue is no worse than already existed in Ada 83
30972 when porting code from one vendor to another.
30973
30974 @item Tasking
30975 The Real-Time Annex introduces a set of policies that define the behavior of
30976 features that were implementation dependent in Ada 83, such as the order in
30977 which open select branches are executed.
30978 @end table
30979
30980 @node Changed semantics
30981 @subsection Changed semantics
30982
30983 @noindent
30984 The worst kind of incompatibility is one where a program that is legal in
30985 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
30986 possible in Ada 83.  Fortunately this is extremely rare, but the one
30987 situation that you should be alert to is the change in the predefined type
30988 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
30989
30990 @table @emph
30991 @item Range of type @code{Character}
30992 The range of @code{Standard.Character} is now the full 256 characters
30993 of Latin-1, whereas in most Ada 83 implementations it was restricted
30994 to 128 characters. Although some of the effects of
30995 this change will be manifest in compile-time rejection of legal
30996 Ada 83 programs it is possible for a working Ada 83 program to have
30997 a different effect in Ada 95, one that was not permitted in Ada 83.
30998 As an example, the expression
30999 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
31000 delivers @code{255} as its value.
31001 In general, you should look at the logic of any
31002 character-processing Ada 83 program and see whether it needs to be adapted
31003 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
31004 character handling package that may be relevant if code needs to be adapted
31005 to account for the additional Latin-1 elements.
31006 The desirable fix is to
31007 modify the program to accommodate the full character set, but in some cases
31008 it may be convenient to define a subtype or derived type of Character that
31009 covers only the restricted range.
31010 @cindex Latin-1
31011 @end table
31012
31013 @node Other language compatibility issues
31014 @subsection Other language compatibility issues
31015
31016 @table @emph
31017 @item @option{-gnat83} switch
31018 All implementations of GNAT provide a switch that causes GNAT to operate
31019 in Ada 83 mode.  In this mode, some but not all compatibility problems
31020 of the type described above are handled automatically.  For example, the
31021 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
31022 as identifiers as in Ada 83.
31023 However,
31024 in practice, it is usually advisable to make the necessary modifications
31025 to the program to remove the need for using this switch.
31026 See @ref{Compiling Different Versions of Ada}.
31027
31028 @item Support for removed Ada 83 pragmas and attributes
31029 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
31030 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
31031 compilers are allowed, but not required, to implement these missing
31032 elements.  In contrast with some other compilers, GNAT implements all
31033 such pragmas and attributes, eliminating this compatibility concern.  These
31034 include @code{pragma Interface} and the floating point type attributes
31035 (@code{Emax}, @code{Mantissa}, etc.), among other items.
31036 @end table
31037
31038
31039 @node Compatibility between Ada 95 and Ada 2005
31040 @section Compatibility between Ada 95 and Ada 2005
31041 @cindex Compatibility between Ada 95 and Ada 2005
31042
31043 @noindent
31044 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
31045 a number of incompatibilities. Several are enumerated below;
31046 for a complete description please see the
31047 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
31048 @cite{Rationale for Ada 2005}.
31049
31050 @table @emph
31051 @item New reserved words.
31052 The words @code{interface}, @code{overriding} and @code{synchronized} are
31053 reserved in Ada 2005.
31054 A pre-Ada 2005 program that uses any of these as an identifier will be
31055 illegal.
31056
31057 @item New declarations in predefined packages.
31058 A number of packages in the predefined environment contain new declarations:
31059 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
31060 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
31061 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
31062 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
31063 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
31064 If an Ada 95 program does a @code{with} and @code{use} of any of these
31065 packages, the new declarations may cause name clashes.
31066
31067 @item Access parameters.
31068 A nondispatching subprogram with an access parameter cannot be renamed
31069 as a dispatching operation.  This was permitted in Ada 95.
31070
31071 @item Access types, discriminants, and constraints.
31072 Rule changes in this area have led to some incompatibilities; for example,
31073 constrained subtypes of some access types are not permitted in Ada 2005.
31074
31075 @item Aggregates for limited types.
31076 The allowance of aggregates for limited types in Ada 2005 raises the
31077 possibility of ambiguities in legal Ada 95 programs, since additional types
31078 now need to be considered in expression resolution.
31079
31080 @item Fixed-point multiplication and division.
31081 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
31082 were legal in Ada 95 and invoked the predefined versions of these operations,
31083 are now ambiguous.
31084 The ambiguity may be resolved either by applying a type conversion to the
31085 expression, or by explicitly invoking the operation from package
31086 @code{Standard}.
31087
31088 @item Return-by-reference types.
31089 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
31090 can declare a function returning a value from an anonymous access type.
31091 @end table
31092
31093
31094 @node Implementation-dependent characteristics
31095 @section Implementation-dependent characteristics
31096 @noindent
31097 Although the Ada language defines the semantics of each construct as
31098 precisely as practical, in some situations (for example for reasons of
31099 efficiency, or where the effect is heavily dependent on the host or target
31100 platform) the implementation is allowed some freedom.  In porting Ada 83
31101 code to GNAT, you need to be aware of whether / how the existing code
31102 exercised such implementation dependencies.  Such characteristics fall into
31103 several categories, and GNAT offers specific support in assisting the
31104 transition from certain Ada 83 compilers.
31105
31106 @menu
31107 * Implementation-defined pragmas::
31108 * Implementation-defined attributes::
31109 * Libraries::
31110 * Elaboration order::
31111 * Target-specific aspects::
31112 @end menu
31113
31114 @node Implementation-defined pragmas
31115 @subsection Implementation-defined pragmas
31116
31117 @noindent
31118 Ada compilers are allowed to supplement the language-defined pragmas, and
31119 these are a potential source of non-portability.  All GNAT-defined pragmas
31120 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
31121 Reference Manual}, and these include several that are specifically
31122 intended to correspond to other vendors' Ada 83 pragmas.
31123 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
31124 For compatibility with HP Ada 83, GNAT supplies the pragmas
31125 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
31126 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
31127 and @code{Volatile}.
31128 Other relevant pragmas include @code{External} and @code{Link_With}.
31129 Some vendor-specific
31130 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
31131 recognized, thus
31132 avoiding compiler rejection of units that contain such pragmas; they are not
31133 relevant in a GNAT context and hence are not otherwise implemented.
31134
31135 @node Implementation-defined attributes
31136 @subsection Implementation-defined attributes
31137
31138 Analogous to pragmas, the set of attributes may be extended by an
31139 implementation.  All GNAT-defined attributes are described in
31140 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
31141 Manual}, and these include several that are specifically intended
31142 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
31143 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
31144 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
31145 @code{Type_Class}.
31146
31147 @node Libraries
31148 @subsection Libraries
31149 @noindent
31150 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
31151 code uses vendor-specific libraries then there are several ways to manage
31152 this in Ada 95 or Ada 2005:
31153 @enumerate
31154 @item
31155 If the source code for the libraries (specs and bodies) are
31156 available, then the libraries can be migrated in the same way as the
31157 application.
31158 @item
31159 If the source code for the specs but not the bodies are
31160 available, then you can reimplement the bodies.
31161 @item
31162 Some features introduced by Ada 95 obviate the need for library support.  For
31163 example most Ada 83 vendors supplied a package for unsigned integers.  The
31164 Ada 95 modular type feature is the preferred way to handle this need, so
31165 instead of migrating or reimplementing the unsigned integer package it may
31166 be preferable to retrofit the application using modular types.
31167 @end enumerate
31168
31169 @node Elaboration order
31170 @subsection Elaboration order
31171 @noindent
31172 The implementation can choose any elaboration order consistent with the unit
31173 dependency relationship.  This freedom means that some orders can result in
31174 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
31175 to invoke a subprogram its body has been elaborated, or to instantiate a
31176 generic before the generic body has been elaborated.  By default GNAT
31177 attempts to choose a safe order (one that will not encounter access before
31178 elaboration problems) by implicitly inserting @code{Elaborate} or
31179 @code{Elaborate_All} pragmas where
31180 needed.  However, this can lead to the creation of elaboration circularities
31181 and a resulting rejection of the program by gnatbind.  This issue is
31182 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
31183 In brief, there are several
31184 ways to deal with this situation:
31185
31186 @itemize @bullet
31187 @item
31188 Modify the program to eliminate the circularities, e.g.@: by moving
31189 elaboration-time code into explicitly-invoked procedures
31190 @item
31191 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
31192 @code{Elaborate} pragmas, and then inhibit the generation of implicit
31193 @code{Elaborate_All}
31194 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
31195 (by selectively suppressing elaboration checks via pragma
31196 @code{Suppress(Elaboration_Check)} when it is safe to do so).
31197 @end itemize
31198
31199 @node Target-specific aspects
31200 @subsection Target-specific aspects
31201 @noindent
31202 Low-level applications need to deal with machine addresses, data
31203 representations, interfacing with assembler code, and similar issues.  If
31204 such an Ada 83 application is being ported to different target hardware (for
31205 example where the byte endianness has changed) then you will need to
31206 carefully examine the program logic; the porting effort will heavily depend
31207 on the robustness of the original design.  Moreover, Ada 95 (and thus
31208 Ada 2005) are sometimes
31209 incompatible with typical Ada 83 compiler practices regarding implicit
31210 packing, the meaning of the Size attribute, and the size of access values.
31211 GNAT's approach to these issues is described in @ref{Representation Clauses}.
31212
31213 @node Compatibility with Other Ada Systems
31214 @section Compatibility with Other Ada Systems
31215
31216 @noindent
31217 If programs avoid the use of implementation dependent and
31218 implementation defined features, as documented in the @cite{Ada
31219 Reference Manual}, there should be a high degree of portability between
31220 GNAT and other Ada systems.  The following are specific items which
31221 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
31222 compilers, but do not affect porting code to GNAT@.
31223 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
31224 the following issues may or may not arise for Ada 2005 programs
31225 when other compilers appear.)
31226
31227 @table @emph
31228 @item Ada 83 Pragmas and Attributes
31229 Ada 95 compilers are allowed, but not required, to implement the missing
31230 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
31231 GNAT implements all such pragmas and attributes, eliminating this as
31232 a compatibility concern, but some other Ada 95 compilers reject these
31233 pragmas and attributes.
31234
31235 @item Specialized Needs Annexes
31236 GNAT implements the full set of special needs annexes.  At the
31237 current time, it is the only Ada 95 compiler to do so.  This means that
31238 programs making use of these features may not be portable to other Ada
31239 95 compilation systems.
31240
31241 @item Representation Clauses
31242 Some other Ada 95 compilers implement only the minimal set of
31243 representation clauses required by the Ada 95 reference manual.  GNAT goes
31244 far beyond this minimal set, as described in the next section.
31245 @end table
31246
31247 @node Representation Clauses
31248 @section Representation Clauses
31249
31250 @noindent
31251 The Ada 83 reference manual was quite vague in describing both the minimal
31252 required implementation of representation clauses, and also their precise
31253 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
31254 minimal set of capabilities required is still quite limited.
31255
31256 GNAT implements the full required set of capabilities in
31257 Ada 95 and Ada 2005, but also goes much further, and in particular
31258 an effort has been made to be compatible with existing Ada 83 usage to the
31259 greatest extent possible.
31260
31261 A few cases exist in which Ada 83 compiler behavior is incompatible with
31262 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
31263 intentional or accidental dependence on specific implementation dependent
31264 characteristics of these Ada 83 compilers.  The following is a list of
31265 the cases most likely to arise in existing Ada 83 code.
31266
31267 @table @emph
31268 @item Implicit Packing
31269 Some Ada 83 compilers allowed a Size specification to cause implicit
31270 packing of an array or record.  This could cause expensive implicit
31271 conversions for change of representation in the presence of derived
31272 types, and the Ada design intends to avoid this possibility.
31273 Subsequent AI's were issued to make it clear that such implicit
31274 change of representation in response to a Size clause is inadvisable,
31275 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
31276 Reference Manuals as implementation advice that is followed by GNAT@.
31277 The problem will show up as an error
31278 message rejecting the size clause.  The fix is simply to provide
31279 the explicit pragma @code{Pack}, or for more fine tuned control, provide
31280 a Component_Size clause.
31281
31282 @item Meaning of Size Attribute
31283 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
31284 the minimal number of bits required to hold values of the type.  For example,
31285 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
31286 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
31287 some 32 in this situation.  This problem will usually show up as a compile
31288 time error, but not always.  It is a good idea to check all uses of the
31289 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
31290 Object_Size can provide a useful way of duplicating the behavior of
31291 some Ada 83 compiler systems.
31292
31293 @item Size of Access Types
31294 A common assumption in Ada 83 code is that an access type is in fact a pointer,
31295 and that therefore it will be the same size as a System.Address value.  This
31296 assumption is true for GNAT in most cases with one exception.  For the case of
31297 a pointer to an unconstrained array type (where the bounds may vary from one
31298 value of the access type to another), the default is to use a ``fat pointer'',
31299 which is represented as two separate pointers, one to the bounds, and one to
31300 the array.  This representation has a number of advantages, including improved
31301 efficiency.  However, it may cause some difficulties in porting existing Ada 83
31302 code which makes the assumption that, for example, pointers fit in 32 bits on
31303 a machine with 32-bit addressing.
31304
31305 To get around this problem, GNAT also permits the use of ``thin pointers'' for
31306 access types in this case (where the designated type is an unconstrained array
31307 type).  These thin pointers are indeed the same size as a System.Address value.
31308 To specify a thin pointer, use a size clause for the type, for example:
31309
31310 @smallexample @c ada
31311 type X is access all String;
31312 for X'Size use Standard'Address_Size;
31313 @end smallexample
31314
31315 @noindent
31316 which will cause the type X to be represented using a single pointer.
31317 When using this representation, the bounds are right behind the array.
31318 This representation is slightly less efficient, and does not allow quite
31319 such flexibility in the use of foreign pointers or in using the
31320 Unrestricted_Access attribute to create pointers to non-aliased objects.
31321 But for any standard portable use of the access type it will work in
31322 a functionally correct manner and allow porting of existing code.
31323 Note that another way of forcing a thin pointer representation
31324 is to use a component size clause for the element size in an array,
31325 or a record representation clause for an access field in a record.
31326 @end table
31327
31328 @ifclear vms
31329 @c This brief section is only in the non-VMS version
31330 @c The complete chapter on HP Ada is in the VMS version
31331 @node Compatibility with HP Ada 83
31332 @section Compatibility with HP Ada 83
31333
31334 @noindent
31335 The VMS version of GNAT fully implements all the pragmas and attributes
31336 provided by HP Ada 83, as well as providing the standard HP Ada 83
31337 libraries, including Starlet.  In addition, data layouts and parameter
31338 passing conventions are highly compatible.  This means that porting
31339 existing HP Ada 83 code to GNAT in VMS systems should be easier than
31340 most other porting efforts.  The following are some of the most
31341 significant differences between GNAT and HP Ada 83.
31342
31343 @table @emph
31344 @item Default floating-point representation
31345 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
31346 it is VMS format.  GNAT does implement the necessary pragmas
31347 (Long_Float, Float_Representation) for changing this default.
31348
31349 @item System
31350 The package System in GNAT exactly corresponds to the definition in the
31351 Ada 95 reference manual, which means that it excludes many of the
31352 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
31353 that contains the additional definitions, and a special pragma,
31354 Extend_System allows this package to be treated transparently as an
31355 extension of package System.
31356
31357 @item To_Address
31358 The definitions provided by Aux_DEC are exactly compatible with those
31359 in the HP Ada 83 version of System, with one exception.
31360 HP Ada provides the following declarations:
31361
31362 @smallexample @c ada
31363 TO_ADDRESS (INTEGER)
31364 TO_ADDRESS (UNSIGNED_LONGWORD)
31365 TO_ADDRESS (@i{universal_integer})
31366 @end smallexample
31367
31368 @noindent
31369 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
31370 an extension to Ada 83 not strictly compatible with the reference manual.
31371 In GNAT, we are constrained to be exactly compatible with the standard,
31372 and this means we cannot provide this capability.  In HP Ada 83, the
31373 point of this definition is to deal with a call like:
31374
31375 @smallexample @c ada
31376 TO_ADDRESS (16#12777#);
31377 @end smallexample
31378
31379 @noindent
31380 Normally, according to the Ada 83 standard, one would expect this to be
31381 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
31382 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
31383 definition using @i{universal_integer} takes precedence.
31384
31385 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
31386 is not possible to be 100% compatible.  Since there are many programs using
31387 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
31388 to change the name of the function in the UNSIGNED_LONGWORD case, so the
31389 declarations provided in the GNAT version of AUX_Dec are:
31390
31391 @smallexample @c ada
31392 function To_Address (X : Integer) return Address;
31393 pragma Pure_Function (To_Address);
31394
31395 function To_Address_Long (X : Unsigned_Longword)
31396  return Address;
31397 pragma Pure_Function (To_Address_Long);
31398 @end smallexample
31399
31400 @noindent
31401 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
31402 change the name to TO_ADDRESS_LONG@.
31403
31404 @item Task_Id values
31405 The Task_Id values assigned will be different in the two systems, and GNAT
31406 does not provide a specified value for the Task_Id of the environment task,
31407 which in GNAT is treated like any other declared task.
31408 @end table
31409
31410 @noindent
31411 For full details on these and other less significant compatibility issues,
31412 see appendix E of the HP publication entitled @cite{HP Ada, Technical
31413 Overview and Comparison on HP Platforms}.
31414
31415 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
31416 attributes are recognized, although only a subset of them can sensibly
31417 be implemented.  The description of pragmas in @ref{Implementation
31418 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
31419 indicates whether or not they are applicable to non-VMS systems.
31420 @end ifclear
31421
31422 @ifset vms
31423 @node Transitioning to 64-Bit GNAT for OpenVMS
31424 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
31425
31426 @noindent
31427 This section is meant to assist users of pre-2006 @value{EDITION}
31428 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
31429 the version of the GNAT technology supplied in 2006 and later for
31430 OpenVMS on both Alpha and I64.
31431
31432 @menu
31433 * Introduction to transitioning::
31434 * Migration of 32 bit code::
31435 * Taking advantage of 64 bit addressing::
31436 * Technical details::
31437 @end menu
31438
31439 @node Introduction to transitioning
31440 @subsection Introduction
31441
31442 @noindent
31443 64-bit @value{EDITION} for Open VMS has been designed to meet
31444 three main goals:
31445
31446 @enumerate
31447 @item
31448 Providing a full conforming implementation of Ada 95 and Ada 2005
31449
31450 @item
31451 Allowing maximum backward compatibility, thus easing migration of existing
31452 Ada source code
31453
31454 @item
31455 Supplying a path for exploiting the full 64-bit address range
31456 @end enumerate
31457
31458 @noindent
31459 Ada's strong typing semantics has made it
31460 impractical to have different 32-bit and 64-bit modes. As soon as
31461 one object could possibly be outside the 32-bit address space, this
31462 would make it necessary for the @code{System.Address} type to be 64 bits.
31463 In particular, this would cause inconsistencies if 32-bit code is
31464 called from 64-bit code that raises an exception.
31465
31466 This issue has been resolved by always using 64-bit addressing
31467 at the system level, but allowing for automatic conversions between
31468 32-bit and 64-bit addresses where required. Thus users who
31469 do not currently require 64-bit addressing capabilities, can
31470 recompile their code with only minimal changes (and indeed
31471 if the code is written in portable Ada, with no assumptions about
31472 the size of the @code{Address} type, then no changes at all are necessary).
31473 At the same time,
31474 this approach provides a simple, gradual upgrade path to future
31475 use of larger memories than available for 32-bit systems.
31476 Also, newly written applications or libraries will by default
31477 be fully compatible with future systems exploiting 64-bit
31478 addressing capabilities.
31479
31480 @ref{Migration of 32 bit code}, will focus on porting applications
31481 that do not require more than 2 GB of
31482 addressable memory. This code will be referred to as
31483 @emph{32-bit code}.
31484 For applications intending to exploit the full 64-bit address space,
31485 @ref{Taking advantage of 64 bit addressing},
31486 will consider further changes that may be required.
31487 Such code will be referred to below as @emph{64-bit code}.
31488
31489 @node Migration of 32 bit code
31490 @subsection Migration of 32-bit code
31491
31492 @menu
31493 * Address types::
31494 * Access types::
31495 * Unchecked conversions::
31496 * Predefined constants::
31497 * Interfacing with C::
31498 * Experience with source compatibility::
31499 @end menu
31500
31501 @node Address types
31502 @subsubsection Address types
31503
31504 @noindent
31505 To solve the problem of mixing 64-bit and 32-bit addressing,
31506 while maintaining maximum backward compatibility, the following
31507 approach has been taken:
31508
31509 @itemize @bullet
31510 @item
31511 @code{System.Address} always has a size of 64 bits
31512
31513 @item
31514 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
31515 @end itemize
31516
31517 @noindent
31518 Since @code{System.Short_Address} is a subtype of @code{System.Address},
31519 a @code{Short_Address}
31520 may be used where an @code{Address} is required, and vice versa, without
31521 needing explicit type conversions.
31522 By virtue of the Open VMS parameter passing conventions,
31523 even imported
31524 and exported subprograms that have 32-bit address parameters are
31525 compatible with those that have 64-bit address parameters.
31526 (See @ref{Making code 64 bit clean} for details.)
31527
31528 The areas that may need attention are those where record types have
31529 been defined that contain components of the type @code{System.Address}, and
31530 where objects of this type are passed to code expecting a record layout with
31531 32-bit addresses.
31532
31533 Different compilers on different platforms cannot be
31534 expected to represent the same type in the same way,
31535 since alignment constraints
31536 and other system-dependent properties affect the compiler's decision.
31537 For that reason, Ada code
31538 generally uses representation clauses to specify the expected
31539 layout where required.
31540
31541 If such a representation clause uses 32 bits for a component having
31542 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
31543 will detect that error and produce a specific diagnostic message.
31544 The developer should then determine whether the representation
31545 should be 64 bits or not and make either of two changes:
31546 change the size to 64 bits and leave the type as @code{System.Address}, or
31547 leave the size as 32 bits and change the type to @code{System.Short_Address}.
31548 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
31549 required in any code setting or accessing the field; the compiler will
31550 automatically perform any needed conversions between address
31551 formats.
31552
31553 @node Access types
31554 @subsubsection Access types
31555
31556 @noindent
31557 By default, objects designated by access values are always
31558 allocated in the 32-bit
31559 address space. Thus legacy code will never contain
31560 any objects that are not addressable with 32-bit addresses, and
31561 the compiler will never raise exceptions as result of mixing
31562 32-bit and 64-bit addresses.
31563
31564 However, the access values themselves are represented in 64 bits, for optimum
31565 performance and future compatibility with 64-bit code. As was
31566 the case with @code{System.Address}, the compiler will give an error message
31567 if an object or record component has a representation clause that
31568 requires the access value to fit in 32 bits. In such a situation,
31569 an explicit size clause for the access type, specifying 32 bits,
31570 will have the desired effect.
31571
31572 General access types (declared with @code{access all}) can never be
31573 32 bits, as values of such types must be able to refer to any object
31574 of the  designated type,
31575 including objects residing outside the 32-bit address range.
31576 Existing Ada 83 code will not contain such type definitions,
31577 however, since general access types were introduced in Ada 95.
31578
31579 @node Unchecked conversions
31580 @subsubsection Unchecked conversions
31581
31582 @noindent
31583 In the case of an @code{Unchecked_Conversion} where the source type is a
31584 64-bit access type or the type @code{System.Address}, and the target
31585 type is a 32-bit type, the compiler will generate a warning.
31586 Even though the generated code will still perform the required
31587 conversions, it is highly recommended in these cases to use
31588 respectively a 32-bit access type or @code{System.Short_Address}
31589 as the source type.
31590
31591 @node Predefined constants
31592 @subsubsection Predefined constants
31593
31594 @noindent
31595 The following table shows the correspondence between pre-2006 versions of
31596 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
31597 (``New''):
31598
31599 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
31600 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
31601 @item   @code{System.Word_Size}          @tab 32      @tab 64
31602 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
31603 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
31604 @item   @code{System.Address_Size}       @tab 32      @tab 64
31605 @end multitable
31606
31607 @noindent
31608 If you need to refer to the specific
31609 memory size of a 32-bit implementation, instead of the
31610 actual memory size, use @code{System.Short_Memory_Size}
31611 rather than @code{System.Memory_Size}.
31612 Similarly, references to @code{System.Address_Size} may need
31613 to be replaced by @code{System.Short_Address'Size}.
31614 The program @command{gnatfind} may be useful for locating
31615 references to the above constants, so that you can verify that they
31616 are still correct.
31617
31618 @node Interfacing with C
31619 @subsubsection Interfacing with C
31620
31621 @noindent
31622 In order to minimize the impact of the transition to 64-bit addresses on
31623 legacy programs, some fundamental types in the @code{Interfaces.C}
31624 package hierarchy continue to be represented in 32 bits.
31625 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
31626 This eases integration with the default HP C layout choices, for example
31627 as found in the system routines in @code{DECC$SHR.EXE}.
31628 Because of this implementation choice, the type fully compatible with
31629 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
31630 Depending on the context the compiler will issue a
31631 warning or an error when type @code{Address} is used, alerting the user to a
31632 potential problem. Otherwise 32-bit programs that use
31633 @code{Interfaces.C} should normally not require code modifications
31634
31635 The other issue arising with C interfacing concerns pragma @code{Convention}.
31636 For VMS 64-bit systems, there is an issue of the appropriate default size
31637 of C convention pointers in the absence of an explicit size clause. The HP
31638 C compiler can choose either 32 or 64 bits depending on compiler options.
31639 GNAT chooses 32-bits rather than 64-bits in the default case where no size
31640 clause is given. This proves a better choice for porting 32-bit legacy
31641 applications. In order to have a 64-bit representation, it is necessary to
31642 specify a size representation clause. For example:
31643
31644 @smallexample @c ada
31645 type int_star is access Interfaces.C.int;
31646 pragma Convention(C, int_star);
31647 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
31648 @end smallexample
31649
31650 @node Experience with source compatibility
31651 @subsubsection Experience with source compatibility
31652
31653 @noindent
31654 The Security Server and STARLET on I64 provide an interesting ``test case''
31655 for source compatibility issues, since it is in such system code
31656 where assumptions about @code{Address} size might be expected to occur.
31657 Indeed, there were a small number of occasions in the Security Server
31658 file @file{jibdef.ads}
31659 where a representation clause for a record type specified
31660 32 bits for a component of type @code{Address}.
31661 All of these errors were detected by the compiler.
31662 The repair was obvious and immediate; to simply replace @code{Address} by
31663 @code{Short_Address}.
31664
31665 In the case of STARLET, there were several record types that should
31666 have had representation clauses but did not.  In these record types
31667 there was an implicit assumption that an @code{Address} value occupied
31668 32 bits.
31669 These compiled without error, but their usage resulted in run-time error
31670 returns from STARLET system calls.
31671 Future GNAT technology enhancements may include a tool that detects and flags
31672 these sorts of potential source code porting problems.
31673
31674 @c ****************************************
31675 @node Taking advantage of 64 bit addressing
31676 @subsection Taking advantage of 64-bit addressing
31677
31678 @menu
31679 * Making code 64 bit clean::
31680 * Allocating memory from the 64 bit storage pool::
31681 * Restrictions on use of 64 bit objects::
31682 * Using 64 bit storage pools by default::
31683 * General access types::
31684 * STARLET and other predefined libraries::
31685 @end menu
31686
31687 @node Making code 64 bit clean
31688 @subsubsection Making code 64-bit clean
31689
31690 @noindent
31691 In order to prevent problems that may occur when (parts of) a
31692 system start using memory outside the 32-bit address range,
31693 we recommend some additional guidelines:
31694
31695 @itemize @bullet
31696 @item
31697 For imported subprograms that take parameters of the
31698 type @code{System.Address}, ensure that these subprograms can
31699 indeed handle 64-bit addresses. If not, or when in doubt,
31700 change the subprogram declaration to specify
31701 @code{System.Short_Address} instead.
31702
31703 @item
31704 Resolve all warnings related to size mismatches in
31705 unchecked conversions. Failing to do so causes
31706 erroneous execution if the source object is outside
31707 the 32-bit address space.
31708
31709 @item
31710 (optional) Explicitly use the 32-bit storage pool
31711 for access types used in a 32-bit context, or use
31712 generic access types where possible
31713 (@pxref{Restrictions on use of 64 bit objects}).
31714 @end itemize
31715
31716 @noindent
31717 If these rules are followed, the compiler will automatically insert
31718 any necessary checks to ensure that no addresses or access values
31719 passed to 32-bit code ever refer to objects outside the 32-bit
31720 address range.
31721 Any attempt to do this will raise @code{Constraint_Error}.
31722
31723 @node Allocating memory from the 64 bit storage pool
31724 @subsubsection Allocating memory from the 64-bit storage pool
31725
31726 @noindent
31727 For any access type @code{T} that potentially requires memory allocations
31728 beyond the 32-bit address space,
31729 use the following representation clause:
31730
31731 @smallexample @c ada
31732    for T'Storage_Pool use System.Pool_64;
31733 @end smallexample
31734
31735 @node Restrictions on use of 64 bit objects
31736 @subsubsection Restrictions on use of 64-bit objects
31737
31738 @noindent
31739 Taking the address of an object allocated from a 64-bit storage pool,
31740 and then passing this address to a subprogram expecting
31741 @code{System.Short_Address},
31742 or assigning it to a variable of type @code{Short_Address}, will cause
31743 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
31744 (@pxref{Making code 64 bit clean}), or checks are suppressed,
31745 no exception is raised and execution
31746 will become erroneous.
31747
31748 @node Using 64 bit storage pools by default
31749 @subsubsection Using 64-bit storage pools by default
31750
31751 @noindent
31752 In some cases it may be desirable to have the compiler allocate
31753 from 64-bit storage pools by default. This may be the case for
31754 libraries that are 64-bit clean, but may be used in both 32-bit
31755 and 64-bit contexts. For these cases the following configuration
31756 pragma may be specified:
31757
31758 @smallexample @c ada
31759   pragma Pool_64_Default;
31760 @end smallexample
31761
31762 @noindent
31763 Any code compiled in the context of this pragma will by default
31764 use the @code{System.Pool_64} storage pool. This default may be overridden
31765 for a specific access type @code{T} by the representation clause:
31766
31767 @smallexample @c ada
31768    for T'Storage_Pool use System.Pool_32;
31769 @end smallexample
31770
31771 @noindent
31772 Any object whose address may be passed to a subprogram with a
31773 @code{Short_Address} argument, or assigned to a variable of type
31774 @code{Short_Address}, needs to be allocated from this pool.
31775
31776 @node General access types
31777 @subsubsection General access types
31778
31779 @noindent
31780 Objects designated by access values from a
31781 general access type (declared with @code{access all}) are never allocated
31782 from a 64-bit storage pool. Code that uses general access types will
31783 accept objects allocated in either 32-bit or 64-bit address spaces,
31784 but never allocate objects outside the 32-bit address space.
31785 Using general access types ensures maximum compatibility with both
31786 32-bit and 64-bit code.
31787
31788 @node STARLET and other predefined libraries
31789 @subsubsection STARLET and other predefined libraries
31790
31791 @noindent
31792 All code that comes as part of GNAT is 64-bit clean, but the
31793 restrictions given in @ref{Restrictions on use of 64 bit objects},
31794 still apply. Look at the package
31795 specs to see in which contexts objects allocated
31796 in 64-bit address space are acceptable.
31797
31798 @node Technical details
31799 @subsection Technical details
31800
31801 @noindent
31802 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
31803 Ada standard with respect to the type of @code{System.Address}. Previous
31804 versions of GNAT Pro have defined this type as private and implemented it as a
31805 modular type.
31806
31807 In order to allow defining @code{System.Short_Address} as a proper subtype,
31808 and to match the implicit sign extension in parameter passing,
31809 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
31810 visible (i.e., non-private) integer type.
31811 Standard operations on the type, such as the binary operators ``+'', ``-'',
31812 etc., that take @code{Address} operands and return an @code{Address} result,
31813 have been hidden by declaring these
31814 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
31815 ambiguities that would otherwise result from overloading.
31816 (Note that, although @code{Address} is a visible integer type,
31817 good programming practice dictates against exploiting the type's
31818 integer properties such as literals, since this will compromise
31819 code portability.)
31820
31821 Defining @code{Address} as a visible integer type helps achieve
31822 maximum compatibility for existing Ada code,
31823 without sacrificing the capabilities of the 64-bit architecture.
31824 @end ifset
31825
31826 @c ************************************************
31827 @ifset unw
31828 @node Microsoft Windows Topics
31829 @appendix Microsoft Windows Topics
31830 @cindex Windows NT
31831 @cindex Windows 95
31832 @cindex Windows 98
31833
31834 @noindent
31835 This chapter describes topics that are specific to the Microsoft Windows
31836 platforms (NT, 2000, and XP Professional).
31837
31838 @menu
31839 * Using GNAT on Windows::
31840 * Using a network installation of GNAT::
31841 * CONSOLE and WINDOWS subsystems::
31842 * Temporary Files::
31843 * Mixed-Language Programming on Windows::
31844 * Windows Calling Conventions::
31845 * Introduction to Dynamic Link Libraries (DLLs)::
31846 * Using DLLs with GNAT::
31847 * Building DLLs with GNAT::
31848 * Building DLLs with GNAT Project files::
31849 * Building DLLs with gnatdll::
31850 * GNAT and Windows Resources::
31851 * Debugging a DLL::
31852 * Setting Stack Size from gnatlink::
31853 * Setting Heap Size from gnatlink::
31854 @end menu
31855
31856 @node Using GNAT on Windows
31857 @section Using GNAT on Windows
31858
31859 @noindent
31860 One of the strengths of the GNAT technology is that its tool set
31861 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
31862 @code{gdb} debugger, etc.) is used in the same way regardless of the
31863 platform.
31864
31865 On Windows this tool set is complemented by a number of Microsoft-specific
31866 tools that have been provided to facilitate interoperability with Windows
31867 when this is required. With these tools:
31868
31869 @itemize @bullet
31870
31871 @item
31872 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
31873 subsystems.
31874
31875 @item
31876 You can use any Dynamically Linked Library (DLL) in your Ada code (both
31877 relocatable and non-relocatable DLLs are supported).
31878
31879 @item
31880 You can build Ada DLLs for use in other applications. These applications
31881 can be written in a language other than Ada (e.g., C, C++, etc). Again both
31882 relocatable and non-relocatable Ada DLLs are supported.
31883
31884 @item
31885 You can include Windows resources in your Ada application.
31886
31887 @item
31888 You can use or create COM/DCOM objects.
31889 @end itemize
31890
31891 @noindent
31892 Immediately below are listed all known general GNAT-for-Windows restrictions.
31893 Other restrictions about specific features like Windows Resources and DLLs
31894 are listed in separate sections below.
31895
31896 @itemize @bullet
31897
31898 @item
31899 It is not possible to use @code{GetLastError} and @code{SetLastError}
31900 when tasking, protected records, or exceptions are used. In these
31901 cases, in order to implement Ada semantics, the GNAT run-time system
31902 calls certain Win32 routines that set the last error variable to 0 upon
31903 success. It should be possible to use @code{GetLastError} and
31904 @code{SetLastError} when tasking, protected record, and exception
31905 features are not used, but it is not guaranteed to work.
31906
31907 @item
31908 It is not possible to link against Microsoft libraries except for
31909 import libraries. The library must be built to be compatible with
31910 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
31911 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
31912 not be compatible with the GNAT runtime. Even if the library is
31913 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
31914
31915 @item
31916 When the compilation environment is located on FAT32 drives, users may
31917 experience recompilations of the source files that have not changed if
31918 Daylight Saving Time (DST) state has changed since the last time files
31919 were compiled. NTFS drives do not have this problem.
31920
31921 @item
31922 No components of the GNAT toolset use any entries in the Windows
31923 registry. The only entries that can be created are file associations and
31924 PATH settings, provided the user has chosen to create them at installation
31925 time, as well as some minimal book-keeping information needed to correctly
31926 uninstall or integrate different GNAT products.
31927 @end itemize
31928
31929 @node Using a network installation of GNAT
31930 @section Using a network installation of GNAT
31931
31932 @noindent
31933 Make sure the system on which GNAT is installed is accessible from the
31934 current machine, i.e., the install location is shared over the network.
31935 Shared resources are accessed on Windows by means of UNC paths, which
31936 have the format @code{\\server\sharename\path}
31937
31938 In order to use such a network installation, simply add the UNC path of the
31939 @file{bin} directory of your GNAT installation in front of your PATH. For
31940 example, if GNAT is installed in @file{\GNAT} directory of a share location
31941 called @file{c-drive} on a machine @file{LOKI}, the following command will
31942 make it available:
31943
31944 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
31945
31946 Be aware that every compilation using the network installation results in the
31947 transfer of large amounts of data across the network and will likely cause
31948 serious performance penalty.
31949
31950 @node CONSOLE and WINDOWS subsystems
31951 @section CONSOLE and WINDOWS subsystems
31952 @cindex CONSOLE Subsystem
31953 @cindex WINDOWS Subsystem
31954 @cindex -mwindows
31955
31956 @noindent
31957 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
31958 (which is the default subsystem) will always create a console when
31959 launching the application. This is not something desirable when the
31960 application has a Windows GUI. To get rid of this console the
31961 application must be using the @code{WINDOWS} subsystem. To do so
31962 the @option{-mwindows} linker option must be specified.
31963
31964 @smallexample
31965 $ gnatmake winprog -largs -mwindows
31966 @end smallexample
31967
31968 @node Temporary Files
31969 @section Temporary Files
31970 @cindex Temporary files
31971
31972 @noindent
31973 It is possible to control where temporary files gets created by setting
31974 the @env{TMP} environment variable. The file will be created:
31975
31976 @itemize
31977 @item Under the directory pointed to by the @env{TMP} environment variable if
31978 this directory exists.
31979
31980 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
31981 set (or not pointing to a directory) and if this directory exists.
31982
31983 @item Under the current working directory otherwise.
31984 @end itemize
31985
31986 @noindent
31987 This allows you to determine exactly where the temporary
31988 file will be created. This is particularly useful in networked
31989 environments where you may not have write access to some
31990 directories.
31991
31992 @node Mixed-Language Programming on Windows
31993 @section Mixed-Language Programming on Windows
31994
31995 @noindent
31996 Developing pure Ada applications on Windows is no different than on
31997 other GNAT-supported platforms. However, when developing or porting an
31998 application that contains a mix of Ada and C/C++, the choice of your
31999 Windows C/C++ development environment conditions your overall
32000 interoperability strategy.
32001
32002 If you use @command{gcc} to compile the non-Ada part of your application,
32003 there are no Windows-specific restrictions that affect the overall
32004 interoperability with your Ada code. If you plan to use
32005 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
32006 the following limitations:
32007
32008 @itemize @bullet
32009 @item
32010 You cannot link your Ada code with an object or library generated with
32011 Microsoft tools if these use the @code{.tls} section (Thread Local
32012 Storage section) since the GNAT linker does not yet support this section.
32013
32014 @item
32015 You cannot link your Ada code with an object or library generated with
32016 Microsoft tools if these use I/O routines other than those provided in
32017 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
32018 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
32019 libraries can cause a conflict with @code{msvcrt.dll} services. For
32020 instance Visual C++ I/O stream routines conflict with those in
32021 @code{msvcrt.dll}.
32022 @end itemize
32023
32024 @noindent
32025 If you do want to use the Microsoft tools for your non-Ada code and hit one
32026 of the above limitations, you have two choices:
32027
32028 @enumerate
32029 @item
32030 Encapsulate your non-Ada code in a DLL to be linked with your Ada
32031 application. In this case, use the Microsoft or whatever environment to
32032 build the DLL and use GNAT to build your executable
32033 (@pxref{Using DLLs with GNAT}).
32034
32035 @item
32036 Or you can encapsulate your Ada code in a DLL to be linked with the
32037 other part of your application. In this case, use GNAT to build the DLL
32038 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
32039 environment to build your executable.
32040 @end enumerate
32041
32042 @node Windows Calling Conventions
32043 @section Windows Calling Conventions
32044 @findex Stdcall
32045 @findex APIENTRY
32046
32047 @menu
32048 * C Calling Convention::
32049 * Stdcall Calling Convention::
32050 * Win32 Calling Convention::
32051 * DLL Calling Convention::
32052 @end menu
32053
32054 @noindent
32055 When a subprogram @code{F} (caller) calls a subprogram @code{G}
32056 (callee), there are several ways to push @code{G}'s parameters on the
32057 stack and there are several possible scenarios to clean up the stack
32058 upon @code{G}'s return. A calling convention is an agreed upon software
32059 protocol whereby the responsibilities between the caller (@code{F}) and
32060 the callee (@code{G}) are clearly defined. Several calling conventions
32061 are available for Windows:
32062
32063 @itemize @bullet
32064 @item
32065 @code{C} (Microsoft defined)
32066
32067 @item
32068 @code{Stdcall} (Microsoft defined)
32069
32070 @item
32071 @code{Win32} (GNAT specific)
32072
32073 @item
32074 @code{DLL} (GNAT specific)
32075 @end itemize
32076
32077 @node C Calling Convention
32078 @subsection @code{C} Calling Convention
32079
32080 @noindent
32081 This is the default calling convention used when interfacing to C/C++
32082 routines compiled with either @command{gcc} or Microsoft Visual C++.
32083
32084 In the @code{C} calling convention subprogram parameters are pushed on the
32085 stack by the caller from right to left. The caller itself is in charge of
32086 cleaning up the stack after the call. In addition, the name of a routine
32087 with @code{C} calling convention is mangled by adding a leading underscore.
32088
32089 The name to use on the Ada side when importing (or exporting) a routine
32090 with @code{C} calling convention is the name of the routine. For
32091 instance the C function:
32092
32093 @smallexample
32094 int get_val (long);
32095 @end smallexample
32096
32097 @noindent
32098 should be imported from Ada as follows:
32099
32100 @smallexample @c ada
32101 @group
32102 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32103 pragma Import (C, Get_Val, External_Name => "get_val");
32104 @end group
32105 @end smallexample
32106
32107 @noindent
32108 Note that in this particular case the @code{External_Name} parameter could
32109 have been omitted since, when missing, this parameter is taken to be the
32110 name of the Ada entity in lower case. When the @code{Link_Name} parameter
32111 is missing, as in the above example, this parameter is set to be the
32112 @code{External_Name} with a leading underscore.
32113
32114 When importing a variable defined in C, you should always use the @code{C}
32115 calling convention unless the object containing the variable is part of a
32116 DLL (in which case you should use the @code{Stdcall} calling
32117 convention, @pxref{Stdcall Calling Convention}).
32118
32119 @node Stdcall Calling Convention
32120 @subsection @code{Stdcall} Calling Convention
32121
32122 @noindent
32123 This convention, which was the calling convention used for Pascal
32124 programs, is used by Microsoft for all the routines in the Win32 API for
32125 efficiency reasons. It must be used to import any routine for which this
32126 convention was specified.
32127
32128 In the @code{Stdcall} calling convention subprogram parameters are pushed
32129 on the stack by the caller from right to left. The callee (and not the
32130 caller) is in charge of cleaning the stack on routine exit. In addition,
32131 the name of a routine with @code{Stdcall} calling convention is mangled by
32132 adding a leading underscore (as for the @code{C} calling convention) and a
32133 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
32134 bytes) of the parameters passed to the routine.
32135
32136 The name to use on the Ada side when importing a C routine with a
32137 @code{Stdcall} calling convention is the name of the C routine. The leading
32138 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
32139 the compiler. For instance the Win32 function:
32140
32141 @smallexample
32142 @b{APIENTRY} int get_val (long);
32143 @end smallexample
32144
32145 @noindent
32146 should be imported from Ada as follows:
32147
32148 @smallexample @c ada
32149 @group
32150 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32151 pragma Import (Stdcall, Get_Val);
32152 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
32153 @end group
32154 @end smallexample
32155
32156 @noindent
32157 As for the @code{C} calling convention, when the @code{External_Name}
32158 parameter is missing, it is taken to be the name of the Ada entity in lower
32159 case. If instead of writing the above import pragma you write:
32160
32161 @smallexample @c ada
32162 @group
32163 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32164 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
32165 @end group
32166 @end smallexample
32167
32168 @noindent
32169 then the imported routine is @code{_retrieve_val@@4}. However, if instead
32170 of specifying the @code{External_Name} parameter you specify the
32171 @code{Link_Name} as in the following example:
32172
32173 @smallexample @c ada
32174 @group
32175 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32176 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
32177 @end group
32178 @end smallexample
32179
32180 @noindent
32181 then the imported routine is @code{retrieve_val}, that is, there is no
32182 decoration at all. No leading underscore and no Stdcall suffix
32183 @code{@@}@code{@var{nn}}.
32184
32185 @noindent
32186 This is especially important as in some special cases a DLL's entry
32187 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
32188 name generated for a call has it.
32189
32190 @noindent
32191 It is also possible to import variables defined in a DLL by using an
32192 import pragma for a variable. As an example, if a DLL contains a
32193 variable defined as:
32194
32195 @smallexample
32196 int my_var;
32197 @end smallexample
32198
32199 @noindent
32200 then, to access this variable from Ada you should write:
32201
32202 @smallexample @c ada
32203 @group
32204 My_Var : Interfaces.C.int;
32205 pragma Import (Stdcall, My_Var);
32206 @end group
32207 @end smallexample
32208
32209 @noindent
32210 Note that to ease building cross-platform bindings this convention
32211 will be handled as a @code{C} calling convention on non-Windows platforms.
32212
32213 @node Win32 Calling Convention
32214 @subsection @code{Win32} Calling Convention
32215
32216 @noindent
32217 This convention, which is GNAT-specific is fully equivalent to the
32218 @code{Stdcall} calling convention described above.
32219
32220 @node DLL Calling Convention
32221 @subsection @code{DLL} Calling Convention
32222
32223 @noindent
32224 This convention, which is GNAT-specific is fully equivalent to the
32225 @code{Stdcall} calling convention described above.
32226
32227 @node Introduction to Dynamic Link Libraries (DLLs)
32228 @section Introduction to Dynamic Link Libraries (DLLs)
32229 @findex DLL
32230
32231 @noindent
32232 A Dynamically Linked Library (DLL) is a library that can be shared by
32233 several applications running under Windows. A DLL can contain any number of
32234 routines and variables.
32235
32236 One advantage of DLLs is that you can change and enhance them without
32237 forcing all the applications that depend on them to be relinked or
32238 recompiled. However, you should be aware than all calls to DLL routines are
32239 slower since, as you will understand below, such calls are indirect.
32240
32241 To illustrate the remainder of this section, suppose that an application
32242 wants to use the services of a DLL @file{API.dll}. To use the services
32243 provided by @file{API.dll} you must statically link against the DLL or
32244 an import library which contains a jump table with an entry for each
32245 routine and variable exported by the DLL. In the Microsoft world this
32246 import library is called @file{API.lib}. When using GNAT this import
32247 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
32248 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
32249
32250 After you have linked your application with the DLL or the import library
32251 and you run your application, here is what happens:
32252
32253 @enumerate
32254 @item
32255 Your application is loaded into memory.
32256
32257 @item
32258 The DLL @file{API.dll} is mapped into the address space of your
32259 application. This means that:
32260
32261 @itemize @bullet
32262 @item
32263 The DLL will use the stack of the calling thread.
32264
32265 @item
32266 The DLL will use the virtual address space of the calling process.
32267
32268 @item
32269 The DLL will allocate memory from the virtual address space of the calling
32270 process.
32271
32272 @item
32273 Handles (pointers) can be safely exchanged between routines in the DLL
32274 routines and routines in the application using the DLL.
32275 @end itemize
32276
32277 @item
32278 The entries in the jump table (from the import library @file{libAPI.dll.a}
32279 or @file{API.lib} or automatically created when linking against a DLL)
32280 which is part of your application are initialized with the addresses
32281 of the routines and variables in @file{API.dll}.
32282
32283 @item
32284 If present in @file{API.dll}, routines @code{DllMain} or
32285 @code{DllMainCRTStartup} are invoked. These routines typically contain
32286 the initialization code needed for the well-being of the routines and
32287 variables exported by the DLL.
32288 @end enumerate
32289
32290 @noindent
32291 There is an additional point which is worth mentioning. In the Windows
32292 world there are two kind of DLLs: relocatable and non-relocatable
32293 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
32294 in the target application address space. If the addresses of two
32295 non-relocatable DLLs overlap and these happen to be used by the same
32296 application, a conflict will occur and the application will run
32297 incorrectly. Hence, when possible, it is always preferable to use and
32298 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
32299 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
32300 User's Guide) removes the debugging symbols from the DLL but the DLL can
32301 still be relocated.
32302
32303 As a side note, an interesting difference between Microsoft DLLs and
32304 Unix shared libraries, is the fact that on most Unix systems all public
32305 routines are exported by default in a Unix shared library, while under
32306 Windows it is possible (but not required) to list exported routines in
32307 a definition file (@pxref{The Definition File}).
32308
32309 @node Using DLLs with GNAT
32310 @section Using DLLs with GNAT
32311
32312 @menu
32313 * Creating an Ada Spec for the DLL Services::
32314 * Creating an Import Library::
32315 @end menu
32316
32317 @noindent
32318 To use the services of a DLL, say @file{API.dll}, in your Ada application
32319 you must have:
32320
32321 @enumerate
32322 @item
32323 The Ada spec for the routines and/or variables you want to access in
32324 @file{API.dll}. If not available this Ada spec must be built from the C/C++
32325 header files provided with the DLL.
32326
32327 @item
32328 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
32329 mentioned an import library is a statically linked library containing the
32330 import table which will be filled at load time to point to the actual
32331 @file{API.dll} routines. Sometimes you don't have an import library for the
32332 DLL you want to use. The following sections will explain how to build
32333 one. Note that this is optional.
32334
32335 @item
32336 The actual DLL, @file{API.dll}.
32337 @end enumerate
32338
32339 @noindent
32340 Once you have all the above, to compile an Ada application that uses the
32341 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
32342 you simply issue the command
32343
32344 @smallexample
32345 $ gnatmake my_ada_app -largs -lAPI
32346 @end smallexample
32347
32348 @noindent
32349 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
32350 tells the GNAT linker to look first for a library named @file{API.lib}
32351 (Microsoft-style name) and if not found for a libraries named
32352 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
32353 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
32354 contains the following pragma
32355
32356 @smallexample @c ada
32357 pragma Linker_Options ("-lAPI");
32358 @end smallexample
32359
32360 @noindent
32361 you do not have to add @option{-largs -lAPI} at the end of the
32362 @command{gnatmake} command.
32363
32364 If any one of the items above is missing you will have to create it
32365 yourself. The following sections explain how to do so using as an
32366 example a fictitious DLL called @file{API.dll}.
32367
32368 @node Creating an Ada Spec for the DLL Services
32369 @subsection Creating an Ada Spec for the DLL Services
32370
32371 @noindent
32372 A DLL typically comes with a C/C++ header file which provides the
32373 definitions of the routines and variables exported by the DLL. The Ada
32374 equivalent of this header file is a package spec that contains definitions
32375 for the imported entities. If the DLL you intend to use does not come with
32376 an Ada spec you have to generate one such spec yourself. For example if
32377 the header file of @file{API.dll} is a file @file{api.h} containing the
32378 following two definitions:
32379
32380 @smallexample
32381 @group
32382 @cartouche
32383 int some_var;
32384 int get (char *);
32385 @end cartouche
32386 @end group
32387 @end smallexample
32388
32389 @noindent
32390 then the equivalent Ada spec could be:
32391
32392 @smallexample @c ada
32393 @group
32394 @cartouche
32395 with Interfaces.C.Strings;
32396 package API is
32397    use Interfaces;
32398
32399    Some_Var : C.int;
32400    function Get (Str : C.Strings.Chars_Ptr) return C.int;
32401
32402 private
32403    pragma Import (C, Get);
32404    pragma Import (DLL, Some_Var);
32405 end API;
32406 @end cartouche
32407 @end group
32408 @end smallexample
32409
32410 @noindent
32411 Note that a variable is
32412 @strong{always imported with a Stdcall convention}. A function
32413 can have @code{C} or @code{Stdcall} convention.
32414 (@pxref{Windows Calling Conventions}).
32415
32416 @node Creating an Import Library
32417 @subsection Creating an Import Library
32418 @cindex Import library
32419
32420 @menu
32421 * The Definition File::
32422 * GNAT-Style Import Library::
32423 * Microsoft-Style Import Library::
32424 @end menu
32425
32426 @noindent
32427 If a Microsoft-style import library @file{API.lib} or a GNAT-style
32428 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
32429 with @file{API.dll} you can skip this section. You can also skip this
32430 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
32431 as in this case it is possible to link directly against the
32432 DLL. Otherwise read on.
32433
32434 @node The Definition File
32435 @subsubsection The Definition File
32436 @cindex Definition file
32437 @findex .def
32438
32439 @noindent
32440 As previously mentioned, and unlike Unix systems, the list of symbols
32441 that are exported from a DLL must be provided explicitly in Windows.
32442 The main goal of a definition file is precisely that: list the symbols
32443 exported by a DLL. A definition file (usually a file with a @code{.def}
32444 suffix) has the following structure:
32445
32446 @smallexample
32447 @group
32448 @cartouche
32449 @r{[}LIBRARY @var{name}@r{]}
32450 @r{[}DESCRIPTION @var{string}@r{]}
32451 EXPORTS
32452    @var{symbol1}
32453    @var{symbol2}
32454    @dots{}
32455 @end cartouche
32456 @end group
32457 @end smallexample
32458
32459 @table @code
32460 @item LIBRARY @var{name}
32461 This section, which is optional, gives the name of the DLL.
32462
32463 @item DESCRIPTION @var{string}
32464 This section, which is optional, gives a description string that will be
32465 embedded in the import library.
32466
32467 @item EXPORTS
32468 This section gives the list of exported symbols (procedures, functions or
32469 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
32470 section of @file{API.def} looks like:
32471
32472 @smallexample
32473 @group
32474 @cartouche
32475 EXPORTS
32476    some_var
32477    get
32478 @end cartouche
32479 @end group
32480 @end smallexample
32481 @end table
32482
32483 @noindent
32484 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
32485 (@pxref{Windows Calling Conventions}) for a Stdcall
32486 calling convention function in the exported symbols list.
32487
32488 @noindent
32489 There can actually be other sections in a definition file, but these
32490 sections are not relevant to the discussion at hand.
32491
32492 @node GNAT-Style Import Library
32493 @subsubsection GNAT-Style Import Library
32494
32495 @noindent
32496 To create a static import library from @file{API.dll} with the GNAT tools
32497 you should proceed as follows:
32498
32499 @enumerate
32500 @item
32501 Create the definition file @file{API.def} (@pxref{The Definition File}).
32502 For that use the @code{dll2def} tool as follows:
32503
32504 @smallexample
32505 $ dll2def API.dll > API.def
32506 @end smallexample
32507
32508 @noindent
32509 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
32510 to standard output the list of entry points in the DLL. Note that if
32511 some routines in the DLL have the @code{Stdcall} convention
32512 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
32513 suffix then you'll have to edit @file{api.def} to add it, and specify
32514 @option{-k} to @command{gnatdll} when creating the import library.
32515
32516 @noindent
32517 Here are some hints to find the right @code{@@}@var{nn} suffix.
32518
32519 @enumerate
32520 @item
32521 If you have the Microsoft import library (.lib), it is possible to get
32522 the right symbols by using Microsoft @code{dumpbin} tool (see the
32523 corresponding Microsoft documentation for further details).
32524
32525 @smallexample
32526 $ dumpbin /exports api.lib
32527 @end smallexample
32528
32529 @item
32530 If you have a message about a missing symbol at link time the compiler
32531 tells you what symbol is expected. You just have to go back to the
32532 definition file and add the right suffix.
32533 @end enumerate
32534
32535 @item
32536 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
32537 (@pxref{Using gnatdll}) as follows:
32538
32539 @smallexample
32540 $ gnatdll -e API.def -d API.dll
32541 @end smallexample
32542
32543 @noindent
32544 @code{gnatdll} takes as input a definition file @file{API.def} and the
32545 name of the DLL containing the services listed in the definition file
32546 @file{API.dll}. The name of the static import library generated is
32547 computed from the name of the definition file as follows: if the
32548 definition file name is @var{xyz}@code{.def}, the import library name will
32549 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
32550 @option{-e} could have been removed because the name of the definition
32551 file (before the ``@code{.def}'' suffix) is the same as the name of the
32552 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
32553 @end enumerate
32554
32555 @node Microsoft-Style Import Library
32556 @subsubsection Microsoft-Style Import Library
32557
32558 @noindent
32559 With GNAT you can either use a GNAT-style or Microsoft-style import
32560 library. A Microsoft import library is needed only if you plan to make an
32561 Ada DLL available to applications developed with Microsoft
32562 tools (@pxref{Mixed-Language Programming on Windows}).
32563
32564 To create a Microsoft-style import library for @file{API.dll} you
32565 should proceed as follows:
32566
32567 @enumerate
32568 @item
32569 Create the definition file @file{API.def} from the DLL. For this use either
32570 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
32571 tool (see the corresponding Microsoft documentation for further details).
32572
32573 @item
32574 Build the actual import library using Microsoft's @code{lib} utility:
32575
32576 @smallexample
32577 $ lib -machine:IX86 -def:API.def -out:API.lib
32578 @end smallexample
32579
32580 @noindent
32581 If you use the above command the definition file @file{API.def} must
32582 contain a line giving the name of the DLL:
32583
32584 @smallexample
32585 LIBRARY      "API"
32586 @end smallexample
32587
32588 @noindent
32589 See the Microsoft documentation for further details about the usage of
32590 @code{lib}.
32591 @end enumerate
32592
32593 @node Building DLLs with GNAT
32594 @section Building DLLs with GNAT
32595 @cindex DLLs, building
32596
32597 @noindent
32598 This section explain how to build DLLs using the GNAT built-in DLL
32599 support. With the following procedure it is straight forward to build
32600 and use DLLs with GNAT.
32601
32602 @enumerate
32603
32604 @item building object files
32605
32606 The first step is to build all objects files that are to be included
32607 into the DLL. This is done by using the standard @command{gnatmake} tool.
32608
32609 @item building the DLL
32610
32611 To build the DLL you must use @command{gcc}'s @option{-shared}
32612 option. It is quite simple to use this method:
32613
32614 @smallexample
32615 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
32616 @end smallexample
32617
32618 It is important to note that in this case all symbols found in the
32619 object files are automatically exported. It is possible to restrict
32620 the set of symbols to export by passing to @command{gcc} a definition
32621 file, @pxref{The Definition File}. For example:
32622
32623 @smallexample
32624 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
32625 @end smallexample
32626
32627 If you use a definition file you must export the elaboration procedures
32628 for every package that required one. Elaboration procedures are named
32629 using the package name followed by "_E".
32630
32631 @item preparing DLL to be used
32632
32633 For the DLL to be used by client programs the bodies must be hidden
32634 from it and the .ali set with read-only attribute. This is very important
32635 otherwise GNAT will recompile all packages and will not actually use
32636 the code in the DLL. For example:
32637
32638 @smallexample
32639 $ mkdir apilib
32640 $ copy *.ads *.ali api.dll apilib
32641 $ attrib +R apilib\*.ali
32642 @end smallexample
32643
32644 @end enumerate
32645
32646 At this point it is possible to use the DLL by directly linking
32647 against it. Note that you must use the GNAT shared runtime when using
32648 GNAT shared libraries. This is achieved by using @option{-shared} binder's
32649 option.
32650
32651 @smallexample
32652 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
32653 @end smallexample
32654
32655 @node Building DLLs with GNAT Project files
32656 @section Building DLLs with GNAT Project files
32657 @cindex DLLs, building
32658
32659 @noindent
32660 There is nothing specific to Windows in the build process.
32661 @pxref{Library Projects}.
32662
32663 @noindent
32664 Due to a system limitation, it is not possible under Windows to create threads
32665 when inside the @code{DllMain} routine which is used for auto-initialization
32666 of shared libraries, so it is not possible to have library level tasks in SALs.
32667
32668 @node Building DLLs with gnatdll
32669 @section Building DLLs with gnatdll
32670 @cindex DLLs, building
32671
32672 @menu
32673 * Limitations When Using Ada DLLs from Ada::
32674 * Exporting Ada Entities::
32675 * Ada DLLs and Elaboration::
32676 * Ada DLLs and Finalization::
32677 * Creating a Spec for Ada DLLs::
32678 * Creating the Definition File::
32679 * Using gnatdll::
32680 @end menu
32681
32682 @noindent
32683 Note that it is preferred to use the built-in GNAT DLL support
32684 (@pxref{Building DLLs with GNAT}) or GNAT Project files
32685 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
32686
32687 This section explains how to build DLLs containing Ada code using
32688 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
32689 remainder of this section.
32690
32691 The steps required to build an Ada DLL that is to be used by Ada as well as
32692 non-Ada applications are as follows:
32693
32694 @enumerate
32695 @item
32696 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
32697 @code{Stdcall} calling convention to avoid any Ada name mangling for the
32698 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
32699 skip this step if you plan to use the Ada DLL only from Ada applications.
32700
32701 @item
32702 Your Ada code must export an initialization routine which calls the routine
32703 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
32704 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
32705 routine exported by the Ada DLL must be invoked by the clients of the DLL
32706 to initialize the DLL.
32707
32708 @item
32709 When useful, the DLL should also export a finalization routine which calls
32710 routine @code{adafinal} generated by @command{gnatbind} to perform the
32711 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
32712 The finalization routine exported by the Ada DLL must be invoked by the
32713 clients of the DLL when the DLL services are no further needed.
32714
32715 @item
32716 You must provide a spec for the services exported by the Ada DLL in each
32717 of the programming languages to which you plan to make the DLL available.
32718
32719 @item
32720 You must provide a definition file listing the exported entities
32721 (@pxref{The Definition File}).
32722
32723 @item
32724 Finally you must use @code{gnatdll} to produce the DLL and the import
32725 library (@pxref{Using gnatdll}).
32726 @end enumerate
32727
32728 @noindent
32729 Note that a relocatable DLL stripped using the @code{strip}
32730 binutils tool will not be relocatable anymore. To build a DLL without
32731 debug information pass @code{-largs -s} to @code{gnatdll}. This
32732 restriction does not apply to a DLL built using a Library Project.
32733 @pxref{Library Projects}.
32734
32735 @node Limitations When Using Ada DLLs from Ada
32736 @subsection Limitations When Using Ada DLLs from Ada
32737
32738 @noindent
32739 When using Ada DLLs from Ada applications there is a limitation users
32740 should be aware of. Because on Windows the GNAT run time is not in a DLL of
32741 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
32742 each Ada DLL includes the services of the GNAT run time that are necessary
32743 to the Ada code inside the DLL. As a result, when an Ada program uses an
32744 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
32745 one in the main program.
32746
32747 It is therefore not possible to exchange GNAT run-time objects between the
32748 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
32749 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
32750 types, etc.
32751
32752 It is completely safe to exchange plain elementary, array or record types,
32753 Windows object handles, etc.
32754
32755 @node Exporting Ada Entities
32756 @subsection Exporting Ada Entities
32757 @cindex Export table
32758
32759 @noindent
32760 Building a DLL is a way to encapsulate a set of services usable from any
32761 application. As a result, the Ada entities exported by a DLL should be
32762 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
32763 any Ada name mangling. As an example here is an Ada package
32764 @code{API}, spec and body, exporting two procedures, a function, and a
32765 variable:
32766
32767 @smallexample @c ada
32768 @group
32769 @cartouche
32770 with Interfaces.C; use Interfaces;
32771 package API is
32772    Count : C.int := 0;
32773    function Factorial (Val : C.int) return C.int;
32774
32775    procedure Initialize_API;
32776    procedure Finalize_API;
32777    --  Initialization & Finalization routines. More in the next section.
32778 private
32779    pragma Export (C, Initialize_API);
32780    pragma Export (C, Finalize_API);
32781    pragma Export (C, Count);
32782    pragma Export (C, Factorial);
32783 end API;
32784 @end cartouche
32785 @end group
32786 @end smallexample
32787
32788 @smallexample @c ada
32789 @group
32790 @cartouche
32791 package body API is
32792    function Factorial (Val : C.int) return C.int is
32793       Fact : C.int := 1;
32794    begin
32795       Count := Count + 1;
32796       for K in 1 .. Val loop
32797          Fact := Fact * K;
32798       end loop;
32799       return Fact;
32800    end Factorial;
32801
32802    procedure Initialize_API is
32803       procedure Adainit;
32804       pragma Import (C, Adainit);
32805    begin
32806       Adainit;
32807    end Initialize_API;
32808
32809    procedure Finalize_API is
32810       procedure Adafinal;
32811       pragma Import (C, Adafinal);
32812    begin
32813       Adafinal;
32814    end Finalize_API;
32815 end API;
32816 @end cartouche
32817 @end group
32818 @end smallexample
32819
32820 @noindent
32821 If the Ada DLL you are building will only be used by Ada applications
32822 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
32823 convention. As an example, the previous package could be written as
32824 follows:
32825
32826 @smallexample @c ada
32827 @group
32828 @cartouche
32829 package API is
32830    Count : Integer := 0;
32831    function Factorial (Val : Integer) return Integer;
32832
32833    procedure Initialize_API;
32834    procedure Finalize_API;
32835    --  Initialization and Finalization routines.
32836 end API;
32837 @end cartouche
32838 @end group
32839 @end smallexample
32840
32841 @smallexample @c ada
32842 @group
32843 @cartouche
32844 package body API is
32845    function Factorial (Val : Integer) return Integer is
32846       Fact : Integer := 1;
32847    begin
32848       Count := Count + 1;
32849       for K in 1 .. Val loop
32850          Fact := Fact * K;
32851       end loop;
32852       return Fact;
32853    end Factorial;
32854
32855    @dots{}
32856    --  The remainder of this package body is unchanged.
32857 end API;
32858 @end cartouche
32859 @end group
32860 @end smallexample
32861
32862 @noindent
32863 Note that if you do not export the Ada entities with a @code{C} or
32864 @code{Stdcall} convention you will have to provide the mangled Ada names
32865 in the definition file of the Ada DLL
32866 (@pxref{Creating the Definition File}).
32867
32868 @node Ada DLLs and Elaboration
32869 @subsection Ada DLLs and Elaboration
32870 @cindex DLLs and elaboration
32871
32872 @noindent
32873 The DLL that you are building contains your Ada code as well as all the
32874 routines in the Ada library that are needed by it. The first thing a
32875 user of your DLL must do is elaborate the Ada code
32876 (@pxref{Elaboration Order Handling in GNAT}).
32877
32878 To achieve this you must export an initialization routine
32879 (@code{Initialize_API} in the previous example), which must be invoked
32880 before using any of the DLL services. This elaboration routine must call
32881 the Ada elaboration routine @code{adainit} generated by the GNAT binder
32882 (@pxref{Binding with Non-Ada Main Programs}). See the body of
32883 @code{Initialize_Api} for an example. Note that the GNAT binder is
32884 automatically invoked during the DLL build process by the @code{gnatdll}
32885 tool (@pxref{Using gnatdll}).
32886
32887 When a DLL is loaded, Windows systematically invokes a routine called
32888 @code{DllMain}. It would therefore be possible to call @code{adainit}
32889 directly from @code{DllMain} without having to provide an explicit
32890 initialization routine. Unfortunately, it is not possible to call
32891 @code{adainit} from the @code{DllMain} if your program has library level
32892 tasks because access to the @code{DllMain} entry point is serialized by
32893 the system (that is, only a single thread can execute ``through'' it at a
32894 time), which means that the GNAT run time will deadlock waiting for the
32895 newly created task to complete its initialization.
32896
32897 @node Ada DLLs and Finalization
32898 @subsection Ada DLLs and Finalization
32899 @cindex DLLs and finalization
32900
32901 @noindent
32902 When the services of an Ada DLL are no longer needed, the client code should
32903 invoke the DLL finalization routine, if available. The DLL finalization
32904 routine is in charge of releasing all resources acquired by the DLL. In the
32905 case of the Ada code contained in the DLL, this is achieved by calling
32906 routine @code{adafinal} generated by the GNAT binder
32907 (@pxref{Binding with Non-Ada Main Programs}).
32908 See the body of @code{Finalize_Api} for an
32909 example. As already pointed out the GNAT binder is automatically invoked
32910 during the DLL build process by the @code{gnatdll} tool
32911 (@pxref{Using gnatdll}).
32912
32913 @node Creating a Spec for Ada DLLs
32914 @subsection Creating a Spec for Ada DLLs
32915
32916 @noindent
32917 To use the services exported by the Ada DLL from another programming
32918 language (e.g.@: C), you have to translate the specs of the exported Ada
32919 entities in that language. For instance in the case of @code{API.dll},
32920 the corresponding C header file could look like:
32921
32922 @smallexample
32923 @group
32924 @cartouche
32925 extern int *_imp__count;
32926 #define count (*_imp__count)
32927 int factorial (int);
32928 @end cartouche
32929 @end group
32930 @end smallexample
32931
32932 @noindent
32933 It is important to understand that when building an Ada DLL to be used by
32934 other Ada applications, you need two different specs for the packages
32935 contained in the DLL: one for building the DLL and the other for using
32936 the DLL. This is because the @code{DLL} calling convention is needed to
32937 use a variable defined in a DLL, but when building the DLL, the variable
32938 must have either the @code{Ada} or @code{C} calling convention. As an
32939 example consider a DLL comprising the following package @code{API}:
32940
32941 @smallexample @c ada
32942 @group
32943 @cartouche
32944 package API is
32945    Count : Integer := 0;
32946    @dots{}
32947    --  Remainder of the package omitted.
32948 end API;
32949 @end cartouche
32950 @end group
32951 @end smallexample
32952
32953 @noindent
32954 After producing a DLL containing package @code{API}, the spec that
32955 must be used to import @code{API.Count} from Ada code outside of the
32956 DLL is:
32957
32958 @smallexample @c ada
32959 @group
32960 @cartouche
32961 package API is
32962    Count : Integer;
32963    pragma Import (DLL, Count);
32964 end API;
32965 @end cartouche
32966 @end group
32967 @end smallexample
32968
32969 @node Creating the Definition File
32970 @subsection Creating the Definition File
32971
32972 @noindent
32973 The definition file is the last file needed to build the DLL. It lists
32974 the exported symbols. As an example, the definition file for a DLL
32975 containing only package @code{API} (where all the entities are exported
32976 with a @code{C} calling convention) is:
32977
32978 @smallexample
32979 @group
32980 @cartouche
32981 EXPORTS
32982     count
32983     factorial
32984     finalize_api
32985     initialize_api
32986 @end cartouche
32987 @end group
32988 @end smallexample
32989
32990 @noindent
32991 If the @code{C} calling convention is missing from package @code{API},
32992 then the definition file contains the mangled Ada names of the above
32993 entities, which in this case are:
32994
32995 @smallexample
32996 @group
32997 @cartouche
32998 EXPORTS
32999     api__count
33000     api__factorial
33001     api__finalize_api
33002     api__initialize_api
33003 @end cartouche
33004 @end group
33005 @end smallexample
33006
33007 @node Using gnatdll
33008 @subsection Using @code{gnatdll}
33009 @findex gnatdll
33010
33011 @menu
33012 * gnatdll Example::
33013 * gnatdll behind the Scenes::
33014 * Using dlltool::
33015 @end menu
33016
33017 @noindent
33018 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
33019 and non-Ada sources that make up your DLL have been compiled.
33020 @code{gnatdll} is actually in charge of two distinct tasks: build the
33021 static import library for the DLL and the actual DLL. The form of the
33022 @code{gnatdll} command is
33023
33024 @smallexample
33025 @cartouche
33026 $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
33027 @end cartouche
33028 @end smallexample
33029
33030 @noindent
33031 where @var{list-of-files} is a list of ALI and object files. The object
33032 file list must be the exact list of objects corresponding to the non-Ada
33033 sources whose services are to be included in the DLL. The ALI file list
33034 must be the exact list of ALI files for the corresponding Ada sources
33035 whose services are to be included in the DLL. If @var{list-of-files} is
33036 missing, only the static import library is generated.
33037
33038 @noindent
33039 You may specify any of the following switches to @code{gnatdll}:
33040
33041 @table @code
33042 @item -a@ovar{address}
33043 @cindex @option{-a} (@code{gnatdll})
33044 Build a non-relocatable DLL at @var{address}. If @var{address} is not
33045 specified the default address @var{0x11000000} will be used. By default,
33046 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
33047 advise the reader to build relocatable DLL.
33048
33049 @item -b @var{address}
33050 @cindex @option{-b} (@code{gnatdll})
33051 Set the relocatable DLL base address. By default the address is
33052 @code{0x11000000}.
33053
33054 @item -bargs @var{opts}
33055 @cindex @option{-bargs} (@code{gnatdll})
33056 Binder options. Pass @var{opts} to the binder.
33057
33058 @item -d @var{dllfile}
33059 @cindex @option{-d} (@code{gnatdll})
33060 @var{dllfile} is the name of the DLL. This switch must be present for
33061 @code{gnatdll} to do anything. The name of the generated import library is
33062 obtained algorithmically from @var{dllfile} as shown in the following
33063 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
33064 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
33065 by option @option{-e}) is obtained algorithmically from @var{dllfile}
33066 as shown in the following example:
33067 if @var{dllfile} is @code{xyz.dll}, the definition
33068 file used is @code{xyz.def}.
33069
33070 @item -e @var{deffile}
33071 @cindex @option{-e} (@code{gnatdll})
33072 @var{deffile} is the name of the definition file.
33073
33074 @item -g
33075 @cindex @option{-g} (@code{gnatdll})
33076 Generate debugging information. This information is stored in the object
33077 file and copied from there to the final DLL file by the linker,
33078 where it can be read by the debugger. You must use the
33079 @option{-g} switch if you plan on using the debugger or the symbolic
33080 stack traceback.
33081
33082 @item -h
33083 @cindex @option{-h} (@code{gnatdll})
33084 Help mode. Displays @code{gnatdll} switch usage information.
33085
33086 @item -Idir
33087 @cindex @option{-I} (@code{gnatdll})
33088 Direct @code{gnatdll} to search the @var{dir} directory for source and
33089 object files needed to build the DLL.
33090 (@pxref{Search Paths and the Run-Time Library (RTL)}).
33091
33092 @item -k
33093 @cindex @option{-k} (@code{gnatdll})
33094 Removes the @code{@@}@var{nn} suffix from the import library's exported
33095 names, but keeps them for the link names. You must specify this
33096 option if you want to use a @code{Stdcall} function in a DLL for which
33097 the @code{@@}@var{nn} suffix has been removed. This is the case for most
33098 of the Windows NT DLL for example. This option has no effect when
33099 @option{-n} option is specified.
33100
33101 @item -l @var{file}
33102 @cindex @option{-l} (@code{gnatdll})
33103 The list of ALI and object files used to build the DLL are listed in
33104 @var{file}, instead of being given in the command line. Each line in
33105 @var{file} contains the name of an ALI or object file.
33106
33107 @item -n
33108 @cindex @option{-n} (@code{gnatdll})
33109 No Import. Do not create the import library.
33110
33111 @item -q
33112 @cindex @option{-q} (@code{gnatdll})
33113 Quiet mode. Do not display unnecessary messages.
33114
33115 @item -v
33116 @cindex @option{-v} (@code{gnatdll})
33117 Verbose mode. Display extra information.
33118
33119 @item -largs @var{opts}
33120 @cindex @option{-largs} (@code{gnatdll})
33121 Linker options. Pass @var{opts} to the linker.
33122 @end table
33123
33124 @node gnatdll Example
33125 @subsubsection @code{gnatdll} Example
33126
33127 @noindent
33128 As an example the command to build a relocatable DLL from @file{api.adb}
33129 once @file{api.adb} has been compiled and @file{api.def} created is
33130
33131 @smallexample
33132 $ gnatdll -d api.dll api.ali
33133 @end smallexample
33134
33135 @noindent
33136 The above command creates two files: @file{libapi.dll.a} (the import
33137 library) and @file{api.dll} (the actual DLL). If you want to create
33138 only the DLL, just type:
33139
33140 @smallexample
33141 $ gnatdll -d api.dll -n api.ali
33142 @end smallexample
33143
33144 @noindent
33145 Alternatively if you want to create just the import library, type:
33146
33147 @smallexample
33148 $ gnatdll -d api.dll
33149 @end smallexample
33150
33151 @node gnatdll behind the Scenes
33152 @subsubsection @code{gnatdll} behind the Scenes
33153
33154 @noindent
33155 This section details the steps involved in creating a DLL. @code{gnatdll}
33156 does these steps for you. Unless you are interested in understanding what
33157 goes on behind the scenes, you should skip this section.
33158
33159 We use the previous example of a DLL containing the Ada package @code{API},
33160 to illustrate the steps necessary to build a DLL. The starting point is a
33161 set of objects that will make up the DLL and the corresponding ALI
33162 files. In the case of this example this means that @file{api.o} and
33163 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
33164 the following:
33165
33166 @enumerate
33167 @item
33168 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
33169 the information necessary to generate relocation information for the
33170 DLL.
33171
33172 @smallexample
33173 @group
33174 $ gnatbind -n api
33175 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
33176 @end group
33177 @end smallexample
33178
33179 @noindent
33180 In addition to the base file, the @command{gnatlink} command generates an
33181 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
33182 asks @command{gnatlink} to generate the routines @code{DllMain} and
33183 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
33184 is loaded into memory.
33185
33186 @item
33187 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
33188 export table (@file{api.exp}). The export table contains the relocation
33189 information in a form which can be used during the final link to ensure
33190 that the Windows loader is able to place the DLL anywhere in memory.
33191
33192 @smallexample
33193 @group
33194 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33195           --output-exp api.exp
33196 @end group
33197 @end smallexample
33198
33199 @item
33200 @code{gnatdll} builds the base file using the new export table. Note that
33201 @command{gnatbind} must be called once again since the binder generated file
33202 has been deleted during the previous call to @command{gnatlink}.
33203
33204 @smallexample
33205 @group
33206 $ gnatbind -n api
33207 $ gnatlink api -o api.jnk api.exp -mdll
33208       -Wl,--base-file,api.base
33209 @end group
33210 @end smallexample
33211
33212 @item
33213 @code{gnatdll} builds the new export table using the new base file and
33214 generates the DLL import library @file{libAPI.dll.a}.
33215
33216 @smallexample
33217 @group
33218 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33219           --output-exp api.exp --output-lib libAPI.a
33220 @end group
33221 @end smallexample
33222
33223 @item
33224 Finally @code{gnatdll} builds the relocatable DLL using the final export
33225 table.
33226
33227 @smallexample
33228 @group
33229 $ gnatbind -n api
33230 $ gnatlink api api.exp -o api.dll -mdll
33231 @end group
33232 @end smallexample
33233 @end enumerate
33234
33235 @node Using dlltool
33236 @subsubsection Using @code{dlltool}
33237
33238 @noindent
33239 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
33240 DLLs and static import libraries. This section summarizes the most
33241 common @code{dlltool} switches. The form of the @code{dlltool} command
33242 is
33243
33244 @smallexample
33245 $ dlltool @ovar{switches}
33246 @end smallexample
33247
33248 @noindent
33249 @code{dlltool} switches include:
33250
33251 @table @option
33252 @item --base-file @var{basefile}
33253 @cindex @option{--base-file} (@command{dlltool})
33254 Read the base file @var{basefile} generated by the linker. This switch
33255 is used to create a relocatable DLL.
33256
33257 @item --def @var{deffile}
33258 @cindex @option{--def} (@command{dlltool})
33259 Read the definition file.
33260
33261 @item --dllname @var{name}
33262 @cindex @option{--dllname} (@command{dlltool})
33263 Gives the name of the DLL. This switch is used to embed the name of the
33264 DLL in the static import library generated by @code{dlltool} with switch
33265 @option{--output-lib}.
33266
33267 @item -k
33268 @cindex @option{-k} (@command{dlltool})
33269 Kill @code{@@}@var{nn} from exported names
33270 (@pxref{Windows Calling Conventions}
33271 for a discussion about @code{Stdcall}-style symbols.
33272
33273 @item --help
33274 @cindex @option{--help} (@command{dlltool})
33275 Prints the @code{dlltool} switches with a concise description.
33276
33277 @item --output-exp @var{exportfile}
33278 @cindex @option{--output-exp} (@command{dlltool})
33279 Generate an export file @var{exportfile}. The export file contains the
33280 export table (list of symbols in the DLL) and is used to create the DLL.
33281
33282 @item --output-lib @var{libfile}
33283 @cindex @option{--output-lib} (@command{dlltool})
33284 Generate a static import library @var{libfile}.
33285
33286 @item -v
33287 @cindex @option{-v} (@command{dlltool})
33288 Verbose mode.
33289
33290 @item --as @var{assembler-name}
33291 @cindex @option{--as} (@command{dlltool})
33292 Use @var{assembler-name} as the assembler. The default is @code{as}.
33293 @end table
33294
33295 @node GNAT and Windows Resources
33296 @section GNAT and Windows Resources
33297 @cindex Resources, windows
33298
33299 @menu
33300 * Building Resources::
33301 * Compiling Resources::
33302 * Using Resources::
33303 @end menu
33304
33305 @noindent
33306 Resources are an easy way to add Windows specific objects to your
33307 application. The objects that can be added as resources include:
33308
33309 @itemize @bullet
33310 @item
33311 menus
33312
33313 @item
33314 accelerators
33315
33316 @item
33317 dialog boxes
33318
33319 @item
33320 string tables
33321
33322 @item
33323 bitmaps
33324
33325 @item
33326 cursors
33327
33328 @item
33329 icons
33330
33331 @item
33332 fonts
33333 @end itemize
33334
33335 @noindent
33336 This section explains how to build, compile and use resources.
33337
33338 @node Building Resources
33339 @subsection Building Resources
33340 @cindex Resources, building
33341
33342 @noindent
33343 A resource file is an ASCII file. By convention resource files have an
33344 @file{.rc} extension.
33345 The easiest way to build a resource file is to use Microsoft tools
33346 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
33347 @code{dlgedit.exe} to build dialogs.
33348 It is always possible to build an @file{.rc} file yourself by writing a
33349 resource script.
33350
33351 It is not our objective to explain how to write a resource file. A
33352 complete description of the resource script language can be found in the
33353 Microsoft documentation.
33354
33355 @node Compiling Resources
33356 @subsection Compiling Resources
33357 @findex rc
33358 @findex windres
33359 @cindex Resources, compiling
33360
33361 @noindent
33362 This section describes how to build a GNAT-compatible (COFF) object file
33363 containing the resources. This is done using the Resource Compiler
33364 @code{windres} as follows:
33365
33366 @smallexample
33367 $ windres -i myres.rc -o myres.o
33368 @end smallexample
33369
33370 @noindent
33371 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
33372 file. You can specify an alternate preprocessor (usually named
33373 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
33374 parameter. A list of all possible options may be obtained by entering
33375 the command @code{windres} @option{--help}.
33376
33377 It is also possible to use the Microsoft resource compiler @code{rc.exe}
33378 to produce a @file{.res} file (binary resource file). See the
33379 corresponding Microsoft documentation for further details. In this case
33380 you need to use @code{windres} to translate the @file{.res} file to a
33381 GNAT-compatible object file as follows:
33382
33383 @smallexample
33384 $ windres -i myres.res -o myres.o
33385 @end smallexample
33386
33387 @node Using Resources
33388 @subsection Using Resources
33389 @cindex Resources, using
33390
33391 @noindent
33392 To include the resource file in your program just add the
33393 GNAT-compatible object file for the resource(s) to the linker
33394 arguments. With @command{gnatmake} this is done by using the @option{-largs}
33395 option:
33396
33397 @smallexample
33398 $ gnatmake myprog -largs myres.o
33399 @end smallexample
33400
33401 @node Debugging a DLL
33402 @section Debugging a DLL
33403 @cindex DLL debugging
33404
33405 @menu
33406 * Program and DLL Both Built with GCC/GNAT::
33407 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
33408 @end menu
33409
33410 @noindent
33411 Debugging a DLL is similar to debugging a standard program. But
33412 we have to deal with two different executable parts: the DLL and the
33413 program that uses it. We have the following four possibilities:
33414
33415 @enumerate 1
33416 @item
33417 The program and the DLL are built with @code{GCC/GNAT}.
33418 @item
33419 The program is built with foreign tools and the DLL is built with
33420 @code{GCC/GNAT}.
33421 @item
33422 The program is built with @code{GCC/GNAT} and the DLL is built with
33423 foreign tools.
33424 @item
33425 @end enumerate
33426
33427 @noindent
33428 In this section we address only cases one and two above.
33429 There is no point in trying to debug
33430 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
33431 information in it. To do so you must use a debugger compatible with the
33432 tools suite used to build the DLL.
33433
33434 @node Program and DLL Both Built with GCC/GNAT
33435 @subsection Program and DLL Both Built with GCC/GNAT
33436
33437 @noindent
33438 This is the simplest case. Both the DLL and the program have @code{GDB}
33439 compatible debugging information. It is then possible to break anywhere in
33440 the process. Let's suppose here that the main procedure is named
33441 @code{ada_main} and that in the DLL there is an entry point named
33442 @code{ada_dll}.
33443
33444 @noindent
33445 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
33446 program must have been built with the debugging information (see GNAT -g
33447 switch). Here are the step-by-step instructions for debugging it:
33448
33449 @enumerate 1
33450 @item Launch @code{GDB} on the main program.
33451
33452 @smallexample
33453 $ gdb -nw ada_main
33454 @end smallexample
33455
33456 @item Start the program and stop at the beginning of the main procedure
33457
33458 @smallexample
33459 (gdb) start
33460 @end smallexample
33461
33462 @noindent
33463 This step is required to be able to set a breakpoint inside the DLL. As long
33464 as the program is not run, the DLL is not loaded. This has the
33465 consequence that the DLL debugging information is also not loaded, so it is not
33466 possible to set a breakpoint in the DLL.
33467
33468 @item Set a breakpoint inside the DLL
33469
33470 @smallexample
33471 (gdb) break ada_dll
33472 (gdb) cont
33473 @end smallexample
33474
33475 @end enumerate
33476
33477 @noindent
33478 At this stage a breakpoint is set inside the DLL. From there on
33479 you can use the standard approach to debug the whole program
33480 (@pxref{Running and Debugging Ada Programs}).
33481
33482 @ignore
33483 @c This used to work, probably because the DLLs were non-relocatable
33484 @c keep this section around until the problem is sorted out.
33485
33486 To break on the @code{DllMain} routine it is not possible to follow
33487 the procedure above. At the time the program stop on @code{ada_main}
33488 the @code{DllMain} routine as already been called. Either you can use
33489 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
33490
33491 @enumerate 1
33492 @item Launch @code{GDB} on the main program.
33493
33494 @smallexample
33495 $ gdb ada_main
33496 @end smallexample
33497
33498 @item Load DLL symbols
33499
33500 @smallexample
33501 (gdb) add-sym api.dll
33502 @end smallexample
33503
33504 @item Set a breakpoint inside the DLL
33505
33506 @smallexample
33507 (gdb) break ada_dll.adb:45
33508 @end smallexample
33509
33510 Note that at this point it is not possible to break using the routine symbol
33511 directly as the program is not yet running. The solution is to break
33512 on the proper line (break in @file{ada_dll.adb} line 45).
33513
33514 @item Start the program
33515
33516 @smallexample
33517 (gdb) run
33518 @end smallexample
33519
33520 @end enumerate
33521 @end ignore
33522
33523 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
33524 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
33525
33526 @menu
33527 * Debugging the DLL Directly::
33528 * Attaching to a Running Process::
33529 @end menu
33530
33531 @noindent
33532 In this case things are slightly more complex because it is not possible to
33533 start the main program and then break at the beginning to load the DLL and the
33534 associated DLL debugging information. It is not possible to break at the
33535 beginning of the program because there is no @code{GDB} debugging information,
33536 and therefore there is no direct way of getting initial control. This
33537 section addresses this issue by describing some methods that can be used
33538 to break somewhere in the DLL to debug it.
33539
33540 @noindent
33541 First suppose that the main procedure is named @code{main} (this is for
33542 example some C code built with Microsoft Visual C) and that there is a
33543 DLL named @code{test.dll} containing an Ada entry point named
33544 @code{ada_dll}.
33545
33546 @noindent
33547 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
33548 been built with debugging information (see GNAT -g option).
33549
33550 @node Debugging the DLL Directly
33551 @subsubsection Debugging the DLL Directly
33552
33553 @enumerate 1
33554 @item
33555 Find out the executable starting address
33556
33557 @smallexample
33558 $ objdump --file-header main.exe
33559 @end smallexample
33560
33561 The starting address is reported on the last line. For example:
33562
33563 @smallexample
33564 main.exe:     file format pei-i386
33565 architecture: i386, flags 0x0000010a:
33566 EXEC_P, HAS_DEBUG, D_PAGED
33567 start address 0x00401010
33568 @end smallexample
33569
33570 @item
33571 Launch the debugger on the executable.
33572
33573 @smallexample
33574 $ gdb main.exe
33575 @end smallexample
33576
33577 @item
33578 Set a breakpoint at the starting address, and launch the program.
33579
33580 @smallexample
33581 $ (gdb) break *0x00401010
33582 $ (gdb) run
33583 @end smallexample
33584
33585 The program will stop at the given address.
33586
33587 @item
33588 Set a breakpoint on a DLL subroutine.
33589
33590 @smallexample
33591 (gdb) break ada_dll.adb:45
33592 @end smallexample
33593
33594 Or if you want to break using a symbol on the DLL, you need first to
33595 select the Ada language (language used by the DLL).
33596
33597 @smallexample
33598 (gdb) set language ada
33599 (gdb) break ada_dll
33600 @end smallexample
33601
33602 @item
33603 Continue the program.
33604
33605 @smallexample
33606 (gdb) cont
33607 @end smallexample
33608
33609 @noindent
33610 This will run the program until it reaches the breakpoint that has been
33611 set. From that point you can use the standard way to debug a program
33612 as described in (@pxref{Running and Debugging Ada Programs}).
33613
33614 @end enumerate
33615
33616 @noindent
33617 It is also possible to debug the DLL by attaching to a running process.
33618
33619 @node Attaching to a Running Process
33620 @subsubsection Attaching to a Running Process
33621 @cindex DLL debugging, attach to process
33622
33623 @noindent
33624 With @code{GDB} it is always possible to debug a running process by
33625 attaching to it. It is possible to debug a DLL this way. The limitation
33626 of this approach is that the DLL must run long enough to perform the
33627 attach operation. It may be useful for instance to insert a time wasting
33628 loop in the code of the DLL to meet this criterion.
33629
33630 @enumerate 1
33631
33632 @item Launch the main program @file{main.exe}.
33633
33634 @smallexample
33635 $ main
33636 @end smallexample
33637
33638 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
33639 that the process PID for @file{main.exe} is 208.
33640
33641 @item Launch gdb.
33642
33643 @smallexample
33644 $ gdb
33645 @end smallexample
33646
33647 @item Attach to the running process to be debugged.
33648
33649 @smallexample
33650 (gdb) attach 208
33651 @end smallexample
33652
33653 @item Load the process debugging information.
33654
33655 @smallexample
33656 (gdb) symbol-file main.exe
33657 @end smallexample
33658
33659 @item Break somewhere in the DLL.
33660
33661 @smallexample
33662 (gdb) break ada_dll
33663 @end smallexample
33664
33665 @item Continue process execution.
33666
33667 @smallexample
33668 (gdb) cont
33669 @end smallexample
33670
33671 @end enumerate
33672
33673 @noindent
33674 This last step will resume the process execution, and stop at
33675 the breakpoint we have set. From there you can use the standard
33676 approach to debug a program as described in
33677 (@pxref{Running and Debugging Ada Programs}).
33678
33679 @node Setting Stack Size from gnatlink
33680 @section Setting Stack Size from @command{gnatlink}
33681
33682 @noindent
33683 It is possible to specify the program stack size at link time. On modern
33684 versions of Windows, starting with XP, this is mostly useful to set the size of
33685 the main stack (environment task). The other task stacks are set with pragma
33686 Storage_Size or with the @command{gnatbind -d} command.
33687
33688 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
33689 reserve size of individual tasks, the link-time stack size applies to all
33690 tasks, and pragma Storage_Size has no effect.
33691 In particular, Stack Overflow checks are made against this
33692 link-time specified size.
33693
33694 This setting can be done with
33695 @command{gnatlink} using either:
33696
33697 @itemize @bullet
33698
33699 @item using @option{-Xlinker} linker option
33700
33701 @smallexample
33702 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
33703 @end smallexample
33704
33705 This sets the stack reserve size to 0x10000 bytes and the stack commit
33706 size to 0x1000 bytes.
33707
33708 @item using @option{-Wl} linker option
33709
33710 @smallexample
33711 $ gnatlink hello -Wl,--stack=0x1000000
33712 @end smallexample
33713
33714 This sets the stack reserve size to 0x1000000 bytes. Note that with
33715 @option{-Wl} option it is not possible to set the stack commit size
33716 because the coma is a separator for this option.
33717
33718 @end itemize
33719
33720 @node Setting Heap Size from gnatlink
33721 @section Setting Heap Size from @command{gnatlink}
33722
33723 @noindent
33724 Under Windows systems, it is possible to specify the program heap size from
33725 @command{gnatlink} using either:
33726
33727 @itemize @bullet
33728
33729 @item using @option{-Xlinker} linker option
33730
33731 @smallexample
33732 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
33733 @end smallexample
33734
33735 This sets the heap reserve size to 0x10000 bytes and the heap commit
33736 size to 0x1000 bytes.
33737
33738 @item using @option{-Wl} linker option
33739
33740 @smallexample
33741 $ gnatlink hello -Wl,--heap=0x1000000
33742 @end smallexample
33743
33744 This sets the heap reserve size to 0x1000000 bytes. Note that with
33745 @option{-Wl} option it is not possible to set the heap commit size
33746 because the coma is a separator for this option.
33747
33748 @end itemize
33749
33750 @end ifset
33751
33752 @c **********************************
33753 @c * GNU Free Documentation License *
33754 @c **********************************
33755 @include fdl.texi
33756 @c GNU Free Documentation License
33757
33758 @node Index,,GNU Free Documentation License, Top
33759 @unnumbered Index
33760
33761 @printindex cp
33762
33763 @contents
33764 @c Put table of contents at end, otherwise it precedes the "title page" in
33765 @c the .txt version
33766 @c Edit the pdf file to move the contents to the beginning, after the title
33767 @c page
33768
33769 @bye