OSDN Git Service

2009-08-17 Robert Dewar <dewar@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
20693 supplied.
20694
20695 @menu
20696 * Format of the Report File::
20697 * General gnatcheck Switches::
20698 * gnatcheck Rule Options::
20699 * Adding the Results of Compiler Checks to gnatcheck Output::
20700 * Project-Wide Checks::
20701 * Rule exemption::
20702 * Predefined Rules::
20703 @end menu
20704
20705 @node Format of the Report File
20706 @section Format of the Report File
20707 @cindex Report file (for @code{gnatcheck})
20708
20709 @noindent
20710 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20711 rule violations.
20712 It also creates a text file  that
20713 contains the complete report of the last gnatcheck run. By default this file
20714 is named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the
20715 current directory; the @option{^-o^/OUTPUT^} option can be used to change the
20716 name and/or location of the report file. This report contains:
20717 @itemize @bullet
20718 @item date and time of @command{gnatcheck} run, the version of
20719 the tool that has generated this report and the full parameters
20720 of the  @command{gnatcheck} invocation;
20721 @item list of enabled rules;
20722 @item total number of detected violations;
20723 @item list of source files where rule violations have been detected;
20724 @item list of source files where no violations have been detected.
20725 @end itemize
20726
20727 @node General gnatcheck Switches
20728 @section General @command{gnatcheck} Switches
20729
20730 @noindent
20731 The following switches control the general @command{gnatcheck} behavior
20732
20733 @table @option
20734 @c !sort!
20735 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20736 @item ^-a^/ALL^
20737 Process all units including those with read-only ALI files such as
20738 those from the GNAT Run-Time library.
20739
20740 @ifclear vms
20741 @ignore
20742 @cindex @option{-d} (@command{gnatcheck})
20743 @item -d
20744 Debug mode
20745 @end ignore
20746
20747 @cindex @option{-dd} (@command{gnatcheck})
20748 @item -dd
20749 Progress indicator mode (for use in GPS).
20750 @end ifclear
20751
20752 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20753 @item ^-h^/HELP^
20754 List the predefined and user-defined rules. For more details see
20755 @ref{Predefined Rules}.
20756
20757 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20758 @item ^-l^/LOCS^
20759 Use full source locations references in the report file. For a construct from
20760 a generic instantiation a full source location is a chain from the location
20761 of this construct in the generic unit to the place where this unit is
20762 instantiated.
20763
20764 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
20765 @item ^-log^/LOG^
20766 Duplicate all the output sent to @file{stderr} into a log file. The log file
20767 is named @file{gnatcheck.log} and is located in the current directory.
20768
20769 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20770 @item ^-m@i{nnnn}^/DIAGNOSTIC_LIMIT=@i{nnnn}^
20771 Maximum number of diagnostics to be sent to @file{stdout}, where @i{nnnn} is in
20772 the range 0@dots{}1000;
20773 the default value is 500. Zero means that there is no limitation on
20774 the number of diagnostic messages to be output.
20775
20776 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20777 @item ^-q^/QUIET^
20778 Quiet mode. All the diagnostics about rule violations are placed in the
20779 @command{gnatcheck} report file only, without duplication on @file{stdout}.
20780
20781 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20782 @item ^-s^/SHORT^
20783 Short format of the report file (no version information, no list of applied
20784 rules, no list of checked sources is included)
20785
20786 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
20787 @item ^-s1^/COMPILER_STYLE^
20788 Include the compiler-style section in the report file
20789
20790 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
20791 @item ^-s2^/BY_RULES^
20792 Include the section containing diagnostics ordered by rules in the report file
20793
20794 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
20795 @item ^-s3^/BY_FILES_BY_RULES^
20796 Include the section containing diagnostics ordered by files and then by rules
20797 in the report file
20798
20799 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
20800 @item ^-t^/TIME^
20801 Print out execution time.
20802
20803 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20804 @item ^-v^/VERBOSE^
20805 Verbose mode; @command{gnatcheck} generates version information and then
20806 a trace of sources being processed.
20807
20808 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
20809 @item ^-o ^/OUTPUT=^@var{report_file}
20810 Set name of report file file to @var{report_file} .
20811
20812 @end table
20813
20814 @noindent
20815 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20816 @option{^-s2^/BY_RULES^} or
20817 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20818 then the  @command{gnatcheck} report file will only contain sections
20819 explicitly denoted by these options.
20820
20821 @node gnatcheck Rule Options
20822 @section @command{gnatcheck} Rule Options
20823
20824 @noindent
20825 The following options control the processing performed by
20826 @command{gnatcheck}.
20827
20828 @table @option
20829 @cindex @option{+ALL} (@command{gnatcheck})
20830 @item +ALL
20831 Turn all the rule checks ON.
20832
20833 @cindex @option{-ALL} (@command{gnatcheck})
20834 @item -ALL
20835 Turn all the rule checks OFF.
20836
20837 @cindex @option{+R} (@command{gnatcheck})
20838 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20839 Turn on the check for a specified rule with the specified parameter, if any.
20840 @var{rule_id} must be the identifier of one of the currently implemented rules
20841 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20842 are not case-sensitive. The @var{param} item must
20843 be a string representing a valid parameter(s) for the specified rule.
20844 If it contains any space characters then this string must be enclosed in
20845 quotation marks.
20846
20847 @cindex @option{-R} (@command{gnatcheck})
20848 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20849 Turn off the check for a specified rule with the specified parameter, if any.
20850
20851 @cindex @option{-from} (@command{gnatcheck})
20852 @item -from=@var{rule_option_filename}
20853 Read the rule options from the text file @var{rule_option_filename}, referred as
20854 ``rule file'' below.
20855
20856 @end table
20857
20858 @noindent
20859 The default behavior is that all the rule checks are disabled.
20860
20861 A rule file is a text file containing a set of rule options.
20862 @cindex Rule file (for @code{gnatcheck})
20863 The file may contain empty lines and Ada-style comments (comment
20864 lines and end-of-line comments). The rule file has free format; that is,
20865 you do not have to start a new rule option on a new line.
20866
20867 A rule file may contain other @option{-from=@var{rule_option_filename}}
20868 options, each such option being replaced with the content of the
20869 corresponding rule file during the rule files processing. In case a
20870 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20871 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20872 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20873 the processing of rule files is interrupted and a part of their content
20874 is ignored.
20875
20876
20877 @node Adding the Results of Compiler Checks to gnatcheck Output
20878 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20879
20880 @noindent
20881 The @command{gnatcheck} tool can include in the generated diagnostic messages
20882 and in
20883 the report file the results of the checks performed by the compiler. Though
20884 disabled by default, this effect may be obtained by using @option{+R} with
20885 the following rule identifiers and parameters:
20886
20887 @table @option
20888 @item Restrictions
20889 To record restrictions violations (which are performed by the compiler if the
20890 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20891 use the @code{Restrictions} rule
20892 with the same parameters as pragma
20893 @code{Restrictions} or @code{Restriction_Warnings}.
20894
20895 @item Style_Checks
20896 To record compiler style checks (@pxref{Style Checking}), use the
20897 @code{Style_Checks} rule.
20898 This rule takes a parameter in one of the following forms:
20899 @itemize
20900 @item
20901 @code{All_Checks},
20902 which enables the standard style checks corresponding to the @option{-gnatyy}
20903 GNAT style check option, or
20904
20905 @item
20906 a string with the same
20907 structure and semantics as the @code{string_LITERAL} parameter of the
20908 GNAT pragma @code{Style_Checks}
20909 (for further information about this pragma,
20910 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
20911 @end itemize
20912
20913 @noindent
20914 For example, the
20915 @code{+RStyle_Checks:O} rule option activates
20916 the compiler style check that corresponds to
20917 @code{-gnatyO} style check option.
20918
20919 @item Warnings
20920 To record compiler warnings (@pxref{Warning Message Control}), use the
20921 @code{Warnings} rule with a parameter that is a valid
20922 @i{static_string_expression} argument of the GNAT pragma @code{Warnings}
20923 (for further information about this pragma,
20924 @pxref{Pragma Warnings,,,gnat_rm, GNAT Reference Manual}).
20925 Note that in case of gnatcheck
20926 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20927 all the specific warnings, but not suppresses the warning mode,
20928 and 'e' parameter, corresponding to @option{-gnatwe} that means
20929 "treat warnings as errors", does not have any effect.
20930
20931 @end table
20932
20933 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20934 option with the corresponding restriction name as a parameter. @code{-R} is
20935 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20936 warnings and style checks, use the corresponding warning and style options.
20937
20938 @node Project-Wide Checks
20939 @section Project-Wide Checks
20940 @cindex Project-wide checks (for @command{gnatcheck})
20941
20942 @noindent
20943 In order to perform checks on all units of a given project, you can use
20944 the GNAT driver along with the @option{-P} option:
20945 @smallexample
20946    gnat check -Pproj -rules -from=my_rules
20947 @end smallexample
20948
20949 @noindent
20950 If the project @code{proj} depends upon other projects, you can perform
20951 checks on the project closure using the @option{-U} option:
20952 @smallexample
20953    gnat check -Pproj -U -rules -from=my_rules
20954 @end smallexample
20955
20956 @noindent
20957 Finally, if not all the units are relevant to a particular main
20958 program in the project closure, you can perform checks for the set
20959 of units needed to create a given main program (unit closure) using
20960 the @option{-U} option followed by the name of the main unit:
20961 @smallexample
20962    gnat check -Pproj -U main -rules -from=my_rules
20963 @end smallexample
20964
20965
20966 @node Rule exemption
20967 @section Rule exemption
20968 @cindex Rule exemption (for @command{gnatcheck})
20969
20970 @noindent
20971 One of the most useful applications of @command{gnatcheck} is to
20972 automate the enforcement of project-specific coding standards,
20973 for example in safety-critical systems where particular features
20974 must be restricted in order to simplify the certification effort.
20975 However, it may sometimes be appropriate to violate a coding standard rule,
20976 and in such cases the rationale for the violation should be provided
20977 in the source program itself so that the individuals
20978 reviewing or maintaining the program can immediately understand the intent.
20979
20980 The @command{gnatcheck} tool supports this practice with the notion of
20981 a ``rule exemption'' covering a specific source code section. Normally
20982 rule violation messages are issued both on @file{stderr}
20983 and in a report file. In contrast, exempted violations are not listed on
20984 @file{stderr}; thus users invoking @command{gnatcheck} interactively
20985 (e.g. in its GPS interface) do not need to pay attention to known and
20986 justified violations. However, exempted violations along with their
20987 justification are documented in a special section of the report file that
20988 @command{gnatcheck} generates.
20989
20990 @menu
20991 * Using pragma Annotate to Control Rule Exemption::
20992 * gnatcheck Annotations Rules::
20993 @end menu
20994
20995 @node Using pragma Annotate to Control Rule Exemption
20996 @subsection Using pragma @code{Annotate} to Control Rule Exemption
20997 @cindex Using pragma Annotate to control rule exemption
20998
20999 @noindent
21000 Rule exemption is controlled by pragma @code{Annotate} when its first
21001 argument is ``gnatcheck''. The syntax of @command{gnatcheck}'s
21002 exemption control annotations is as follows:
21003
21004 @smallexample @c ada
21005 @group
21006 pragma Annotate (gnatcheck, @i{exemption_control}, @i{Rule_Name}, [@i{justification}]);
21007
21008 @i{exemption_control} ::= "Exempt_On" | "Exempt_Off"
21009
21010 @i{Rule_Name}         ::= string_literal
21011
21012 @i{justification}     ::= string_literal
21013 @end group
21014 @end smallexample
21015
21016 @noindent
21017 When a @command{gnatcheck} annotation has more then four arguments,
21018 @command{gnatcheck} issues a warning and ignores the additional arguments.
21019 If the additional arguments do not follow the syntax above,
21020 @command{gnatcheck} emits a warning and ignores the annotation.
21021
21022 The @i{@code{Rule_Name}} argument should be the name of some existing
21023 @command{gnatcheck} rule.
21024 Otherwise a warning message is generated and the pragma is
21025 ignored. If @code{Rule_Name} denotes a rule that is not activated by the given
21026 @command{gnatcheck} call, the pragma is ignored and no warning is issued.
21027
21028 A source code section where an exemption is active for a given rule is
21029 delimited by an @code{exempt_on} and @code{exempt_off} annotation pair:
21030
21031 @smallexample @c ada
21032 pragma Annotate (gnatcheck, "Exempt_On", Rule_Name, "justification");
21033 -- source code section
21034 pragma Annotate (gnatcheck, "Exempt_Off", Rule_Name);
21035 @end smallexample
21036
21037
21038 @node gnatcheck Annotations Rules
21039 @subsection @command{gnatcheck} Annotations Rules
21040 @cindex @command{gnatcheck} annotations rules
21041
21042 @itemize @bullet
21043
21044 @item
21045 An ``Exempt_Off'' annotation can only appear after a corresponding
21046 ``Exempt_On'' annotation.
21047
21048 @item
21049 Exempted source code sections are only based on the source location of the
21050 annotations. Any source construct between the two
21051 annotations is part of the exempted source code section.
21052
21053 @item
21054 Exempted source code sections for different rules are independent. They can
21055 be nested or intersect with one another without limitation.
21056 Creating nested or intersecting source code sections for the same rule is
21057 not allowed.
21058
21059 @item
21060 Malformed exempted source code sections are reported by a warning, and
21061 the corresponding rule exemptions are ignored.
21062
21063 @item
21064 When an exempted source code section does not contain at least one violation
21065 of the exempted rule, a warning is emitted on @file{stderr}.
21066
21067 @item
21068 If an ``Exempt_On'' annotation pragma does not have a matching
21069 ``Exempt_Off'' annotation pragma in the same compilation unit, then the
21070 exemption for the given rule is ignored and a warning is issued.
21071 @end itemize
21072
21073
21074 @node Predefined Rules
21075 @section Predefined Rules
21076 @cindex Predefined rules (for @command{gnatcheck})
21077
21078 @ignore
21079 @c (Jan 2007) Since the global rules are still under development and are not
21080 @c documented, there is no point in explaining the difference between
21081 @c global and local rules
21082 @noindent
21083 A rule in @command{gnatcheck} is either local or global.
21084 A @emph{local rule} is a rule that applies to a well-defined section
21085 of a program and that can be checked by analyzing only this section.
21086 A @emph{global rule} requires analysis of some global properties of the
21087 whole program (mostly related to the program call graph).
21088 As of @value{NOW}, the implementation of global rules should be
21089 considered to be at a preliminary stage. You can use the
21090 @option{+GLOBAL} option to enable all the global rules, and the
21091 @option{-GLOBAL} rule option to disable all the global rules.
21092
21093 All the global rules in the list below are
21094 so indicated by marking them ``GLOBAL''.
21095 This +GLOBAL and -GLOBAL options are not
21096 included in the list of gnatcheck options above, because at the moment they
21097 are considered as a temporary debug options.
21098
21099 @command{gnatcheck} performs rule checks for generic
21100 instances only for global rules.  This limitation may be relaxed in a later
21101 release.
21102 @end ignore
21103
21104 @noindent
21105 The following subsections document the rules implemented in
21106 @command{gnatcheck}.
21107 The subsection title is the same as the rule identifier, which may be
21108 used as a parameter of the @option{+R} or @option{-R} options.
21109
21110
21111 @menu
21112 * Abstract_Type_Declarations::
21113 * Anonymous_Arrays::
21114 * Anonymous_Subtypes::
21115 * Blocks::
21116 * Boolean_Relational_Operators::
21117 @ignore
21118 * Ceiling_Violations::
21119 @end ignore
21120 * Complex_Inlined_Subprograms::
21121 * Controlled_Type_Declarations::
21122 * Declarations_In_Blocks::
21123 * Deep_Inheritance_Hierarchies::
21124 * Deeply_Nested_Generics::
21125 * Deeply_Nested_Inlining::
21126 @ignore
21127 * Deeply_Nested_Local_Inlining::
21128 @end ignore
21129 * Default_Parameters::
21130 * Direct_Calls_To_Primitives::
21131 * Discriminated_Records::
21132 * Enumeration_Ranges_In_CASE_Statements::
21133 * Exceptions_As_Control_Flow::
21134 * Exits_From_Conditional_Loops::
21135 * EXIT_Statements_With_No_Loop_Name::
21136 * Expanded_Loop_Exit_Names::
21137 * Explicit_Full_Discrete_Ranges::
21138 * Float_Equality_Checks::
21139 * Forbidden_Attributes::
21140 * Forbidden_Pragmas::
21141 * Function_Style_Procedures::
21142 * Generics_In_Subprograms::
21143 * GOTO_Statements::
21144 * Implicit_IN_Mode_Parameters::
21145 * Implicit_SMALL_For_Fixed_Point_Types::
21146 * Improperly_Located_Instantiations::
21147 * Improper_Returns::
21148 * Library_Level_Subprograms::
21149 * Local_Packages::
21150 @ignore
21151 * Improperly_Called_Protected_Entries::
21152 @end ignore
21153 * Metrics::
21154 * Misnamed_Controlling_Parameters::
21155 * Misnamed_Identifiers::
21156 * Multiple_Entries_In_Protected_Definitions::
21157 * Name_Clashes::
21158 * Non_Qualified_Aggregates::
21159 * Non_Short_Circuit_Operators::
21160 * Non_SPARK_Attributes::
21161 * Non_Tagged_Derived_Types::
21162 * Non_Visible_Exceptions::
21163 * Numeric_Literals::
21164 * OTHERS_In_Aggregates::
21165 * OTHERS_In_CASE_Statements::
21166 * OTHERS_In_Exception_Handlers::
21167 * Outer_Loop_Exits::
21168 * Overloaded_Operators::
21169 * Overly_Nested_Control_Structures::
21170 * Parameters_Out_Of_Order::
21171 * Positional_Actuals_For_Defaulted_Generic_Parameters::
21172 * Positional_Actuals_For_Defaulted_Parameters::
21173 * Positional_Components::
21174 * Positional_Generic_Parameters::
21175 * Positional_Parameters::
21176 * Predefined_Numeric_Types::
21177 * Raising_External_Exceptions::
21178 * Raising_Predefined_Exceptions::
21179 * Separate_Numeric_Error_Handlers::
21180 @ignore
21181 * Recursion::
21182 * Side_Effect_Functions::
21183 @end ignore
21184 * Slices::
21185 * Too_Many_Parents::
21186 * Unassigned_OUT_Parameters::
21187 * Uncommented_BEGIN_In_Package_Bodies::
21188 * Unconditional_Exits::
21189 * Unconstrained_Array_Returns::
21190 * Universal_Ranges::
21191 * Unnamed_Blocks_And_Loops::
21192 @ignore
21193 * Unused_Subprograms::
21194 @end ignore
21195 * USE_PACKAGE_Clauses::
21196 * Visible_Components::
21197 * Volatile_Objects_Without_Address_Clauses::
21198 @end menu
21199
21200
21201 @node Abstract_Type_Declarations
21202 @subsection @code{Abstract_Type_Declarations}
21203 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
21204
21205 @noindent
21206 Flag all declarations of abstract types. For an abstract private
21207 type, both the private and full type declarations are flagged.
21208
21209 This rule has no parameters.
21210
21211
21212 @node Anonymous_Arrays
21213 @subsection @code{Anonymous_Arrays}
21214 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
21215
21216 @noindent
21217 Flag all anonymous array type definitions (by Ada semantics these can only
21218 occur in object declarations).
21219
21220 This rule has no parameters.
21221
21222 @node Anonymous_Subtypes
21223 @subsection @code{Anonymous_Subtypes}
21224 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
21225
21226 @noindent
21227 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
21228 any instance of a subtype indication with a constraint, other than one
21229 that occurs immediately within a subtype declaration. Any use of a range
21230 other than as a constraint used immediately within a subtype declaration
21231 is considered as an anonymous subtype.
21232
21233 An effect of this rule is that @code{for} loops such as the following are
21234 flagged (since @code{1..N} is formally a ``range''):
21235
21236 @smallexample @c ada
21237 for I in 1 .. N loop
21238    @dots{}
21239 end loop;
21240 @end smallexample
21241
21242 @noindent
21243 Declaring an explicit subtype solves the problem:
21244
21245 @smallexample @c ada
21246 subtype S is Integer range 1..N;
21247 @dots{}
21248 for I in S loop
21249    @dots{}
21250 end loop;
21251 @end smallexample
21252
21253 @noindent
21254 This rule has no parameters.
21255
21256 @node Blocks
21257 @subsection @code{Blocks}
21258 @cindex @code{Blocks} rule (for @command{gnatcheck})
21259
21260 @noindent
21261 Flag each block statement.
21262
21263 This rule has no parameters.
21264
21265 @node Boolean_Relational_Operators
21266 @subsection @code{Boolean_Relational_Operators}
21267 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
21268
21269 @noindent
21270 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
21271 ``>='', ``='' and ``/='') for the predefined Boolean type.
21272 (This rule is useful in enforcing the SPARK language restrictions.)
21273
21274 Calls to predefined relational operators of any type derived from
21275 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
21276 with these designators, and uses of operators that are renamings
21277 of the predefined relational operators for @code{Standard.Boolean},
21278 are likewise not detected.
21279
21280 This rule has no parameters.
21281
21282 @ignore
21283 @node Ceiling_Violations
21284 @subsection @code{Ceiling5_Violations} (under construction, GLOBAL)
21285 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
21286
21287 @noindent
21288 Flag invocations of a protected operation by a task whose priority exceeds
21289 the protected object's ceiling.
21290
21291 As of @value{NOW}, this rule has the following limitations:
21292
21293 @itemize @bullet
21294
21295 @item
21296  We consider only pragmas Priority and Interrupt_Priority as means to define
21297   a task/protected operation priority. We do not consider the effect of using
21298   Ada.Dynamic_Priorities.Set_Priority procedure;
21299
21300 @item
21301  We consider only base task priorities, and no priority inheritance. That is,
21302   we do not make a difference between calls issued during task activation and
21303   execution of the sequence of statements from task body;
21304
21305 @item
21306  Any situation when the priority of protected operation caller is set by a
21307   dynamic expression (that is, the corresponding Priority or
21308   Interrupt_Priority pragma has a non-static expression as an argument) we
21309   treat as a priority inconsistency (and, therefore, detect this situation).
21310 @end itemize
21311
21312 @noindent
21313 At the moment the notion of the main subprogram is not implemented in
21314 gnatcheck, so any pragma Priority in a library level subprogram body (in case
21315 if this subprogram can be a main subprogram of a partition) changes the
21316 priority of an environment task. So if we have more then one such pragma in
21317 the set of processed sources, the pragma that is processed last, defines the
21318 priority of an environment task.
21319
21320 This rule has no parameters.
21321 @end ignore
21322
21323 @node Controlled_Type_Declarations
21324 @subsection @code{Controlled_Type_Declarations}
21325 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
21326
21327 @noindent
21328 Flag all declarations of controlled types. A declaration of a private type
21329 is flagged if its full declaration declares a controlled type. A declaration
21330 of a derived type is flagged if its ancestor type is controlled. Subtype
21331 declarations are not checked. A declaration of a type that itself is not a
21332 descendant of a type declared in @code{Ada.Finalization} but has a controlled
21333 component is not checked.
21334
21335 This rule has no parameters.
21336
21337
21338 @node Complex_Inlined_Subprograms
21339 @subsection @code{Complex_Inlined_Subprograms}
21340 @cindex @code{Complex_Inlined_Subprograms} rule (for @command{gnatcheck})
21341
21342 @noindent
21343 Flags a subprogram (or generic subprogram) if
21344 pragma Inline is applied to the subprogram and at least one of the following
21345 conditions is met:
21346
21347 @itemize @bullet
21348 @item
21349 it contains at least one complex declaration such as a subprogram body,
21350 package, task, protected declaration, or a generic instantiation
21351 (except instantiation of @code{Ada.Unchecked_Conversion});
21352
21353 @item
21354 it contains at least one complex statement such as a loop, a case
21355 or a if statement, or a short circuit control form;
21356
21357 @item
21358 the number of statements exceeds
21359 a value specified by the @option{N} rule parameter;
21360 @end itemize
21361
21362 @noindent
21363 This rule has the following (mandatory) parameter for the @option{+R} option:
21364
21365 @table @emph
21366 @item N
21367 Positive integer specifying the maximum allowed total number of statements
21368 in the subprogram body.
21369 @end table
21370
21371
21372 @node Declarations_In_Blocks
21373 @subsection @code{Declarations_In_Blocks}
21374 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
21375
21376 @noindent
21377 Flag all block statements containing local declarations. A @code{declare}
21378 block with an empty @i{declarative_part} or with a @i{declarative part}
21379 containing only pragmas and/or @code{use} clauses is not flagged.
21380
21381 This rule has no parameters.
21382
21383
21384 @node Deep_Inheritance_Hierarchies
21385 @subsection @code{Deep_Inheritance_Hierarchies}
21386 @cindex @code{Deep_Inheritance_Hierarchies} rule (for @command{gnatcheck})
21387
21388 @noindent
21389 Flags a tagged derived type declaration or an interface type declaration if
21390 its depth (in its inheritance
21391 hierarchy) exceeds the value specified by the @option{N} rule parameter.
21392
21393 The inheritance depth of a tagged type or interface type is defined as 0 for
21394 a type  with no parent and no progenitor, and otherwise as 1 + max of the
21395 depths of the immediate parent and immediate progenitors.
21396
21397 This rule does not flag private extension
21398 declarations. In the case of a private extension, the corresponding full
21399 declaration is checked.
21400
21401 This rule has the following (mandatory) parameter for the @option{+R} option:
21402
21403 @table @emph
21404 @item N
21405 Integer not less than -1 specifying the maximal allowed depth of any inheritance
21406 hierarchy. If the rule parameter is set to -1, the rule flags all the declarations
21407 of tagged and interface types.
21408 @end table
21409
21410
21411 @node Deeply_Nested_Generics
21412 @subsection @code{Deeply_Nested_Generics}
21413 @cindex @code{Deeply_Nested_Generics} rule (for @command{gnatcheck})
21414
21415 @noindent
21416 Flags a generic declaration nested in another generic declaration if
21417 the nesting level of the inner generic exceeds
21418 a value specified by the @option{N} rule parameter.
21419 The nesting level is the number of generic declaratons that enclose the given
21420 (generic) declaration. Formal packages are not flagged by this rule.
21421
21422 This rule has the following (mandatory) parameters for the @option{+R} option:
21423
21424 @table @emph
21425 @item N
21426 Positive integer specifying the maximal allowed nesting level
21427 for a generic declaration.
21428 @end table
21429
21430 @node Deeply_Nested_Inlining
21431 @subsection @code{Deeply_Nested_Inlining}
21432 @cindex @code{Deeply_Nested_Inlining} rule (for @command{gnatcheck})
21433
21434 @noindent
21435 Flags a subprogram (or generic subprogram) if
21436 pragma Inline has been applied to the subprogram but the subprogram
21437 calls to another inlined subprogram that results in nested inlining
21438 with nesting depth exceeding the value specified by the
21439 @option{N} rule parameter.
21440
21441 This rule requires the global analysis of all the compilation units that
21442 are @command{gnatcheck} arguments; such analysis may affect the tool's
21443 performance.
21444
21445 This rule has the following (mandatory) parameter for the @option{+R} option:
21446
21447 @table @emph
21448 @item N
21449 Positive integer specifying the maximal allowed level of nested inlining.
21450 @end table
21451
21452
21453 @ignore
21454 @node Deeply_Nested_Local_Inlining
21455 @subsection @code{Deeply_Nested_Local_Inlining}
21456 @cindex @code{Deeply_Nested_Local_Inlining} rule (for @command{gnatcheck})
21457
21458 @noindent
21459 Flags a subprogram body if a pragma @code{Inline} is applied to the
21460 corresponding subprogram (or generic subprogram) and the body contains a call
21461 to another inlined subprogram that results in nested inlining with nesting
21462 depth more then a value specified by the @option{N} rule parameter.
21463 This rule is similar to @code{Deeply_Nested_Inlining} rule, but it
21464 assumes that calls to subprograms in
21465 with'ed units are not inlided, so all the analysis of the depth of inlining is
21466 limited by the compilation unit where the subprogram body is located and the
21467 units it depends semantically upon. Such analysis may be usefull for the case
21468 when neiter @option{-gnatn} nor @option{-gnatN} option is used when building
21469 the executable.
21470
21471 This rule has the following (mandatory) parameters for the @option{+R} option:
21472
21473 @table @emph
21474 @item N
21475 Positive integer specifying the maximal allowed level of nested inlining.
21476 @end table
21477
21478 @end ignore
21479
21480 @node Default_Parameters
21481 @subsection @code{Default_Parameters}
21482 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
21483
21484 @noindent
21485 Flag all default expressions for subprogram parameters. Parameter
21486 declarations of formal and generic subprograms are also checked.
21487
21488 This rule has no parameters.
21489
21490
21491 @node Direct_Calls_To_Primitives
21492 @subsection @code{Direct_Calls_To_Primitives}
21493 @cindex @code{Direct_Calls_To_Primitives} rule (for @command{gnatcheck})
21494
21495 @noindent
21496 Flags any non-dispatching call to a dispatching primitive operation, except
21497 for the common idiom where a primitive subprogram for a tagged type
21498 directly calls the same primitive subprogram of the type's immediate ancestor.
21499
21500 This rule has no parameters.
21501
21502
21503 @node Discriminated_Records
21504 @subsection @code{Discriminated_Records}
21505 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
21506
21507 @noindent
21508 Flag all declarations of record types with discriminants. Only the
21509 declarations of record and record extension types are checked. Incomplete,
21510 formal, private, derived and private extension type declarations are not
21511 checked. Task and protected type declarations also are not checked.
21512
21513 This rule has no parameters.
21514
21515
21516 @node Enumeration_Ranges_In_CASE_Statements
21517 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
21518 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
21519
21520 @noindent
21521 Flag each use of a range of enumeration literals as a choice in a
21522 @code{case} statement.
21523 All forms for specifying a range (explicit ranges
21524 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
21525 An enumeration range is
21526 flagged even if contains exactly one enumeration value or no values at all. A
21527 type derived from an enumeration type is considered as an enumeration type.
21528
21529 This rule helps prevent maintenance problems arising from adding an
21530 enumeration value to a type and having it implicitly handled by an existing
21531 @code{case} statement with an enumeration range that includes the new literal.
21532
21533 This rule has no parameters.
21534
21535
21536 @node Exceptions_As_Control_Flow
21537 @subsection @code{Exceptions_As_Control_Flow}
21538 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
21539
21540 @noindent
21541 Flag each place where an exception is explicitly raised and handled in the
21542 same subprogram body. A @code{raise} statement in an exception handler,
21543 package body, task body or entry body is not flagged.
21544
21545 The rule has no parameters.
21546
21547 @node Exits_From_Conditional_Loops
21548 @subsection @code{Exits_From_Conditional_Loops}
21549 @cindex @code{Exits_From_Conditional_Loops} (for @command{gnatcheck})
21550
21551 @noindent
21552 Flag any exit statement if it transfers the control out of a @code{for} loop
21553 or a @code{while} loop. This includes cases when the @code{exit} statement
21554 applies to a @code{FOR} or @code{while} loop, and cases when it is enclosed
21555 in some @code{for} or @code{while} loop, but transfers the control from some
21556 outer (inconditional) @code{loop} statement.
21557
21558 The rule has no parameters.
21559
21560
21561 @node EXIT_Statements_With_No_Loop_Name
21562 @subsection @code{EXIT_Statements_With_No_Loop_Name}
21563 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
21564
21565 @noindent
21566 Flag each @code{exit} statement that does not specify the name of the loop
21567 being exited.
21568
21569 The rule has no parameters.
21570
21571
21572 @node Expanded_Loop_Exit_Names
21573 @subsection @code{Expanded_Loop_Exit_Names}
21574 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
21575
21576 @noindent
21577 Flag all expanded loop names in @code{exit} statements.
21578
21579 This rule has no parameters.
21580
21581 @node Explicit_Full_Discrete_Ranges
21582 @subsection @code{Explicit_Full_Discrete_Ranges}
21583 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
21584
21585 @noindent
21586 Flag each discrete range that has the form @code{A'First .. A'Last}.
21587
21588 This rule has no parameters.
21589
21590 @node Float_Equality_Checks
21591 @subsection @code{Float_Equality_Checks}
21592 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
21593
21594 @noindent
21595 Flag all calls to the predefined equality operations for floating-point types.
21596 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
21597 User-defined equality operations are not flagged, nor are ``@code{=}''
21598 and ``@code{/=}'' operations for fixed-point types.
21599
21600 This rule has no parameters.
21601
21602
21603 @node Forbidden_Attributes
21604 @subsection @code{Forbidden_Attributes}
21605 @cindex @code{Forbidden_Attributes} rule (for @command{gnatcheck})
21606
21607 @noindent
21608 Flag each use of the specified attributes. The attributes to be detected are
21609 named in the rule's parameters.
21610
21611 This rule has the following parameters:
21612
21613 @itemize @bullet
21614 @item For the @option{+R} option
21615
21616 @table @asis
21617 @item @emph{Attribute_Designator}
21618 Adds the specified attribute to the set of attributes to be detected and sets
21619 the detection checks for all the specified attributes ON.
21620 If @emph{Attribute_Designator}
21621 does not denote any attribute defined in the Ada standard
21622 or in
21623 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
21624 Manual}, it is treated as the name of unknown attribute.
21625
21626 @item @code{GNAT}
21627 All the GNAT-specific attributes are detected; this sets
21628 the detection checks for all the specified attributes ON.
21629
21630 @item @code{ALL}
21631 All attributes are detected; this sets the rule ON.
21632 @end table
21633
21634 @item For the @option{-R} option
21635 @table @asis
21636 @item @emph{Attribute_Designator}
21637 Removes the specified attribute from the set of attributes to be
21638 detected without affecting detection checks for
21639 other attributes. If @emph{Attribute_Designator} does not correspond to any
21640 attribute defined in the Ada standard or in
21641 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference Manual},
21642 this option is treated as turning OFF detection of all unknown attributes.
21643
21644 @item GNAT
21645 Turn OFF detection of all GNAT-specific attributes
21646
21647 @item ALL
21648 Clear the list of the attributes to be detected and
21649 turn the rule OFF.
21650 @end table
21651 @end itemize
21652
21653 @noindent
21654 Parameters are not case sensitive. If @emph{Attribute_Designator} does not
21655 have the syntax of an Ada identifier and therefore can not be considered as a
21656 (part of an) attribute designator, a diagnostic message is generated and the
21657 corresponding parameter is ignored. (If an attribute allows a static
21658 expression to be a part of the attribute designator, this expression is
21659 ignored by this rule.)
21660
21661 When more then one parameter is given in the same rule option, the parameters
21662 must be separated by commas.
21663
21664 If more then one option for this rule is specified for the gnatcheck call, a
21665 new option overrides the previous one(s).
21666
21667 The @option{+R} option with no parameters turns the rule ON, with the set of
21668 attributes to be detected defined by the previous rule options.
21669 (By default this set is empty, so if the only option specified for the rule is
21670 @option{+RForbidden_Attributes} (with
21671 no parameter), then the rule is enabled, but it does not detect anything).
21672 The @option{-R} option with no parameter turns the rule OFF, but it does not
21673 affect the set of attributes to be detected.
21674
21675
21676 @node Forbidden_Pragmas
21677 @subsection @code{Forbidden_Pragmas}
21678 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
21679
21680 @noindent
21681 Flag each use of the specified pragmas.  The pragmas to be detected
21682 are named in the rule's  parameters.
21683
21684 This rule has the following parameters:
21685
21686 @itemize @bullet
21687 @item For the @option{+R} option
21688
21689 @table @asis
21690 @item @emph{Pragma_Name}
21691 Adds the specified pragma to the set of pragmas to be
21692 checked and sets the checks for all the specified pragmas
21693 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
21694 does not correspond to any pragma name defined in the Ada
21695 standard or to the name of a GNAT-specific pragma defined
21696 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21697 Manual}, it is treated as the name of unknown pragma.
21698
21699 @item @code{GNAT}
21700 All the GNAT-specific pragmas are detected; this sets
21701 the checks for all the specified pragmas ON.
21702
21703 @item @code{ALL}
21704 All pragmas are detected; this sets the rule ON.
21705 @end table
21706
21707 @item For the @option{-R} option
21708 @table @asis
21709 @item @emph{Pragma_Name}
21710 Removes the specified pragma from the set of pragmas to be
21711 checked without affecting checks for
21712 other pragmas. @emph{Pragma_Name} is treated as a name
21713 of a pragma. If it does not correspond to any pragma
21714 defined in the Ada standard or to any name defined in
21715 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21716 this option is treated as turning OFF detection of all unknown pragmas.
21717
21718 @item GNAT
21719 Turn OFF detection of all GNAT-specific pragmas
21720
21721 @item ALL
21722 Clear the list of the pragmas to be detected and
21723 turn the rule OFF.
21724 @end table
21725 @end itemize
21726
21727 @noindent
21728 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
21729 the syntax of an Ada identifier and therefore can not be considered
21730 as a pragma name, a diagnostic message is generated and the corresponding
21731 parameter is ignored.
21732
21733 When more then one parameter is given in the same rule option, the parameters
21734 must be separated by a comma.
21735
21736 If more then one option for this rule is specified for the @command{gnatcheck}
21737 call, a new option overrides the previous one(s).
21738
21739 The @option{+R} option with no parameters turns the rule ON with the set of
21740 pragmas to be detected defined by the previous rule options.
21741 (By default this set is empty, so if the only option specified for the rule is
21742 @option{+RForbidden_Pragmas} (with
21743 no parameter), then the rule is enabled, but it does not detect anything).
21744 The @option{-R} option with no parameter turns the rule OFF, but it does not
21745 affect the set of pragmas to be detected.
21746
21747
21748
21749
21750 @node Function_Style_Procedures
21751 @subsection @code{Function_Style_Procedures}
21752 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
21753
21754 @noindent
21755 Flag each procedure that can be rewritten as a function. A procedure can be
21756 converted into a function if it has exactly one parameter of mode @code{out}
21757 and no parameters of mode @code{in out}. Procedure declarations,
21758 formal procedure declarations, and generic procedure declarations are always
21759 checked. Procedure
21760 bodies and body stubs are flagged only if they do not have corresponding
21761 separate declarations. Procedure renamings and procedure instantiations are
21762 not flagged.
21763
21764 If a procedure can be rewritten as a function, but its @code{out} parameter is
21765 of a limited type, it is not flagged.
21766
21767 Protected procedures are not flagged. Null procedures also are not flagged.
21768
21769 This rule has no parameters.
21770
21771
21772 @node Generics_In_Subprograms
21773 @subsection @code{Generics_In_Subprograms}
21774 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21775
21776 @noindent
21777 Flag each declaration of a generic unit in a subprogram. Generic
21778 declarations in the bodies of generic subprograms are also flagged.
21779 A generic unit nested in another generic unit is not flagged.
21780 If a generic unit is
21781 declared in a local package that is declared in a subprogram body, the
21782 generic unit is flagged.
21783
21784 This rule has no parameters.
21785
21786
21787 @node GOTO_Statements
21788 @subsection @code{GOTO_Statements}
21789 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21790
21791 @noindent
21792 Flag each occurrence of a @code{goto} statement.
21793
21794 This rule has no parameters.
21795
21796
21797 @node Implicit_IN_Mode_Parameters
21798 @subsection @code{Implicit_IN_Mode_Parameters}
21799 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21800
21801 @noindent
21802 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21803 Note that @code{access} parameters, although they technically behave
21804 like @code{in} parameters, are not flagged.
21805
21806 This rule has no parameters.
21807
21808
21809 @node Implicit_SMALL_For_Fixed_Point_Types
21810 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21811 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21812
21813 @noindent
21814 Flag each fixed point type declaration that lacks an explicit
21815 representation  clause to define its @code{'Small} value.
21816 Since @code{'Small} can be  defined only for ordinary fixed point types,
21817 decimal fixed point type declarations are not checked.
21818
21819 This rule has no parameters.
21820
21821
21822 @node Improperly_Located_Instantiations
21823 @subsection @code{Improperly_Located_Instantiations}
21824 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21825
21826 @noindent
21827 Flag all generic instantiations in library-level package specs
21828 (including library generic packages) and in all subprogram bodies.
21829
21830 Instantiations in task and entry bodies are not flagged. Instantiations in the
21831 bodies of protected subprograms are flagged.
21832
21833 This rule has no parameters.
21834
21835
21836
21837 @node Improper_Returns
21838 @subsection @code{Improper_Returns}
21839 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21840
21841 @noindent
21842 Flag each explicit @code{return} statement in procedures, and
21843 multiple @code{return} statements in functions.
21844 Diagnostic messages are generated for all @code{return} statements
21845 in a procedure (thus each procedure must be written so that it
21846 returns implicitly at the end of its statement part),
21847 and for all @code{return} statements in a function after the first one.
21848 This rule supports the stylistic convention that each subprogram
21849 should have no more than one point of normal return.
21850
21851 This rule has no parameters.
21852
21853
21854 @node Library_Level_Subprograms
21855 @subsection @code{Library_Level_Subprograms}
21856 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21857
21858 @noindent
21859 Flag all library-level subprograms (including generic subprogram instantiations).
21860
21861 This rule has no parameters.
21862
21863
21864 @node Local_Packages
21865 @subsection @code{Local_Packages}
21866 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21867
21868 @noindent
21869 Flag all local packages declared in package and generic package
21870 specs.
21871 Local packages in bodies are not flagged.
21872
21873 This rule has no parameters.
21874
21875 @ignore
21876 @node Improperly_Called_Protected_Entries
21877 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21878 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21879
21880 @noindent
21881 Flag each protected entry that can be called from more than one task.
21882
21883 This rule has no parameters.
21884 @end ignore
21885
21886 @node Metrics
21887 @subsection @code{Metrics}
21888 @cindex @code{Metrics} rule (for @command{gnatcheck})
21889
21890 @noindent
21891 There is a set of checks based on computing a metric value and comparing the
21892 result with the specified upper (or lower, depending on a specific metric)
21893 value specified for a given metric. A construct is flagged if a given metric
21894 is applicable (can be computed) for it and the computed value is greater
21895 then (lover then) the specified upper (lower) bound.
21896
21897 The name of any metric-based rule consists of the prefix @code{Metrics_}
21898 followed by the name of the corresponding metric (see the table below).
21899 For @option{+R} option, each metric-based rule has a numeric parameter
21900 specifying the bound (integer or real, depending on a metric), @option{-R}
21901 option for metric rules does not have a parameter.
21902
21903 The following table shows the metric names for that the corresponding
21904 metrics-based checks are supported by gnatcheck, including the
21905 constraint that must be satisfied by the bound that is specified for the check
21906 and what bound - upper (U) or lower (L) - should be specified.
21907
21908 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21909 @ifnothtml
21910 @headitem Check Name @tab Description @tab Bounds Value
21911 @end ifnothtml
21912 @ifhtml
21913 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21914 @end ifhtml
21915 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21916 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21917 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21918 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21919 @end multitable
21920
21921 @noindent
21922 The meaning and the computed values for all these metrics are exactly
21923 the same as for the corresponding metrics in @command{gnatmetric}.
21924
21925 @emph{Example:} the rule
21926 @smallexample
21927 +RMetrics_Cyclomatic_Complexity : 7
21928 @end smallexample
21929 @noindent
21930 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21931
21932 To turn OFF the check for cyclomatic complexity metric, use the following option:
21933 @smallexample
21934 -RMetrics_Cyclomatic_Complexity
21935 @end smallexample
21936
21937
21938 @node Misnamed_Controlling_Parameters
21939 @subsection @code{Misnamed_Controlling_Parameters}
21940 @cindex @code{Misnamed_Controlling_Parameters} rule (for @command{gnatcheck})
21941
21942 @noindent
21943 Flags a declaration of a dispatching operation, if the first parameter is
21944 not a controlling one and its name is not @code{This} (the check for
21945 parameter name is not case-sensitive). Declarations of dispatching functions
21946 with controlling result and no controlling parameter are never flagged.
21947
21948 A subprogram body declaration, subprogram renaming declaration or subprogram
21949 body stub is flagged only if it is not a completion of a prior subprogram
21950 declaration.
21951
21952 This rule has no parameters.
21953
21954
21955
21956 @node Misnamed_Identifiers
21957 @subsection @code{Misnamed_Identifiers}
21958 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21959
21960 @noindent
21961 Flag the declaration of each identifier that does not have a suffix
21962 corresponding to the kind of entity being declared.
21963 The following declarations are checked:
21964
21965 @itemize @bullet
21966 @item
21967 type declarations
21968
21969 @item
21970 subtype declarations
21971
21972 @item
21973 constant declarations (but not number declarations)
21974
21975 @item
21976 package renaming declarations (but not generic package renaming
21977 declarations)
21978 @end itemize
21979
21980 @noindent
21981 This rule may have parameters. When used without parameters, the rule enforces
21982 the following checks:
21983
21984 @itemize @bullet
21985 @item
21986 type-defining names end with @code{_T}, unless the type is an access type,
21987 in which case the suffix must be @code{_A}
21988 @item
21989 constant names end with @code{_C}
21990 @item
21991 names defining package renamings end with @code{_R}
21992 @end itemize
21993
21994 @noindent
21995 Defining identifiers from incomplete type declarations are never flagged.
21996
21997 For a private type declaration (including private extensions), the defining
21998 identifier from the private type declaration is checked against the type
21999 suffix (even if the corresponding full declaration is an access type
22000 declaration), and the defining identifier from the corresponding full type
22001 declaration is not checked.
22002
22003 @noindent
22004 For a deferred constant, the defining name in the corresponding full constant
22005 declaration is not checked.
22006
22007 Defining names of formal types are not checked.
22008
22009 The rule may have the following parameters:
22010
22011 @itemize @bullet
22012 @item
22013 For the @option{+R} option:
22014 @table @code
22015 @item Default
22016 Sets the default listed above for all the names to be checked.
22017
22018 @item Type_Suffix=@emph{string}
22019 Specifies the suffix for a type name.
22020
22021 @item Access_Suffix=@emph{string}
22022 Specifies the suffix for an access type name. If
22023 this parameter is set, it overrides for access
22024 types the suffix set by the @code{Type_Suffix} parameter.
22025 For access types, @emph{string} may have the following format:
22026 @emph{suffix1(suffix2)}. That means that an access type name
22027 should have the @emph{suffix1} suffix except for the case when
22028 the designated type is also an access type, in this case the
22029 type name should have the @emph{suffix1 & suffix2} suffix.
22030
22031 @item Class_Access_Suffix=@emph{string}
22032 Specifies the suffix for the name of an access type that points to some class-wide
22033 type. If this parameter is set, it overrides for such access
22034 types the suffix set by the @code{Type_Suffix} or @code{Access_Suffix}
22035 parameter.
22036
22037 @item Class_Subtype_Suffix=@emph{string}
22038 Specifies the suffix for the name of a subtype that denotes a class-wide type.
22039
22040 @item Constant_Suffix=@emph{string}
22041 Specifies the suffix for a constant name.
22042
22043 @item Renaming_Suffix=@emph{string}
22044 Specifies the suffix for a package renaming name.
22045 @end table
22046
22047 @item
22048 For the @option{-R} option:
22049 @table @code
22050 @item All_Suffixes
22051 Remove all the suffixes specified for the
22052 identifier suffix checks, whether by default or
22053 as specified by other rule parameters. All the
22054 checks for this rule are disabled as a result.
22055
22056 @item Type_Suffix
22057 Removes the suffix specified for types. This
22058 disables checks for types but does not disable
22059 any other checks for this rule (including the
22060 check for access type names if @code{Access_Suffix} is
22061 set).
22062
22063 @item Access_Suffix
22064 Removes the suffix specified for access types.
22065 This disables checks for access type names but
22066 does not disable any other checks for this rule.
22067 If @code{Type_Suffix} is set, access type names are
22068 checked as ordinary type names.
22069
22070 @item Class_Access_Suffix
22071 Removes the suffix specified for access types pointing to class-wide
22072 type. This disables specific checks for names of access types pointing to
22073 class-wide types but does not disable any other checks for this rule.
22074 If @code{Type_Suffix} is set, access type names are
22075 checked as ordinary type names. If @code{Access_Suffix} is set, these
22076 access types are checked as any other access type name.
22077
22078 @item Class_Subtype_Suffix=@emph{string}
22079 Removes the suffix specified for subtype names.
22080 This disables checks for subtype names but
22081 does not disable any other checks for this rule.
22082
22083 @item Constant_Suffix
22084 Removes the suffix specified for constants. This
22085 disables checks for constant names but does not
22086 disable any other checks for this rule.
22087
22088 @item Renaming_Suffix
22089 Removes the suffix specified for package
22090 renamings. This disables checks for package
22091 renamings but does not disable any other checks
22092 for this rule.
22093 @end table
22094 @end itemize
22095
22096 @noindent
22097 If more than one parameter is used, parameters must be separated by commas.
22098
22099 If more than one  option is specified for the @command{gnatcheck} invocation,
22100 a new option overrides the previous one(s).
22101
22102 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
22103 checks for all the
22104 name suffixes specified by previous options used for this rule.
22105
22106 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
22107 all the checks but keeps
22108 all the suffixes specified by previous options used for this rule.
22109
22110 The @emph{string} value must be a valid suffix for an Ada identifier (after
22111 trimming all the leading and trailing space characters, if any).
22112 Parameters are not case sensitive, except the @emph{string} part.
22113
22114 If any error is detected in a rule parameter, the parameter is ignored.
22115 In such a case the options that are set for the rule are not
22116 specified.
22117
22118
22119
22120 @node Multiple_Entries_In_Protected_Definitions
22121 @subsection @code{Multiple_Entries_In_Protected_Definitions}
22122 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
22123
22124 @noindent
22125 Flag each protected definition (i.e., each protected object/type declaration)
22126 that defines more than one entry.
22127 Diagnostic messages are generated for all the entry declarations
22128 except the first one. An entry family is counted as one entry. Entries from
22129 the private part of the protected definition are also checked.
22130
22131 This rule has no parameters.
22132
22133 @node Name_Clashes
22134 @subsection @code{Name_Clashes}
22135 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
22136
22137 @noindent
22138 Check that certain names are not used as defining identifiers. To activate
22139 this rule, you need to supply a reference to the dictionary file(s) as a rule
22140 parameter(s) (more then one dictionary file can be specified). If no
22141 dictionary file is set, this rule will not cause anything to be flagged.
22142 Only defining occurrences, not references, are checked.
22143 The check is not case-sensitive.
22144
22145 This rule is enabled by default, but without setting any corresponding
22146 dictionary file(s); thus the default effect is to do no checks.
22147
22148 A dictionary file is a plain text file. The maximum line length for this file
22149 is 1024 characters.  If the line is longer then this limit, extra characters
22150 are ignored.
22151
22152 Each line can be either an empty line, a comment line, or a line containing
22153 a list of identifiers separated by space or HT characters.
22154 A comment is an Ada-style comment (from @code{--} to end-of-line).
22155 Identifiers must follow the Ada syntax for identifiers.
22156 A line containing one or more identifiers may end with a comment.
22157
22158 @node Non_Qualified_Aggregates
22159 @subsection @code{Non_Qualified_Aggregates}
22160 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
22161
22162 @noindent
22163 Flag each non-qualified aggregate.
22164 A non-qualified aggregate is an
22165 aggregate that is not the expression of a qualified expression. A
22166 string literal is not considered an aggregate, but an array
22167 aggregate of a string type is considered as a normal aggregate.
22168 Aggregates of anonymous array types are not flagged.
22169
22170 This rule has no parameters.
22171
22172
22173 @node Non_Short_Circuit_Operators
22174 @subsection @code{Non_Short_Circuit_Operators}
22175 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
22176
22177 @noindent
22178 Flag all calls to predefined @code{and} and @code{or} operators for
22179 any boolean type. Calls to
22180 user-defined @code{and} and @code{or} and to operators defined by renaming
22181 declarations are not flagged. Calls to predefined @code{and} and @code{or}
22182 operators for modular types or boolean array types are not flagged.
22183
22184 This rule has no parameters.
22185
22186
22187
22188 @node Non_SPARK_Attributes
22189 @subsection @code{Non_SPARK_Attributes}
22190 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
22191
22192 @noindent
22193 The SPARK language defines the following subset of Ada 95 attribute
22194 designators as those that can be used in SPARK programs. The use of
22195 any other attribute is flagged.
22196
22197 @itemize @bullet
22198 @item @code{'Adjacent}
22199 @item @code{'Aft}
22200 @item @code{'Base}
22201 @item @code{'Ceiling}
22202 @item @code{'Component_Size}
22203 @item @code{'Compose}
22204 @item @code{'Copy_Sign}
22205 @item @code{'Delta}
22206 @item @code{'Denorm}
22207 @item @code{'Digits}
22208 @item @code{'Exponent}
22209 @item @code{'First}
22210 @item @code{'Floor}
22211 @item @code{'Fore}
22212 @item @code{'Fraction}
22213 @item @code{'Last}
22214 @item @code{'Leading_Part}
22215 @item @code{'Length}
22216 @item @code{'Machine}
22217 @item @code{'Machine_Emax}
22218 @item @code{'Machine_Emin}
22219 @item @code{'Machine_Mantissa}
22220 @item @code{'Machine_Overflows}
22221 @item @code{'Machine_Radix}
22222 @item @code{'Machine_Rounds}
22223 @item @code{'Max}
22224 @item @code{'Min}
22225 @item @code{'Model}
22226 @item @code{'Model_Emin}
22227 @item @code{'Model_Epsilon}
22228 @item @code{'Model_Mantissa}
22229 @item @code{'Model_Small}
22230 @item @code{'Modulus}
22231 @item @code{'Pos}
22232 @item @code{'Pred}
22233 @item @code{'Range}
22234 @item @code{'Remainder}
22235 @item @code{'Rounding}
22236 @item @code{'Safe_First}
22237 @item @code{'Safe_Last}
22238 @item @code{'Scaling}
22239 @item @code{'Signed_Zeros}
22240 @item @code{'Size}
22241 @item @code{'Small}
22242 @item @code{'Succ}
22243 @item @code{'Truncation}
22244 @item @code{'Unbiased_Rounding}
22245 @item @code{'Val}
22246 @item @code{'Valid}
22247 @end itemize
22248
22249 @noindent
22250 This rule has no parameters.
22251
22252
22253 @node Non_Tagged_Derived_Types
22254 @subsection @code{Non_Tagged_Derived_Types}
22255 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
22256
22257 @noindent
22258 Flag all derived type declarations that do not have a record extension part.
22259
22260 This rule has no parameters.
22261
22262
22263
22264 @node Non_Visible_Exceptions
22265 @subsection @code{Non_Visible_Exceptions}
22266 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
22267
22268 @noindent
22269 Flag constructs leading to the possibility of propagating an exception
22270 out of the scope in which the exception is declared.
22271 Two cases are detected:
22272
22273 @itemize @bullet
22274 @item
22275 An exception declaration in a subprogram body, task body or block
22276 statement is flagged if the body or statement does not contain a handler for
22277 that exception or a handler with an @code{others} choice.
22278
22279 @item
22280 A @code{raise} statement in an exception handler of a subprogram body,
22281 task body or block statement is flagged if it (re)raises a locally
22282 declared exception.  This may occur under the following circumstances:
22283 @itemize @minus
22284 @item
22285 it explicitly raises a locally declared exception, or
22286 @item
22287 it does not specify an exception name (i.e., it is simply @code{raise;})
22288 and the enclosing handler contains a locally declared exception in its
22289 exception choices.
22290 @end itemize
22291 @end itemize
22292
22293 @noindent
22294 Renamings of local exceptions are not flagged.
22295
22296 This rule has no parameters.
22297
22298
22299 @node Numeric_Literals
22300 @subsection @code{Numeric_Literals}
22301 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
22302
22303 @noindent
22304 Flag each use of a numeric literal in an index expression, and in any
22305 circumstance except for the following:
22306
22307 @itemize @bullet
22308 @item
22309 a literal occurring in the initialization expression for a constant
22310 declaration or a named number declaration, or
22311
22312 @item
22313 an integer literal that is less than or equal to a value
22314 specified by the @option{N} rule parameter.
22315 @end itemize
22316
22317 @noindent
22318 This rule may have the following parameters for the @option{+R} option:
22319
22320 @table @asis
22321 @item @emph{N}
22322 @emph{N} is an integer literal used as the maximal value that is not flagged
22323 (i.e., integer literals not exceeding this value are allowed)
22324
22325 @item @code{ALL}
22326 All integer literals are flagged
22327 @end table
22328
22329 @noindent
22330 If no parameters are set, the maximum unflagged value is 1.
22331
22332 The last specified check limit (or the fact that there is no limit at
22333 all) is used when multiple @option{+R} options appear.
22334
22335 The @option{-R} option for this rule has no parameters.
22336 It disables the rule but retains the last specified maximum unflagged value.
22337 If the @option{+R} option subsequently appears, this value is used as the
22338 threshold for the check.
22339
22340
22341 @node OTHERS_In_Aggregates
22342 @subsection @code{OTHERS_In_Aggregates}
22343 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
22344
22345 @noindent
22346 Flag each use of an @code{others} choice in extension aggregates.
22347 In record and array aggregates, an @code{others} choice is flagged unless
22348 it is used to refer to all components, or to all but one component.
22349
22350 If, in case of a named array aggregate, there are two associations, one
22351 with an @code{others} choice and another with a discrete range, the
22352 @code{others} choice is flagged even if the discrete range specifies
22353 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
22354
22355 This rule has no parameters.
22356
22357 @node OTHERS_In_CASE_Statements
22358 @subsection @code{OTHERS_In_CASE_Statements}
22359 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
22360
22361 @noindent
22362 Flag any use of an @code{others} choice in a @code{case} statement.
22363
22364 This rule has no parameters.
22365
22366 @node OTHERS_In_Exception_Handlers
22367 @subsection @code{OTHERS_In_Exception_Handlers}
22368 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
22369
22370 @noindent
22371 Flag any use of an @code{others} choice in an exception handler.
22372
22373 This rule has no parameters.
22374
22375
22376 @node Outer_Loop_Exits
22377 @subsection @code{Outer_Loop_Exits}
22378 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
22379
22380 @noindent
22381 Flag each @code{exit} statement containing a loop name that is not the name
22382 of the immediately enclosing @code{loop} statement.
22383
22384 This rule has no parameters.
22385
22386
22387 @node Overloaded_Operators
22388 @subsection @code{Overloaded_Operators}
22389 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
22390
22391 @noindent
22392 Flag each function declaration that overloads an operator symbol.
22393 A function body is checked only if the body does not have a
22394 separate spec. Formal functions are also checked. For a
22395 renaming declaration, only renaming-as-declaration is checked
22396
22397 This rule has no parameters.
22398
22399
22400 @node Overly_Nested_Control_Structures
22401 @subsection @code{Overly_Nested_Control_Structures}
22402 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
22403
22404 @noindent
22405 Flag each control structure whose nesting level exceeds the value provided
22406 in the rule parameter.
22407
22408 The control structures checked are the following:
22409
22410 @itemize @bullet
22411 @item    @code{if} statement
22412 @item    @code{case} statement
22413 @item    @code{loop} statement
22414 @item    Selective accept statement
22415 @item    Timed entry call statement
22416 @item    Conditional entry call
22417 @item    Asynchronous select statement
22418 @end itemize
22419
22420 @noindent
22421 The rule has the following parameter for the @option{+R} option:
22422
22423 @table @emph
22424 @item N
22425 Positive integer specifying the maximal control structure nesting
22426 level that is not flagged
22427 @end table
22428
22429 @noindent
22430 If the parameter for the @option{+R} option is not specified or
22431 if it is not a positive integer, @option{+R} option is ignored.
22432
22433 If more then one  option is specified for the gnatcheck call, the later option and
22434 new parameter override the previous one(s).
22435
22436
22437 @node Parameters_Out_Of_Order
22438 @subsection @code{Parameters_Out_Of_Order}
22439 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
22440
22441 @noindent
22442 Flag each subprogram and entry declaration whose formal parameters are not
22443 ordered according to the following scheme:
22444
22445 @itemize @bullet
22446
22447 @item @code{in} and @code{access} parameters first,
22448 then @code{in out} parameters,
22449 and then @code{out} parameters;
22450
22451 @item for @code{in} mode, parameters with default initialization expressions
22452 occur last
22453 @end itemize
22454
22455 @noindent
22456 Only the first violation of the described order is flagged.
22457
22458 The following constructs are checked:
22459
22460 @itemize @bullet
22461 @item   subprogram declarations (including null procedures);
22462 @item   generic subprogram declarations;
22463 @item   formal subprogram declarations;
22464 @item   entry declarations;
22465 @item   subprogram bodies and subprogram body stubs that do not
22466 have separate specifications
22467 @end itemize
22468
22469 @noindent
22470 Subprogram renamings are not checked.
22471
22472 This rule has no parameters.
22473
22474
22475 @node Positional_Actuals_For_Defaulted_Generic_Parameters
22476 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
22477 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
22478
22479 @noindent
22480 Flag each generic actual parameter corresponding to a generic formal
22481 parameter with a default initialization, if positional notation is used.
22482
22483 This rule has no parameters.
22484
22485 @node Positional_Actuals_For_Defaulted_Parameters
22486 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
22487 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
22488
22489 @noindent
22490 Flag each actual parameter to a subprogram or entry call where the
22491 corresponding formal parameter has a default expression, if positional
22492 notation is used.
22493
22494 This rule has no parameters.
22495
22496 @node Positional_Components
22497 @subsection @code{Positional_Components}
22498 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
22499
22500 @noindent
22501 Flag each array, record and extension aggregate that includes positional
22502 notation.
22503
22504 This rule has no parameters.
22505
22506
22507 @node Positional_Generic_Parameters
22508 @subsection @code{Positional_Generic_Parameters}
22509 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
22510
22511 @noindent
22512 Flag each instantiation using positional parameter notation.
22513
22514 This rule has no parameters.
22515
22516
22517 @node Positional_Parameters
22518 @subsection @code{Positional_Parameters}
22519 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
22520
22521 @noindent
22522 Flag each subprogram or entry call using positional parameter notation,
22523 except for the following:
22524
22525 @itemize @bullet
22526 @item
22527 Invocations of prefix or infix operators are not flagged
22528 @item
22529 If the called subprogram or entry has only one formal parameter,
22530 the call is not flagged;
22531 @item
22532 If a subprogram call uses the @emph{Object.Operation} notation, then
22533 @itemize @minus
22534 @item
22535 the first parameter (that is, @emph{Object}) is not flagged;
22536 @item
22537 if the called subprogram has only two parameters, the second parameter
22538 of the call is not flagged;
22539 @end itemize
22540 @end itemize
22541
22542 @noindent
22543 This rule has no parameters.
22544
22545
22546
22547
22548 @node Predefined_Numeric_Types
22549 @subsection @code{Predefined_Numeric_Types}
22550 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
22551
22552 @noindent
22553 Flag each explicit use of the name of any numeric type or subtype defined
22554 in package @code{Standard}.
22555
22556 The rationale for this rule is to detect when the
22557 program may depend on platform-specific characteristics of the implementation
22558 of the predefined numeric types. Note that this rule is over-pessimistic;
22559 for example, a program that uses @code{String} indexing
22560 likely needs a variable of type @code{Integer}.
22561 Another example is the flagging of predefined numeric types with explicit
22562 constraints:
22563
22564 @smallexample @c ada
22565     subtype My_Integer is Integer range Left .. Right;
22566     Vy_Var : My_Integer;
22567 @end smallexample
22568
22569 @noindent
22570 This rule detects only numeric types and subtypes defined in
22571 @code{Standard}. The use of numeric types and subtypes defined in other
22572 predefined packages (such as @code{System.Any_Priority} or
22573 @code{Ada.Text_IO.Count}) is not flagged
22574
22575 This rule has no parameters.
22576
22577
22578
22579 @node Raising_External_Exceptions
22580 @subsection @code{Raising_External_Exceptions}
22581 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
22582
22583 @noindent
22584 Flag any @code{raise} statement, in a program unit declared in a library
22585 package or in a generic library package, for an exception that is
22586 neither a predefined exception nor an exception that is also declared (or
22587 renamed) in the visible part of the package.
22588
22589 This rule has no parameters.
22590
22591
22592
22593 @node Raising_Predefined_Exceptions
22594 @subsection @code{Raising_Predefined_Exceptions}
22595 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
22596
22597 @noindent
22598 Flag each @code{raise} statement that raises a predefined exception
22599 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
22600 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
22601
22602 This rule has no parameters.
22603
22604 @node Separate_Numeric_Error_Handlers
22605 @subsection @code{Separate_Numeric_Error_Handlers}
22606 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
22607
22608 @noindent
22609 Flags each exception handler that contains a choice for
22610 the predefined @code{Constraint_Error} exception, but does not contain
22611 the choice for the predefined @code{Numeric_Error} exception, or
22612 that contains the choice for @code{Numeric_Error}, but does not contain the
22613 choice for @code{Constraint_Error}.
22614
22615 This rule has no parameters.
22616
22617 @ignore
22618 @node Recursion
22619 @subsection @code{Recursion} (under construction, GLOBAL)
22620 @cindex @code{Recursion} rule (for @command{gnatcheck})
22621
22622 @noindent
22623 Flag recursive subprograms (cycles in the call graph). Declarations, and not
22624 calls, of recursive subprograms are detected.
22625
22626 This rule has no parameters.
22627 @end ignore
22628
22629 @ignore
22630 @node Side_Effect_Functions
22631 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
22632 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
22633
22634 @noindent
22635 Flag functions with side effects.
22636
22637 We define a side effect as changing any data object that is not local for the
22638 body of this function.
22639
22640 At the moment, we do NOT consider a side effect any input-output operations
22641 (changing a state or a content of any file).
22642
22643 We do not consider protected functions for this rule (???)
22644
22645 There are the following sources of side effect:
22646
22647 @enumerate
22648 @item Explicit (or direct) side-effect:
22649
22650 @itemize @bullet
22651 @item
22652 direct assignment to a non-local variable;
22653
22654 @item
22655 direct call to an entity that is known to change some data object that is
22656      not local for the body of this function (Note, that if F1 calls F2 and F2
22657      does have a side effect, this does not automatically mean that F1 also
22658      have a side effect, because it may be the case that F2 is declared in
22659      F1's body and it changes some data object that is global for F2, but
22660      local for F1);
22661 @end itemize
22662
22663 @item Indirect side-effect:
22664 @itemize @bullet
22665 @item
22666 Subprogram calls implicitly issued by:
22667 @itemize @bullet
22668 @item
22669 computing initialization expressions from type declarations as a part
22670          of object elaboration or allocator evaluation;
22671 @item
22672 computing implicit parameters of subprogram or entry calls or generic
22673          instantiations;
22674 @end itemize
22675
22676 @item
22677 activation of a task that change some non-local data object (directly or
22678      indirectly);
22679
22680 @item
22681 elaboration code of a package that is a result of a package instantiation;
22682
22683 @item
22684 controlled objects;
22685 @end itemize
22686
22687 @item Situations when we can suspect a side-effect, but the full static check
22688 is either impossible or too hard:
22689 @itemize @bullet
22690 @item
22691 assignment to access variables or to the objects pointed by access
22692      variables;
22693
22694 @item
22695 call to a subprogram pointed by access-to-subprogram value
22696
22697 @item
22698 dispatching calls;
22699 @end itemize
22700 @end enumerate
22701
22702 @noindent
22703 This rule has no parameters.
22704 @end ignore
22705
22706 @node Slices
22707 @subsection @code{Slices}
22708 @cindex @code{Slices} rule (for @command{gnatcheck})
22709
22710 @noindent
22711 Flag all uses of array slicing
22712
22713 This rule has no parameters.
22714
22715
22716 @node Too_Many_Parents
22717 @subsection @code{Too_Many_Parents}
22718 @cindex @code{Too_Many_Parents} rule (for @command{gnatcheck})
22719
22720 @noindent
22721 Flags any type declaration, single task declaration or single protected
22722 declaration that has more then  @option{N} parents,  @option{N} is a parameter
22723 of the rule.
22724 A parent here is either a (sub)type denoted by the subtype mark from the
22725 parent_subtype_indication (in case of a derived type declaration), or
22726 any of the progenitors from the interface list, if any.
22727
22728 This rule has the following (mandatory) parameters for the @option{+R} option:
22729
22730 @table @emph
22731 @item N
22732 Positive integer specifying the maximal allowed number of parents.
22733 @end table
22734
22735
22736 @node Unassigned_OUT_Parameters
22737 @subsection @code{Unassigned_OUT_Parameters}
22738 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
22739
22740 @noindent
22741 Flags procedures' @code{out} parameters that are not assigned, and
22742 identifies the contexts in which the assignments are missing.
22743
22744 An @code{out} parameter is flagged in the statements in the procedure
22745 body's handled sequence of statements (before the procedure body's
22746 @code{exception} part, if any) if this sequence of statements contains
22747 no assignments to the parameter.
22748
22749 An @code{out} parameter is flagged in an exception handler in the exception
22750 part of the procedure body's handled sequence of statements if the handler
22751 contains no assignment to the parameter.
22752
22753 Bodies of generic procedures are also considered.
22754
22755 The following are treated as assignments to an @code{out} parameter:
22756
22757 @itemize @bullet
22758 @item
22759 an assignment statement, with the parameter or some component as the target;
22760
22761 @item
22762 passing the parameter (or one of its components) as an @code{out} or
22763 @code{in out} parameter.
22764 @end itemize
22765
22766 @noindent
22767 This rule does not have any parameters.
22768
22769
22770
22771 @node Uncommented_BEGIN_In_Package_Bodies
22772 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
22773 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
22774
22775 @noindent
22776 Flags each package body with declarations and a statement part that does not
22777 include a trailing comment on the line containing the @code{begin} keyword;
22778 this trailing comment needs to specify the package name and nothing else.
22779 The @code{begin} is not flagged if the package body does not
22780 contain any declarations.
22781
22782 If the @code{begin} keyword is placed on the
22783 same line as the last declaration or the first statement, it is flagged
22784 independently of whether the line contains a trailing comment. The
22785 diagnostic message is attached to the line containing the first statement.
22786
22787 This rule has no parameters.
22788
22789 @node Unconditional_Exits
22790 @subsection @code{Unconditional_Exits}
22791 @cindex @code{Unconditional_Exits} rule (for @command{gnatcheck})
22792
22793 @noindent
22794 Flag unconditional @code{exit} statements.
22795
22796 This rule has no parameters.
22797
22798 @node Unconstrained_Array_Returns
22799 @subsection @code{Unconstrained_Array_Returns}
22800 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
22801
22802 @noindent
22803 Flag each function returning an unconstrained array. Function declarations,
22804 function bodies (and body stubs) having no separate specifications,
22805 and generic function instantiations are checked.
22806 Function calls and function renamings are
22807 not checked.
22808
22809 Generic function declarations, and function declarations in generic
22810 packages are not checked, instead this rule checks the results of
22811 generic instantiations (that is, expanded specification and expanded
22812 body corresponding to an instantiation).
22813
22814 This rule has no parameters.
22815
22816 @node Universal_Ranges
22817 @subsection @code{Universal_Ranges}
22818 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
22819
22820 @noindent
22821 Flag discrete ranges that are a part of an index constraint, constrained
22822 array definition, or @code{for}-loop parameter specification, and whose bounds
22823 are both of type @i{universal_integer}. Ranges that have at least one
22824 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
22825 or an expression of non-universal type) are not flagged.
22826
22827 This rule has no parameters.
22828
22829
22830 @node Unnamed_Blocks_And_Loops
22831 @subsection @code{Unnamed_Blocks_And_Loops}
22832 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
22833
22834 @noindent
22835 Flag each unnamed block statement and loop statement.
22836
22837 The rule has no parameters.
22838
22839
22840
22841 @ignore
22842 @node Unused_Subprograms
22843 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22844 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22845
22846 @noindent
22847 Flag all unused subprograms.
22848
22849 This rule has no parameters.
22850 @end ignore
22851
22852
22853
22854
22855 @node USE_PACKAGE_Clauses
22856 @subsection @code{USE_PACKAGE_Clauses}
22857 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22858
22859 @noindent
22860 Flag all @code{use} clauses for packages; @code{use type} clauses are
22861 not flagged.
22862
22863 This rule has no parameters.
22864
22865
22866 @node Visible_Components
22867 @subsection @code{Visible_Components}
22868 @cindex @code{Visible_Components} rule (for @command{gnatcheck})
22869
22870 @noindent
22871 Flags all the type declarations located in the visible part of a library
22872 package or a library generic package that can declare a visible component. A
22873 type is considered as declaring a visible component if it contains a record
22874 definition by its own or as a part of a record extension. Type declaration is
22875 flagged even if it contains a record definition that defines no components.
22876
22877 Declarations located in private parts of local (generic) packages are not
22878 flagged. Declarations in private packages are not flagged.
22879
22880 This rule has no parameters.
22881
22882
22883 @node Volatile_Objects_Without_Address_Clauses
22884 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22885 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22886
22887 @noindent
22888 Flag each volatile object that does not have an address clause.
22889
22890 The following check is made: if the pragma @code{Volatile} is applied to a
22891 data object or to its type, then an address clause must
22892 be supplied for this object.
22893
22894 This rule does not check the components of data objects,
22895 array components that are volatile as a result of the pragma
22896 @code{Volatile_Components}, or objects that are volatile because
22897 they are atomic as a result of pragmas @code{Atomic} or
22898 @code{Atomic_Components}.
22899
22900 Only variable declarations, and not constant declarations, are checked.
22901
22902 This rule has no parameters.
22903
22904
22905 @c *********************************
22906 @node Creating Sample Bodies Using gnatstub
22907 @chapter Creating Sample Bodies Using @command{gnatstub}
22908 @findex gnatstub
22909
22910 @noindent
22911 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
22912 for library unit declarations.
22913
22914 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
22915 driver (see @ref{The GNAT Driver and Project Files}).
22916
22917 To create a body stub, @command{gnatstub} has to compile the library
22918 unit declaration. Therefore, bodies can be created only for legal
22919 library units. Moreover, if a library unit depends semantically upon
22920 units located outside the current directory, you have to provide
22921 the source search path when calling @command{gnatstub}, see the description
22922 of @command{gnatstub} switches below.
22923
22924 By default, all the program unit body stubs generated by @code{gnatstub}
22925 raise the predefined @code{Program_Error} exception, which will catch
22926 accidental calls of generated stubs. This behavior can be changed with
22927 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
22928
22929 @menu
22930 * Running gnatstub::
22931 * Switches for gnatstub::
22932 @end menu
22933
22934 @node Running gnatstub
22935 @section Running @command{gnatstub}
22936
22937 @noindent
22938 @command{gnatstub} has the command-line interface of the form
22939
22940 @smallexample
22941 $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
22942 @end smallexample
22943
22944 @noindent
22945 where
22946 @table @var
22947 @item filename
22948 is the name of the source file that contains a library unit declaration
22949 for which a body must be created. The file name may contain the path
22950 information.
22951 The file name does not have to follow the GNAT file name conventions. If the
22952 name
22953 does not follow GNAT file naming conventions, the name of the body file must
22954 be provided
22955 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
22956 If the file name follows the GNAT file naming
22957 conventions and the name of the body file is not provided,
22958 @command{gnatstub}
22959 creates the name
22960 of the body file from the argument file name by replacing the @file{.ads}
22961 suffix
22962 with the @file{.adb} suffix.
22963
22964 @item directory
22965 indicates the directory in which the body stub is to be placed (the default
22966 is the
22967 current directory)
22968
22969 @item switches
22970 is an optional sequence of switches as described in the next section
22971 @end table
22972
22973 @node Switches for gnatstub
22974 @section Switches for @command{gnatstub}
22975
22976 @table @option
22977 @c !sort!
22978
22979 @item ^-f^/FULL^
22980 @cindex @option{^-f^/FULL^} (@command{gnatstub})
22981 If the destination directory already contains a file with the name of the
22982 body file
22983 for the argument spec file, replace it with the generated body stub.
22984
22985 @item ^-hs^/HEADER=SPEC^
22986 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
22987 Put the comment header (i.e., all the comments preceding the
22988 compilation unit) from the source of the library unit declaration
22989 into the body stub.
22990
22991 @item ^-hg^/HEADER=GENERAL^
22992 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
22993 Put a sample comment header into the body stub.
22994
22995 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
22996 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
22997 Use the content of the file as the comment header for a generated body stub.
22998
22999 @ifclear vms
23000 @item -IDIR
23001 @cindex @option{-IDIR} (@command{gnatstub})
23002 @itemx -I-
23003 @cindex @option{-I-} (@command{gnatstub})
23004 @end ifclear
23005 @ifset vms
23006 @item /NOCURRENT_DIRECTORY
23007 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
23008 @end ifset
23009 ^These switches have ^This switch has^ the same meaning as in calls to
23010 @command{gcc}.
23011 ^They define ^It defines ^ the source search path in the call to
23012 @command{gcc} issued
23013 by @command{gnatstub} to compile an argument source file.
23014
23015 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
23016 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
23017 This switch has the same meaning as in calls to @command{gcc}.
23018 It defines the additional configuration file to be passed to the call to
23019 @command{gcc} issued
23020 by @command{gnatstub} to compile an argument source file.
23021
23022 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
23023 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
23024 (@var{n} is a non-negative integer). Set the maximum line length in the
23025 body stub to @var{n}; the default is 79. The maximum value that can be
23026 specified is 32767. Note that in the special case of configuration
23027 pragma files, the maximum is always 32767 regardless of whether or
23028 not this switch appears.
23029
23030 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
23031 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
23032 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
23033 the generated body sample to @var{n}.
23034 The default indentation is 3.
23035
23036 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
23037 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
23038 Order local bodies alphabetically. (By default local bodies are ordered
23039 in the same way as the corresponding local specs in the argument spec file.)
23040
23041 @item ^-i^/INDENTATION=^@var{n}
23042 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
23043 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
23044
23045 @item ^-k^/TREE_FILE=SAVE^
23046 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
23047 Do not remove the tree file (i.e., the snapshot of the compiler internal
23048 structures used by @command{gnatstub}) after creating the body stub.
23049
23050 @item ^-l^/LINE_LENGTH=^@var{n}
23051 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
23052 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
23053
23054 @item ^--no-exception^/NO_EXCEPTION^
23055 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
23056 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
23057 This is not always possible for function stubs.
23058
23059 @item ^--no-local-header^/NO_LOCAL_HEADER^
23060 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
23061 Do not place local comment header with unit name before body stub for a
23062 unit.
23063
23064 @item ^-o ^/BODY=^@var{body-name}
23065 @cindex @option{^-o^/BODY^} (@command{gnatstub})
23066 Body file name.  This should be set if the argument file name does not
23067 follow
23068 the GNAT file naming
23069 conventions. If this switch is omitted the default name for the body will be
23070 obtained
23071 from the argument file name according to the GNAT file naming conventions.
23072
23073 @item ^-q^/QUIET^
23074 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
23075 Quiet mode: do not generate a confirmation when a body is
23076 successfully created, and do not generate a message when a body is not
23077 required for an
23078 argument unit.
23079
23080 @item ^-r^/TREE_FILE=REUSE^
23081 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
23082 Reuse the tree file (if it exists) instead of creating it.  Instead of
23083 creating the tree file for the library unit declaration, @command{gnatstub}
23084 tries to find it in the current directory and use it for creating
23085 a body. If the tree file is not found, no body is created. This option
23086 also implies @option{^-k^/SAVE^}, whether or not
23087 the latter is set explicitly.
23088
23089 @item ^-t^/TREE_FILE=OVERWRITE^
23090 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
23091 Overwrite the existing tree file.  If the current directory already
23092 contains the file which, according to the GNAT file naming rules should
23093 be considered as a tree file for the argument source file,
23094 @command{gnatstub}
23095 will refuse to create the tree file needed to create a sample body
23096 unless this option is set.
23097
23098 @item ^-v^/VERBOSE^
23099 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
23100 Verbose mode: generate version information.
23101
23102 @end table
23103
23104 @c *********************************
23105 @node Generating Ada Bindings for C and C++ headers
23106 @chapter Generating Ada Bindings for C and C++ headers
23107 @findex binding
23108
23109 @noindent
23110 GNAT now comes with a new experimental binding generator for C and C++
23111 headers which is intended to do 95% of the tedious work of generating
23112 Ada specs from C or C++ header files. Note that this still is a work in
23113 progress, not designed to generate 100% correct Ada specs.
23114
23115 The code generated is using the Ada 2005 syntax, which makes it
23116 easier to interface with other languages than previous versions of Ada.
23117
23118 @menu
23119 * Running the binding generator::
23120 * Generating bindings for C++ headers::
23121 * Switches::
23122 @end menu
23123
23124 @node Running the binding generator
23125 @section Running the binding generator
23126
23127 @noindent
23128 The binding generator is part of the @command{gcc} compiler and can be
23129 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
23130 spec files for the header files specified on the command line, and all
23131 header files needed by these files transitivitely. For example:
23132
23133 @smallexample
23134 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
23135 $ gcc -c -gnat05 *.ads
23136 @end smallexample
23137
23138 will generate, under GNU/Linux, the following files: @file{time_h.ads},
23139 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
23140 correspond to the files @file{/usr/include/time.h},
23141 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
23142 mode these Ada specs.
23143
23144 The @code{-C} switch tells @command{gcc} to extract comments from headers,
23145 and will attempt to generate corresponding Ada comments.
23146
23147 If you want to generate a single Ada file and not the transitive closure, you
23148 can use instead the @option{-fdump-ada-spec-slim} switch.
23149
23150 Note that we recommend when possible to use the @command{g++} driver to
23151 generate bindings, even for most C headers, since this will in general
23152 generate better Ada specs. For generating bindings for C++ headers, it is
23153 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
23154 is equivalent in this case. If @command{g++} cannot work on your C headers
23155 because of incompatibilities between C and C++, then you can fallback to
23156 @command{gcc} instead.
23157
23158 For an example of better bindings generated from the C++ front-end,
23159 the name of the parameters (when available) are actually ignored by the C
23160 front-end. Consider the following C header:
23161
23162 @smallexample
23163 extern void foo (int variable);
23164 @end smallexample
23165
23166 with the C front-end, @code{variable} is ignored, and the above is handled as:
23167
23168 @smallexample
23169 extern void foo (int);
23170 @end smallexample
23171
23172 generating a generic:
23173
23174 @smallexample
23175 procedure foo (param1 : int);
23176 @end smallexample
23177
23178 with the C++ front-end, the name is available, and we generate:
23179
23180 @smallexample
23181 procedure foo (variable : int);
23182 @end smallexample
23183
23184 In some cases, the generated bindings will be more complete or more meaningful
23185 when defining some macros, which you can do via the @option{-D} switch. This
23186 is for example the case with @file{Xlib.h} under GNU/Linux:
23187
23188 @smallexample
23189 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
23190 @end smallexample
23191
23192 The above will generate more complete bindings than a straight call without
23193 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
23194
23195 In other cases, it is not possible to parse a header file in a stand alone
23196 manner, because other include files need to be included first. In this
23197 case, the solution is to create a small header file including the needed
23198 @code{#include} and possible @code{#define} directives. For example, to
23199 generate Ada bindings for @file{readline/readline.h}, you need to first
23200 include @file{stdio.h}, so you can create a file with the following two
23201 lines in e.g. @file{readline1.h}:
23202
23203 @smallexample
23204 #include <stdio.h>
23205 #include <readline/readline.h>
23206 @end smallexample
23207
23208 and then generate Ada bindings from this file:
23209
23210 @smallexample
23211 $ g++ -c -fdump-ada-spec readline1.h
23212 @end smallexample
23213
23214 @node Generating bindings for C++ headers
23215 @section Generating bindings for C++ headers
23216
23217 @noindent
23218 Generating bindings for C++ headers is done using the same options, always
23219 with the @command{g++} compiler.
23220
23221 In this mode, C++ classes will be mapped to Ada tagged types, constructors
23222 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
23223 multiple inheritance of abstract classes will be mapped to Ada interfaces
23224 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
23225 information on interfacing to C++).
23226
23227 For example, given the following C++ header file:
23228
23229 @smallexample
23230 @group
23231 @cartouche
23232 class Carnivore @{
23233 public:
23234    virtual int Number_Of_Teeth () = 0;
23235 @};
23236
23237 class Domestic @{
23238 public:
23239    virtual void Set_Owner (char* Name) = 0;
23240 @};
23241
23242 class Animal @{
23243 public:
23244   int Age_Count;
23245   virtual void Set_Age (int New_Age);
23246 @};
23247
23248 class Dog : Animal, Carnivore, Domestic @{
23249  public:
23250   int  Tooth_Count;
23251   char *Owner;
23252
23253   virtual int  Number_Of_Teeth ();
23254   virtual void Set_Owner (char* Name);
23255
23256   Dog();
23257 @};
23258 @end cartouche
23259 @end group
23260 @end smallexample
23261
23262 The corresponding Ada code is generated:
23263
23264 @smallexample @c ada
23265 @group
23266 @cartouche
23267   package Class_Carnivore is
23268     type Carnivore is limited interface;
23269     pragma Import (CPP, Carnivore);
23270
23271     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
23272   end;
23273   use Class_Carnivore;
23274
23275   package Class_Domestic is
23276     type Domestic is limited interface;
23277     pragma Import (CPP, Domestic);
23278
23279     procedure Set_Owner
23280       (this : access Domestic;
23281        Name : Interfaces.C.Strings.chars_ptr) is abstract;
23282   end;
23283   use Class_Domestic;
23284
23285   package Class_Animal is
23286     type Animal is tagged limited record
23287       Age_Count : aliased int;
23288     end record;
23289     pragma Import (CPP, Animal);
23290
23291     procedure Set_Age (this : access Animal; New_Age : int);
23292     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
23293   end;
23294   use Class_Animal;
23295
23296   package Class_Dog is
23297     type Dog is new Animal and Carnivore and Domestic with record
23298       Tooth_Count : aliased int;
23299       Owner : Interfaces.C.Strings.chars_ptr;
23300     end record;
23301     pragma Import (CPP, Dog);
23302
23303     function Number_Of_Teeth (this : access Dog) return int;
23304     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
23305
23306     procedure Set_Owner
23307       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
23308     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
23309
23310     function New_Dog return Dog;
23311     pragma CPP_Constructor (New_Dog);
23312     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
23313   end;
23314   use Class_Dog;
23315 @end cartouche
23316 @end group
23317 @end smallexample
23318
23319 @node Switches
23320 @section Switches
23321
23322 @table @option
23323 @item -fdump-ada-spec
23324 @cindex @option{-fdump-ada-spec} (@command{gcc})
23325 Generate Ada spec files for the given header files transitively (including
23326 all header files that these headers depend upon).
23327
23328 @item -fdump-ada-spec-slim
23329 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
23330 Generate Ada spec files for the header files specified on the command line
23331 only.
23332
23333 @item -C
23334 @cindex @option{-C} (@command{gcc})
23335 Extract comments from headers and generate Ada comments in the Ada spec files.
23336 @end table
23337
23338 @node Other Utility Programs
23339 @chapter Other Utility Programs
23340
23341 @noindent
23342 This chapter discusses some other utility programs available in the Ada
23343 environment.
23344
23345 @menu
23346 * Using Other Utility Programs with GNAT::
23347 * The External Symbol Naming Scheme of GNAT::
23348 * Converting Ada Files to html with gnathtml::
23349 * Installing gnathtml::
23350 @ifset vms
23351 * LSE::
23352 * Profiling::
23353 @end ifset
23354 @end menu
23355
23356 @node Using Other Utility Programs with GNAT
23357 @section Using Other Utility Programs with GNAT
23358
23359 @noindent
23360 The object files generated by GNAT are in standard system format and in
23361 particular the debugging information uses this format. This means
23362 programs generated by GNAT can be used with existing utilities that
23363 depend on these formats.
23364
23365 @ifclear vms
23366 In general, any utility program that works with C will also often work with
23367 Ada programs generated by GNAT. This includes software utilities such as
23368 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
23369 as Purify.
23370 @end ifclear
23371
23372 @node The External Symbol Naming Scheme of GNAT
23373 @section The External Symbol Naming Scheme of GNAT
23374
23375 @noindent
23376 In order to interpret the output from GNAT, when using tools that are
23377 originally intended for use with other languages, it is useful to
23378 understand the conventions used to generate link names from the Ada
23379 entity names.
23380
23381 All link names are in all lowercase letters. With the exception of library
23382 procedure names, the mechanism used is simply to use the full expanded
23383 Ada name with dots replaced by double underscores. For example, suppose
23384 we have the following package spec:
23385
23386 @smallexample @c ada
23387 @group
23388 @cartouche
23389 package QRS is
23390    MN : Integer;
23391 end QRS;
23392 @end cartouche
23393 @end group
23394 @end smallexample
23395
23396 @noindent
23397 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
23398 the corresponding link name is @code{qrs__mn}.
23399 @findex Export
23400 Of course if a @code{pragma Export} is used this may be overridden:
23401
23402 @smallexample @c ada
23403 @group
23404 @cartouche
23405 package Exports is
23406    Var1 : Integer;
23407    pragma Export (Var1, C, External_Name => "var1_name");
23408    Var2 : Integer;
23409    pragma Export (Var2, C, Link_Name => "var2_link_name");
23410 end Exports;
23411 @end cartouche
23412 @end group
23413 @end smallexample
23414
23415 @noindent
23416 In this case, the link name for @var{Var1} is whatever link name the
23417 C compiler would assign for the C function @var{var1_name}. This typically
23418 would be either @var{var1_name} or @var{_var1_name}, depending on operating
23419 system conventions, but other possibilities exist. The link name for
23420 @var{Var2} is @var{var2_link_name}, and this is not operating system
23421 dependent.
23422
23423 @findex _main
23424 One exception occurs for library level procedures. A potential ambiguity
23425 arises between the required name @code{_main} for the C main program,
23426 and the name we would otherwise assign to an Ada library level procedure
23427 called @code{Main} (which might well not be the main program).
23428
23429 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
23430 names. So if we have a library level procedure such as
23431
23432 @smallexample @c ada
23433 @group
23434 @cartouche
23435 procedure Hello (S : String);
23436 @end cartouche
23437 @end group
23438 @end smallexample
23439
23440 @noindent
23441 the external name of this procedure will be @var{_ada_hello}.
23442
23443
23444 @node Converting Ada Files to html with gnathtml
23445 @section Converting Ada Files to HTML with @code{gnathtml}
23446
23447 @noindent
23448 This @code{Perl} script allows Ada source files to be browsed using
23449 standard Web browsers. For installation procedure, see the section
23450 @xref{Installing gnathtml}.
23451
23452 Ada reserved keywords are highlighted in a bold font and Ada comments in
23453 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
23454 switch to suppress the generation of cross-referencing information, user
23455 defined variables and types will appear in a different color; you will
23456 be able to click on any identifier and go to its declaration.
23457
23458 The command line is as follow:
23459 @smallexample
23460 $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
23461 @end smallexample
23462
23463 @noindent
23464 You can pass it as many Ada files as you want. @code{gnathtml} will generate
23465 an html file for every ada file, and a global file called @file{index.htm}.
23466 This file is an index of every identifier defined in the files.
23467
23468 The available ^switches^options^ are the following ones:
23469
23470 @table @option
23471 @item -83
23472 @cindex @option{-83} (@code{gnathtml})
23473 Only the Ada 83 subset of keywords will be highlighted.
23474
23475 @item -cc @var{color}
23476 @cindex @option{-cc} (@code{gnathtml})
23477 This option allows you to change the color used for comments. The default
23478 value is green. The color argument can be any name accepted by html.
23479
23480 @item -d
23481 @cindex @option{-d} (@code{gnathtml})
23482 If the Ada files depend on some other files (for instance through
23483 @code{with} clauses, the latter files will also be converted to html.
23484 Only the files in the user project will be converted to html, not the files
23485 in the run-time library itself.
23486
23487 @item -D
23488 @cindex @option{-D} (@code{gnathtml})
23489 This command is the same as @option{-d} above, but @command{gnathtml} will
23490 also look for files in the run-time library, and generate html files for them.
23491
23492 @item -ext @var{extension}
23493 @cindex @option{-ext} (@code{gnathtml})
23494 This option allows you to change the extension of the generated HTML files.
23495 If you do not specify an extension, it will default to @file{htm}.
23496
23497 @item -f
23498 @cindex @option{-f} (@code{gnathtml})
23499 By default, gnathtml will generate html links only for global entities
23500 ('with'ed units, global variables and types,@dots{}).  If you specify
23501 @option{-f} on the command line, then links will be generated for local
23502 entities too.
23503
23504 @item -l @var{number}
23505 @cindex @option{-l} (@code{gnathtml})
23506 If this ^switch^option^ is provided and @var{number} is not 0, then
23507 @code{gnathtml} will number the html files every @var{number} line.
23508
23509 @item -I @var{dir}
23510 @cindex @option{-I} (@code{gnathtml})
23511 Specify a directory to search for library files (@file{.ALI} files) and
23512 source files. You can provide several -I switches on the command line,
23513 and the directories will be parsed in the order of the command line.
23514
23515 @item -o @var{dir}
23516 @cindex @option{-o} (@code{gnathtml})
23517 Specify the output directory for html files. By default, gnathtml will
23518 saved the generated html files in a subdirectory named @file{html/}.
23519
23520 @item -p @var{file}
23521 @cindex @option{-p} (@code{gnathtml})
23522 If you are using Emacs and the most recent Emacs Ada mode, which provides
23523 a full Integrated Development Environment for compiling, checking,
23524 running and debugging applications, you may use @file{.gpr} files
23525 to give the directories where Emacs can find sources and object files.
23526
23527 Using this ^switch^option^, you can tell gnathtml to use these files.
23528 This allows you to get an html version of your application, even if it
23529 is spread over multiple directories.
23530
23531 @item -sc @var{color}
23532 @cindex @option{-sc} (@code{gnathtml})
23533 This ^switch^option^ allows you to change the color used for symbol
23534 definitions.
23535 The default value is red. The color argument can be any name accepted by html.
23536
23537 @item -t @var{file}
23538 @cindex @option{-t} (@code{gnathtml})
23539 This ^switch^option^ provides the name of a file. This file contains a list of
23540 file names to be converted, and the effect is exactly as though they had
23541 appeared explicitly on the command line. This
23542 is the recommended way to work around the command line length limit on some
23543 systems.
23544
23545 @end table
23546
23547 @node Installing gnathtml
23548 @section Installing @code{gnathtml}
23549
23550 @noindent
23551 @code{Perl} needs to be installed on your machine to run this script.
23552 @code{Perl} is freely available for almost every architecture and
23553 Operating System via the Internet.
23554
23555 On Unix systems, you  may want to modify  the  first line of  the script
23556 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
23557 is. The syntax of this line is:
23558 @smallexample
23559 #!full_path_name_to_perl
23560 @end smallexample
23561
23562 @noindent
23563 Alternatively, you may run the script using the following command line:
23564
23565 @smallexample
23566 $ perl gnathtml.pl @ovar{switches} @var{files}
23567 @end smallexample
23568
23569 @ifset vms
23570 @node LSE
23571 @section LSE
23572 @findex LSE
23573
23574 @noindent
23575 The GNAT distribution provides an Ada 95 template for the HP Language
23576 Sensitive Editor (LSE), a component of DECset. In order to
23577 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
23578
23579 @node Profiling
23580 @section Profiling
23581 @findex PCA
23582
23583 @noindent
23584 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
23585 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
23586 the collection phase with the /DEBUG qualifier.
23587
23588 @smallexample
23589 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
23590 $ DEFINE LIB$DEBUG PCA$COLLECTOR
23591 $ RUN/DEBUG <PROGRAM_NAME>
23592 @end smallexample
23593 @noindent
23594 @end ifset
23595
23596 @ifclear vms
23597 @c ******************************
23598 @node Code Coverage and Profiling
23599 @chapter Code Coverage and Profiling
23600 @cindex Code Coverage
23601 @cindex Profiling
23602
23603 @noindent
23604 This chapter describes how to use @code{gcov} - coverage testing tool - and
23605 @code{gprof} - profiler tool - on your Ada programs.
23606
23607 @menu
23608 * Code Coverage of Ada Programs using gcov::
23609 * Profiling an Ada Program using gprof::
23610 @end menu
23611
23612 @node Code Coverage of Ada Programs using gcov
23613 @section Code Coverage of Ada Programs using gcov
23614 @cindex gcov
23615 @cindex -fprofile-arcs
23616 @cindex -ftest-coverage
23617 @cindex -coverage
23618 @cindex Code Coverage
23619
23620 @noindent
23621 @code{gcov} is a test coverage program: it analyzes the execution of a given
23622 program on selected tests, to help you determine the portions of the program
23623 that are still untested.
23624
23625 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
23626 User's Guide. You can refer to this documentation for a more complete
23627 description.
23628
23629 This chapter provides a quick startup guide, and
23630 details some Gnat-specific features.
23631
23632 @menu
23633 * Quick startup guide::
23634 * Gnat specifics::
23635 @end menu
23636
23637 @node Quick startup guide
23638 @subsection Quick startup guide
23639
23640 In order to perform coverage analysis of a program using @code{gcov}, 3
23641 steps are needed:
23642
23643 @itemize @bullet
23644 @item
23645 Code instrumentation during the compilation process
23646 @item
23647 Execution of the instrumented program
23648 @item
23649 Execution of the @code{gcov} tool to generate the result.
23650 @end itemize
23651
23652 The code instrumentation needed by gcov is created at the object level:
23653 The source code is not modified in any way, because the instrumentation code is
23654 inserted by gcc during the compilation process. To compile your code with code
23655 coverage activated, you need to recompile your whole project using the
23656 switches
23657 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
23658 @code{-fprofile-arcs}.
23659
23660 @smallexample
23661 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
23662    -largs -fprofile-arcs
23663 @end smallexample
23664
23665 This compilation process will create @file{.gcno} files together with
23666 the usual object files.
23667
23668 Once the program is compiled with coverage instrumentation, you can
23669 run it as many times as needed - on portions of a test suite for
23670 example. The first execution will produce @file{.gcda} files at the
23671 same location as the @file{.gcno} files.  The following executions
23672 will update those files, so that a cumulative result of the covered
23673 portions of the program is generated.
23674
23675 Finally, you need to call the @code{gcov} tool. The different options of
23676 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
23677
23678 This will create annotated source files with a @file{.gcov} extension:
23679 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
23680
23681 @node Gnat specifics
23682 @subsection Gnat specifics
23683
23684 Because Ada semantics, portions of the source code may be shared among
23685 several object files. This is the case for example when generics are
23686 involved, when inlining is active  or when declarations generate  initialisation
23687 calls. In order to take
23688 into account this shared code, you need to call @code{gcov} on all
23689 source files of the tested program at once.
23690
23691 The list of source files might exceed the system's maximum command line
23692 length. In order to bypass this limitation, a new mechanism has been
23693 implemented in @code{gcov}: you can now list all your project's files into a
23694 text file, and provide this file to gcov as a parameter,  preceded by a @@
23695 (e.g. @samp{gcov @@mysrclist.txt}).
23696
23697 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
23698 not supported as there can be unresolved symbols during the final link.
23699
23700 @node Profiling an Ada Program using gprof
23701 @section Profiling an Ada Program using gprof
23702 @cindex gprof
23703 @cindex -pg
23704 @cindex Profiling
23705
23706 @noindent
23707 This section is not meant to be an exhaustive documentation of @code{gprof}.
23708 Full documentation for it can be found in the GNU Profiler User's Guide
23709 documentation that is part of this GNAT distribution.
23710
23711 Profiling a program helps determine the parts of a program that are executed
23712 most often, and are therefore the most time-consuming.
23713
23714 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
23715 better handle Ada programs and multitasking.
23716 It is currently supported on the following platforms
23717 @itemize @bullet
23718 @item
23719 linux x86/x86_64
23720 @item
23721 solaris sparc/sparc64/x86
23722 @item
23723 windows x86
23724 @end itemize
23725
23726 @noindent
23727 In order to profile a program using @code{gprof}, 3 steps are needed:
23728
23729 @itemize @bullet
23730 @item
23731 Code instrumentation, requiring a full recompilation of the project with the
23732 proper switches.
23733 @item
23734 Execution of the program under the analysis conditions, i.e. with the desired
23735 input.
23736 @item
23737 Analysis of the results using the @code{gprof} tool.
23738 @end itemize
23739
23740 @noindent
23741 The following sections detail the different steps, and indicate how
23742 to interpret the results:
23743 @menu
23744 * Compilation for profiling::
23745 * Program execution::
23746 * Running gprof::
23747 * Interpretation of profiling results::
23748 @end menu
23749
23750 @node Compilation for profiling
23751 @subsection Compilation for profiling
23752 @cindex -pg
23753 @cindex Profiling
23754
23755 In order to profile a program the first step is to tell the compiler
23756 to generate the necessary profiling information. The compiler switch to be used
23757 is @code{-pg}, which must be added to other compilation switches. This
23758 switch needs to be specified both during compilation and link stages, and can
23759 be specified once when using gnatmake:
23760
23761 @smallexample
23762 gnatmake -f -pg -P my_project
23763 @end smallexample
23764
23765 @noindent
23766 Note that only the objects that were compiled with the @samp{-pg} switch will be
23767 profiled; if you need to profile your whole project, use the
23768 @samp{-f} gnatmake switch to force full recompilation.
23769
23770 @node Program execution
23771 @subsection Program execution
23772
23773 @noindent
23774 Once the program has been compiled for profiling, you can run it as usual.
23775
23776 The only constraint imposed by profiling is that the program must terminate
23777 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
23778 properly analyzed.
23779
23780 Once the program completes execution, a data file called @file{gmon.out} is
23781 generated in the directory where the program was launched from. If this file
23782 already exists, it will be overwritten.
23783
23784 @node Running gprof
23785 @subsection Running gprof
23786
23787 @noindent
23788 The @code{gprof} tool is called as follow:
23789
23790 @smallexample
23791 gprof my_prog gmon.out
23792 @end smallexample
23793
23794 @noindent
23795 or simpler:
23796
23797 @smallexample
23798 gprof my_prog
23799 @end smallexample
23800
23801 @noindent
23802 The complete form of the gprof command line is the following:
23803
23804 @smallexample
23805 gprof [^switches^options^] [executable [data-file]]
23806 @end smallexample
23807
23808 @noindent
23809 @code{gprof} supports numerous ^switch^options^. The order of these
23810 ^switch^options^ does not matter. The full list of options can be found in
23811 the GNU Profiler User's Guide documentation that comes with this documentation.
23812
23813 The following is the subset of those switches that is most relevant:
23814
23815 @table @option
23816
23817 @item --demangle[=@var{style}]
23818 @itemx --no-demangle
23819 @cindex @option{--demangle} (@code{gprof})
23820 These options control whether symbol names should be demangled when
23821 printing output.  The default is to demangle C++ symbols.  The
23822 @code{--no-demangle} option may be used to turn off demangling. Different
23823 compilers have different mangling styles.  The optional demangling style
23824 argument can be used to choose an appropriate demangling style for your
23825 compiler, in particular Ada symbols generated by GNAT can be demangled using
23826 @code{--demangle=gnat}.
23827
23828 @item -e @var{function_name}
23829 @cindex @option{-e} (@code{gprof})
23830 The @samp{-e @var{function}} option tells @code{gprof} not to print
23831 information about the function @var{function_name} (and its
23832 children@dots{}) in the call graph.  The function will still be listed
23833 as a child of any functions that call it, but its index number will be
23834 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
23835 given; only one @var{function_name} may be indicated with each @samp{-e}
23836 option.
23837
23838 @item -E @var{function_name}
23839 @cindex @option{-E} (@code{gprof})
23840 The @code{-E @var{function}} option works like the @code{-e} option, but
23841 execution time spent in the function (and children who were not called from
23842 anywhere else), will not be used to compute the percentages-of-time for
23843 the call graph.  More than one @samp{-E} option may be given; only one
23844 @var{function_name} may be indicated with each @samp{-E} option.
23845
23846 @item -f @var{function_name}
23847 @cindex @option{-f} (@code{gprof})
23848 The @samp{-f @var{function}} option causes @code{gprof} to limit the
23849 call graph to the function @var{function_name} and its children (and
23850 their children@dots{}).  More than one @samp{-f} option may be given;
23851 only one @var{function_name} may be indicated with each @samp{-f}
23852 option.
23853
23854 @item -F @var{function_name}
23855 @cindex @option{-F} (@code{gprof})
23856 The @samp{-F @var{function}} option works like the @code{-f} option, but
23857 only time spent in the function and its children (and their
23858 children@dots{}) will be used to determine total-time and
23859 percentages-of-time for the call graph.  More than one @samp{-F} option
23860 may be given; only one @var{function_name} may be indicated with each
23861 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
23862
23863 @end table
23864
23865 @node Interpretation of profiling results
23866 @subsection Interpretation of profiling results
23867
23868 @noindent
23869
23870 The results of the profiling analysis are represented by two arrays: the
23871 'flat profile' and the 'call graph'. Full documentation of those outputs
23872 can be found in the GNU Profiler User's Guide.
23873
23874 The flat profile shows the time spent in each function of the program, and how
23875 many time it has been called. This allows you to locate easily the most
23876 time-consuming functions.
23877
23878 The call graph shows, for each subprogram, the subprograms that call it,
23879 and the subprograms that it calls. It also provides an estimate of the time
23880 spent in each of those callers/called subprograms.
23881 @end ifclear
23882
23883 @c ******************************
23884 @node Running and Debugging Ada Programs
23885 @chapter Running and Debugging Ada Programs
23886 @cindex Debugging
23887
23888 @noindent
23889 This chapter discusses how to debug Ada programs.
23890 @ifset vms
23891 It applies to GNAT on the Alpha OpenVMS platform;
23892 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
23893 since HP has implemented Ada support in the OpenVMS debugger on I64.
23894 @end ifset
23895
23896 An incorrect Ada program may be handled in three ways by the GNAT compiler:
23897
23898 @enumerate
23899 @item
23900 The illegality may be a violation of the static semantics of Ada. In
23901 that case GNAT diagnoses the constructs in the program that are illegal.
23902 It is then a straightforward matter for the user to modify those parts of
23903 the program.
23904
23905 @item
23906 The illegality may be a violation of the dynamic semantics of Ada. In
23907 that case the program compiles and executes, but may generate incorrect
23908 results, or may terminate abnormally with some exception.
23909
23910 @item
23911 When presented with a program that contains convoluted errors, GNAT
23912 itself may terminate abnormally without providing full diagnostics on
23913 the incorrect user program.
23914 @end enumerate
23915
23916 @menu
23917 * The GNAT Debugger GDB::
23918 * Running GDB::
23919 * Introduction to GDB Commands::
23920 * Using Ada Expressions::
23921 * Calling User-Defined Subprograms::
23922 * Using the Next Command in a Function::
23923 * Ada Exceptions::
23924 * Ada Tasks::
23925 * Debugging Generic Units::
23926 * GNAT Abnormal Termination or Failure to Terminate::
23927 * Naming Conventions for GNAT Source Files::
23928 * Getting Internal Debugging Information::
23929 * Stack Traceback::
23930 @end menu
23931
23932 @cindex Debugger
23933 @findex gdb
23934
23935 @node The GNAT Debugger GDB
23936 @section The GNAT Debugger GDB
23937
23938 @noindent
23939 @code{GDB} is a general purpose, platform-independent debugger that
23940 can be used to debug mixed-language programs compiled with @command{gcc},
23941 and in particular is capable of debugging Ada programs compiled with
23942 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
23943 complex Ada data structures.
23944
23945 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
23946 @ifset vms
23947 located in the GNU:[DOCS] directory,
23948 @end ifset
23949 for full details on the usage of @code{GDB}, including a section on
23950 its usage on programs. This manual should be consulted for full
23951 details. The section that follows is a brief introduction to the
23952 philosophy and use of @code{GDB}.
23953
23954 When GNAT programs are compiled, the compiler optionally writes debugging
23955 information into the generated object file, including information on
23956 line numbers, and on declared types and variables. This information is
23957 separate from the generated code. It makes the object files considerably
23958 larger, but it does not add to the size of the actual executable that
23959 will be loaded into memory, and has no impact on run-time performance. The
23960 generation of debug information is triggered by the use of the
23961 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
23962 used to carry out the compilations. It is important to emphasize that
23963 the use of these options does not change the generated code.
23964
23965 The debugging information is written in standard system formats that
23966 are used by many tools, including debuggers and profilers. The format
23967 of the information is typically designed to describe C types and
23968 semantics, but GNAT implements a translation scheme which allows full
23969 details about Ada types and variables to be encoded into these
23970 standard C formats. Details of this encoding scheme may be found in
23971 the file exp_dbug.ads in the GNAT source distribution. However, the
23972 details of this encoding are, in general, of no interest to a user,
23973 since @code{GDB} automatically performs the necessary decoding.
23974
23975 When a program is bound and linked, the debugging information is
23976 collected from the object files, and stored in the executable image of
23977 the program. Again, this process significantly increases the size of
23978 the generated executable file, but it does not increase the size of
23979 the executable program itself. Furthermore, if this program is run in
23980 the normal manner, it runs exactly as if the debug information were
23981 not present, and takes no more actual memory.
23982
23983 However, if the program is run under control of @code{GDB}, the
23984 debugger is activated.  The image of the program is loaded, at which
23985 point it is ready to run.  If a run command is given, then the program
23986 will run exactly as it would have if @code{GDB} were not present. This
23987 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
23988 entirely non-intrusive until a breakpoint is encountered.  If no
23989 breakpoint is ever hit, the program will run exactly as it would if no
23990 debugger were present. When a breakpoint is hit, @code{GDB} accesses
23991 the debugging information and can respond to user commands to inspect
23992 variables, and more generally to report on the state of execution.
23993
23994 @c **************
23995 @node Running GDB
23996 @section Running GDB
23997
23998 @noindent
23999 This section describes how to initiate the debugger.
24000 @c The above sentence is really just filler, but it was otherwise
24001 @c clumsy to get the first paragraph nonindented given the conditional
24002 @c nature of the description
24003
24004 @ifclear vms
24005 The debugger can be launched from a @code{GPS} menu or
24006 directly from the command line. The description below covers the latter use.
24007 All the commands shown can be used in the @code{GPS} debug console window,
24008 but there are usually more GUI-based ways to achieve the same effect.
24009 @end ifclear
24010
24011 The command to run @code{GDB} is
24012
24013 @smallexample
24014 $ ^gdb program^GDB PROGRAM^
24015 @end smallexample
24016
24017 @noindent
24018 where @code{^program^PROGRAM^} is the name of the executable file. This
24019 activates the debugger and results in a prompt for debugger commands.
24020 The simplest command is simply @code{run}, which causes the program to run
24021 exactly as if the debugger were not present. The following section
24022 describes some of the additional commands that can be given to @code{GDB}.
24023
24024 @c *******************************
24025 @node Introduction to GDB Commands
24026 @section Introduction to GDB Commands
24027
24028 @noindent
24029 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
24030 Debugging with GDB, gdb, Debugging with GDB},
24031 @ifset vms
24032 located in the GNU:[DOCS] directory,
24033 @end ifset
24034 for extensive documentation on the use
24035 of these commands, together with examples of their use. Furthermore,
24036 the command @command{help} invoked from within GDB activates a simple help
24037 facility which summarizes the available commands and their options.
24038 In this section we summarize a few of the most commonly
24039 used commands to give an idea of what @code{GDB} is about. You should create
24040 a simple program with debugging information and experiment with the use of
24041 these @code{GDB} commands on the program as you read through the
24042 following section.
24043
24044 @table @code
24045 @item set args @var{arguments}
24046 The @var{arguments} list above is a list of arguments to be passed to
24047 the program on a subsequent run command, just as though the arguments
24048 had been entered on a normal invocation of the program. The @code{set args}
24049 command is not needed if the program does not require arguments.
24050
24051 @item run
24052 The @code{run} command causes execution of the program to start from
24053 the beginning. If the program is already running, that is to say if
24054 you are currently positioned at a breakpoint, then a prompt will ask
24055 for confirmation that you want to abandon the current execution and
24056 restart.
24057
24058 @item breakpoint @var{location}
24059 The breakpoint command sets a breakpoint, that is to say a point at which
24060 execution will halt and @code{GDB} will await further
24061 commands. @var{location} is
24062 either a line number within a file, given in the format @code{file:linenumber},
24063 or it is the name of a subprogram. If you request that a breakpoint be set on
24064 a subprogram that is overloaded, a prompt will ask you to specify on which of
24065 those subprograms you want to breakpoint. You can also
24066 specify that all of them should be breakpointed. If the program is run
24067 and execution encounters the breakpoint, then the program
24068 stops and @code{GDB} signals that the breakpoint was encountered by
24069 printing the line of code before which the program is halted.
24070
24071 @item breakpoint exception @var{name}
24072 A special form of the breakpoint command which breakpoints whenever
24073 exception @var{name} is raised.
24074 If @var{name} is omitted,
24075 then a breakpoint will occur when any exception is raised.
24076
24077 @item print @var{expression}
24078 This will print the value of the given expression. Most simple
24079 Ada expression formats are properly handled by @code{GDB}, so the expression
24080 can contain function calls, variables, operators, and attribute references.
24081
24082 @item continue
24083 Continues execution following a breakpoint, until the next breakpoint or the
24084 termination of the program.
24085
24086 @item step
24087 Executes a single line after a breakpoint. If the next statement
24088 is a subprogram call, execution continues into (the first statement of)
24089 the called subprogram.
24090
24091 @item next
24092 Executes a single line. If this line is a subprogram call, executes and
24093 returns from the call.
24094
24095 @item list
24096 Lists a few lines around the current source location. In practice, it
24097 is usually more convenient to have a separate edit window open with the
24098 relevant source file displayed. Successive applications of this command
24099 print subsequent lines. The command can be given an argument which is a
24100 line number, in which case it displays a few lines around the specified one.
24101
24102 @item backtrace
24103 Displays a backtrace of the call chain. This command is typically
24104 used after a breakpoint has occurred, to examine the sequence of calls that
24105 leads to the current breakpoint. The display includes one line for each
24106 activation record (frame) corresponding to an active subprogram.
24107
24108 @item up
24109 At a breakpoint, @code{GDB} can display the values of variables local
24110 to the current frame. The command @code{up} can be used to
24111 examine the contents of other active frames, by moving the focus up
24112 the stack, that is to say from callee to caller, one frame at a time.
24113
24114 @item down
24115 Moves the focus of @code{GDB} down from the frame currently being
24116 examined to the frame of its callee (the reverse of the previous command),
24117
24118 @item frame @var{n}
24119 Inspect the frame with the given number. The value 0 denotes the frame
24120 of the current breakpoint, that is to say the top of the call stack.
24121
24122 @end table
24123
24124 @noindent
24125 The above list is a very short introduction to the commands that
24126 @code{GDB} provides. Important additional capabilities, including conditional
24127 breakpoints, the ability to execute command sequences on a breakpoint,
24128 the ability to debug at the machine instruction level and many other
24129 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
24130 Debugging with GDB}.  Note that most commands can be abbreviated
24131 (for example, c for continue, bt for backtrace).
24132
24133 @node Using Ada Expressions
24134 @section Using Ada Expressions
24135 @cindex Ada expressions
24136
24137 @noindent
24138 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
24139 extensions. The philosophy behind the design of this subset is
24140
24141 @itemize @bullet
24142 @item
24143 That @code{GDB} should provide basic literals and access to operations for
24144 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
24145 leaving more sophisticated computations to subprograms written into the
24146 program (which therefore may be called from @code{GDB}).
24147
24148 @item
24149 That type safety and strict adherence to Ada language restrictions
24150 are not particularly important to the @code{GDB} user.
24151
24152 @item
24153 That brevity is important to the @code{GDB} user.
24154 @end itemize
24155
24156 @noindent
24157 Thus, for brevity, the debugger acts as if there were
24158 implicit @code{with} and @code{use} clauses in effect for all user-written
24159 packages, thus making it unnecessary to fully qualify most names with
24160 their packages, regardless of context. Where this causes ambiguity,
24161 @code{GDB} asks the user's intent.
24162
24163 For details on the supported Ada syntax, see @ref{Top,, Debugging with
24164 GDB, gdb, Debugging with GDB}.
24165
24166 @node Calling User-Defined Subprograms
24167 @section Calling User-Defined Subprograms
24168
24169 @noindent
24170 An important capability of @code{GDB} is the ability to call user-defined
24171 subprograms while debugging. This is achieved simply by entering
24172 a subprogram call statement in the form:
24173
24174 @smallexample
24175 call subprogram-name (parameters)
24176 @end smallexample
24177
24178 @noindent
24179 The keyword @code{call} can be omitted in the normal case where the
24180 @code{subprogram-name} does not coincide with any of the predefined
24181 @code{GDB} commands.
24182
24183 The effect is to invoke the given subprogram, passing it the
24184 list of parameters that is supplied. The parameters can be expressions and
24185 can include variables from the program being debugged. The
24186 subprogram must be defined
24187 at the library level within your program, and @code{GDB} will call the
24188 subprogram within the environment of your program execution (which
24189 means that the subprogram is free to access or even modify variables
24190 within your program).
24191
24192 The most important use of this facility is in allowing the inclusion of
24193 debugging routines that are tailored to particular data structures
24194 in your program. Such debugging routines can be written to provide a suitably
24195 high-level description of an abstract type, rather than a low-level dump
24196 of its physical layout. After all, the standard
24197 @code{GDB print} command only knows the physical layout of your
24198 types, not their abstract meaning. Debugging routines can provide information
24199 at the desired semantic level and are thus enormously useful.
24200
24201 For example, when debugging GNAT itself, it is crucial to have access to
24202 the contents of the tree nodes used to represent the program internally.
24203 But tree nodes are represented simply by an integer value (which in turn
24204 is an index into a table of nodes).
24205 Using the @code{print} command on a tree node would simply print this integer
24206 value, which is not very useful. But the PN routine (defined in file
24207 treepr.adb in the GNAT sources) takes a tree node as input, and displays
24208 a useful high level representation of the tree node, which includes the
24209 syntactic category of the node, its position in the source, the integers
24210 that denote descendant nodes and parent node, as well as varied
24211 semantic information. To study this example in more detail, you might want to
24212 look at the body of the PN procedure in the stated file.
24213
24214 @node Using the Next Command in a Function
24215 @section Using the Next Command in a Function
24216
24217 @noindent
24218 When you use the @code{next} command in a function, the current source
24219 location will advance to the next statement as usual. A special case
24220 arises in the case of a @code{return} statement.
24221
24222 Part of the code for a return statement is the ``epilog'' of the function.
24223 This is the code that returns to the caller. There is only one copy of
24224 this epilog code, and it is typically associated with the last return
24225 statement in the function if there is more than one return. In some
24226 implementations, this epilog is associated with the first statement
24227 of the function.
24228
24229 The result is that if you use the @code{next} command from a return
24230 statement that is not the last return statement of the function you
24231 may see a strange apparent jump to the last return statement or to
24232 the start of the function. You should simply ignore this odd jump.
24233 The value returned is always that from the first return statement
24234 that was stepped through.
24235
24236 @node Ada Exceptions
24237 @section Breaking on Ada Exceptions
24238 @cindex Exceptions
24239
24240 @noindent
24241 You can set breakpoints that trip when your program raises
24242 selected exceptions.
24243
24244 @table @code
24245 @item break exception
24246 Set a breakpoint that trips whenever (any task in the) program raises
24247 any exception.
24248
24249 @item break exception @var{name}
24250 Set a breakpoint that trips whenever (any task in the) program raises
24251 the exception @var{name}.
24252
24253 @item break exception unhandled
24254 Set a breakpoint that trips whenever (any task in the) program raises an
24255 exception for which there is no handler.
24256
24257 @item info exceptions
24258 @itemx info exceptions @var{regexp}
24259 The @code{info exceptions} command permits the user to examine all defined
24260 exceptions within Ada programs. With a regular expression, @var{regexp}, as
24261 argument, prints out only those exceptions whose name matches @var{regexp}.
24262 @end table
24263
24264 @node Ada Tasks
24265 @section Ada Tasks
24266 @cindex Tasks
24267
24268 @noindent
24269 @code{GDB} allows the following task-related commands:
24270
24271 @table @code
24272 @item info tasks
24273 This command shows a list of current Ada tasks, as in the following example:
24274
24275 @smallexample
24276 @iftex
24277 @leftskip=0cm
24278 @end iftex
24279 (gdb) info tasks
24280   ID       TID P-ID   Thread Pri State                 Name
24281    1   8088000   0   807e000  15 Child Activation Wait main_task
24282    2   80a4000   1   80ae000  15 Accept/Select Wait    b
24283    3   809a800   1   80a4800  15 Child Activation Wait a
24284 *  4   80ae800   3   80b8000  15 Running               c
24285 @end smallexample
24286
24287 @noindent
24288 In this listing, the asterisk before the first task indicates it to be the
24289 currently running task. The first column lists the task ID that is used
24290 to refer to tasks in the following commands.
24291
24292 @item break @var{linespec} task @var{taskid}
24293 @itemx break @var{linespec} task @var{taskid} if @dots{}
24294 @cindex Breakpoints and tasks
24295 These commands are like the @code{break @dots{} thread @dots{}}.
24296 @var{linespec} specifies source lines.
24297
24298 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
24299 to specify that you only want @code{GDB} to stop the program when a
24300 particular Ada task reaches this breakpoint. @var{taskid} is one of the
24301 numeric task identifiers assigned by @code{GDB}, shown in the first
24302 column of the @samp{info tasks} display.
24303
24304 If you do not specify @samp{task @var{taskid}} when you set a
24305 breakpoint, the breakpoint applies to @emph{all} tasks of your
24306 program.
24307
24308 You can use the @code{task} qualifier on conditional breakpoints as
24309 well; in this case, place @samp{task @var{taskid}} before the
24310 breakpoint condition (before the @code{if}).
24311
24312 @item task @var{taskno}
24313 @cindex Task switching
24314
24315 This command allows to switch to the task referred by @var{taskno}. In
24316 particular, This allows to browse the backtrace of the specified
24317 task. It is advised to switch back to the original task before
24318 continuing execution otherwise the scheduling of the program may be
24319 perturbed.
24320 @end table
24321
24322 @noindent
24323 For more detailed information on the tasking support,
24324 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
24325
24326 @node Debugging Generic Units
24327 @section Debugging Generic Units
24328 @cindex Debugging Generic Units
24329 @cindex Generics
24330
24331 @noindent
24332 GNAT always uses code expansion for generic instantiation. This means that
24333 each time an instantiation occurs, a complete copy of the original code is
24334 made, with appropriate substitutions of formals by actuals.
24335
24336 It is not possible to refer to the original generic entities in
24337 @code{GDB}, but it is always possible to debug a particular instance of
24338 a generic, by using the appropriate expanded names. For example, if we have
24339
24340 @smallexample @c ada
24341 @group
24342 @cartouche
24343 procedure g is
24344
24345    generic package k is
24346       procedure kp (v1 : in out integer);
24347    end k;
24348
24349    package body k is
24350       procedure kp (v1 : in out integer) is
24351       begin
24352          v1 := v1 + 1;
24353       end kp;
24354    end k;
24355
24356    package k1 is new k;
24357    package k2 is new k;
24358
24359    var : integer := 1;
24360
24361 begin
24362    k1.kp (var);
24363    k2.kp (var);
24364    k1.kp (var);
24365    k2.kp (var);
24366 end;
24367 @end cartouche
24368 @end group
24369 @end smallexample
24370
24371 @noindent
24372 Then to break on a call to procedure kp in the k2 instance, simply
24373 use the command:
24374
24375 @smallexample
24376 (gdb) break g.k2.kp
24377 @end smallexample
24378
24379 @noindent
24380 When the breakpoint occurs, you can step through the code of the
24381 instance in the normal manner and examine the values of local variables, as for
24382 other units.
24383
24384 @node GNAT Abnormal Termination or Failure to Terminate
24385 @section GNAT Abnormal Termination or Failure to Terminate
24386 @cindex GNAT Abnormal Termination or Failure to Terminate
24387
24388 @noindent
24389 When presented with programs that contain serious errors in syntax
24390 or semantics,
24391 GNAT may on rare occasions  experience problems in operation, such
24392 as aborting with a
24393 segmentation fault or illegal memory access, raising an internal
24394 exception, terminating abnormally, or failing to terminate at all.
24395 In such cases, you can activate
24396 various features of GNAT that can help you pinpoint the construct in your
24397 program that is the likely source of the problem.
24398
24399 The following strategies are presented in increasing order of
24400 difficulty, corresponding to your experience in using GNAT and your
24401 familiarity with compiler internals.
24402
24403 @enumerate
24404 @item
24405 Run @command{gcc} with the @option{-gnatf}. This first
24406 switch causes all errors on a given line to be reported. In its absence,
24407 only the first error on a line is displayed.
24408
24409 The @option{-gnatdO} switch causes errors to be displayed as soon as they
24410 are encountered, rather than after compilation is terminated. If GNAT
24411 terminates prematurely or goes into an infinite loop, the last error
24412 message displayed may help to pinpoint the culprit.
24413
24414 @item
24415 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
24416 mode, @command{gcc} produces ongoing information about the progress of the
24417 compilation and provides the name of each procedure as code is
24418 generated. This switch allows you to find which Ada procedure was being
24419 compiled when it encountered a code generation problem.
24420
24421 @item
24422 @cindex @option{-gnatdc} switch
24423 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
24424 switch that does for the front-end what @option{^-v^VERBOSE^} does
24425 for the back end. The system prints the name of each unit,
24426 either a compilation unit or nested unit, as it is being analyzed.
24427 @item
24428 Finally, you can start
24429 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
24430 front-end of GNAT, and can be run independently (normally it is just
24431 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
24432 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
24433 @code{where} command is the first line of attack; the variable
24434 @code{lineno} (seen by @code{print lineno}), used by the second phase of
24435 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
24436 which the execution stopped, and @code{input_file name} indicates the name of
24437 the source file.
24438 @end enumerate
24439
24440 @node Naming Conventions for GNAT Source Files
24441 @section Naming Conventions for GNAT Source Files
24442
24443 @noindent
24444 In order to examine the workings of the GNAT system, the following
24445 brief description of its organization may be helpful:
24446
24447 @itemize @bullet
24448 @item
24449 Files with prefix @file{^sc^SC^} contain the lexical scanner.
24450
24451 @item
24452 All files prefixed with @file{^par^PAR^} are components of the parser. The
24453 numbers correspond to chapters of the Ada Reference Manual. For example,
24454 parsing of select statements can be found in @file{par-ch9.adb}.
24455
24456 @item
24457 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
24458 numbers correspond to chapters of the Ada standard. For example, all
24459 issues involving context clauses can be found in @file{sem_ch10.adb}. In
24460 addition, some features of the language require sufficient special processing
24461 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
24462 dynamic dispatching, etc.
24463
24464 @item
24465 All files prefixed with @file{^exp^EXP^} perform normalization and
24466 expansion of the intermediate representation (abstract syntax tree, or AST).
24467 these files use the same numbering scheme as the parser and semantics files.
24468 For example, the construction of record initialization procedures is done in
24469 @file{exp_ch3.adb}.
24470
24471 @item
24472 The files prefixed with @file{^bind^BIND^} implement the binder, which
24473 verifies the consistency of the compilation, determines an order of
24474 elaboration, and generates the bind file.
24475
24476 @item
24477 The files @file{atree.ads} and @file{atree.adb} detail the low-level
24478 data structures used by the front-end.
24479
24480 @item
24481 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
24482 the abstract syntax tree as produced by the parser.
24483
24484 @item
24485 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
24486 all entities, computed during semantic analysis.
24487
24488 @item
24489 Library management issues are dealt with in files with prefix
24490 @file{^lib^LIB^}.
24491
24492 @item
24493 @findex Ada
24494 @cindex Annex A
24495 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
24496 defined in Annex A.
24497
24498 @item
24499 @findex Interfaces
24500 @cindex Annex B
24501 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
24502 defined in Annex B.
24503
24504 @item
24505 @findex System
24506 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
24507 both language-defined children and GNAT run-time routines.
24508
24509 @item
24510 @findex GNAT
24511 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
24512 general-purpose packages, fully documented in their specs. All
24513 the other @file{.c} files are modifications of common @command{gcc} files.
24514 @end itemize
24515
24516 @node Getting Internal Debugging Information
24517 @section Getting Internal Debugging Information
24518
24519 @noindent
24520 Most compilers have internal debugging switches and modes. GNAT
24521 does also, except GNAT internal debugging switches and modes are not
24522 secret. A summary and full description of all the compiler and binder
24523 debug flags are in the file @file{debug.adb}. You must obtain the
24524 sources of the compiler to see the full detailed effects of these flags.
24525
24526 The switches that print the source of the program (reconstructed from
24527 the internal tree) are of general interest for user programs, as are the
24528 options to print
24529 the full internal tree, and the entity table (the symbol table
24530 information). The reconstructed source provides a readable version of the
24531 program after the front-end has completed analysis and  expansion,
24532 and is useful when studying the performance of specific constructs.
24533 For example, constraint checks are indicated, complex aggregates
24534 are replaced with loops and assignments, and tasking primitives
24535 are replaced with run-time calls.
24536
24537 @node Stack Traceback
24538 @section Stack Traceback
24539 @cindex traceback
24540 @cindex stack traceback
24541 @cindex stack unwinding
24542
24543 @noindent
24544 Traceback is a mechanism to display the sequence of subprogram calls that
24545 leads to a specified execution point in a program. Often (but not always)
24546 the execution point is an instruction at which an exception has been raised.
24547 This mechanism is also known as @i{stack unwinding} because it obtains
24548 its information by scanning the run-time stack and recovering the activation
24549 records of all active subprograms. Stack unwinding is one of the most
24550 important tools for program debugging.
24551
24552 The first entry stored in traceback corresponds to the deepest calling level,
24553 that is to say the subprogram currently executing the instruction
24554 from which we want to obtain the traceback.
24555
24556 Note that there is no runtime performance penalty when stack traceback
24557 is enabled, and no exception is raised during program execution.
24558
24559 @menu
24560 * Non-Symbolic Traceback::
24561 * Symbolic Traceback::
24562 @end menu
24563
24564 @node Non-Symbolic Traceback
24565 @subsection Non-Symbolic Traceback
24566 @cindex traceback, non-symbolic
24567
24568 @noindent
24569 Note: this feature is not supported on all platforms. See
24570 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
24571 platforms.
24572
24573 @menu
24574 * Tracebacks From an Unhandled Exception::
24575 * Tracebacks From Exception Occurrences (non-symbolic)::
24576 * Tracebacks From Anywhere in a Program (non-symbolic)::
24577 @end menu
24578
24579 @node Tracebacks From an Unhandled Exception
24580 @subsubsection Tracebacks From an Unhandled Exception
24581
24582 @noindent
24583 A runtime non-symbolic traceback is a list of addresses of call instructions.
24584 To enable this feature you must use the @option{-E}
24585 @code{gnatbind}'s option. With this option a stack traceback is stored as part
24586 of exception information. You can retrieve this information using the
24587 @code{addr2line} tool.
24588
24589 Here is a simple example:
24590
24591 @smallexample @c ada
24592 @cartouche
24593 procedure STB is
24594
24595    procedure P1 is
24596    begin
24597       raise Constraint_Error;
24598    end P1;
24599
24600    procedure P2 is
24601    begin
24602       P1;
24603    end P2;
24604
24605 begin
24606    P2;
24607 end STB;
24608 @end cartouche
24609 @end smallexample
24610
24611 @smallexample
24612 $ gnatmake stb -bargs -E
24613 $ stb
24614
24615 Execution terminated by unhandled exception
24616 Exception name: CONSTRAINT_ERROR
24617 Message: stb.adb:5
24618 Call stack traceback locations:
24619 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24620 @end smallexample
24621
24622 @noindent
24623 As we see the traceback lists a sequence of addresses for the unhandled
24624 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
24625 guess that this exception come from procedure P1. To translate these
24626 addresses into the source lines where the calls appear, the
24627 @code{addr2line} tool, described below, is invaluable. The use of this tool
24628 requires the program to be compiled with debug information.
24629
24630 @smallexample
24631 $ gnatmake -g stb -bargs -E
24632 $ stb
24633
24634 Execution terminated by unhandled exception
24635 Exception name: CONSTRAINT_ERROR
24636 Message: stb.adb:5
24637 Call stack traceback locations:
24638 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24639
24640 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
24641    0x4011f1 0x77e892a4
24642
24643 00401373 at d:/stb/stb.adb:5
24644 0040138B at d:/stb/stb.adb:10
24645 0040139C at d:/stb/stb.adb:14
24646 00401335 at d:/stb/b~stb.adb:104
24647 004011C4 at /build/@dots{}/crt1.c:200
24648 004011F1 at /build/@dots{}/crt1.c:222
24649 77E892A4 in ?? at ??:0
24650 @end smallexample
24651
24652 @noindent
24653 The @code{addr2line} tool has several other useful options:
24654
24655 @table @code
24656 @item --functions
24657 to get the function name corresponding to any location
24658
24659 @item --demangle=gnat
24660 to use the gnat decoding mode for the function names. Note that
24661 for binutils version 2.9.x the option is simply @option{--demangle}.
24662 @end table
24663
24664 @smallexample
24665 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
24666    0x40139c 0x401335 0x4011c4 0x4011f1
24667
24668 00401373 in stb.p1 at d:/stb/stb.adb:5
24669 0040138B in stb.p2 at d:/stb/stb.adb:10
24670 0040139C in stb at d:/stb/stb.adb:14
24671 00401335 in main at d:/stb/b~stb.adb:104
24672 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
24673 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
24674 @end smallexample
24675
24676 @noindent
24677 From this traceback we can see that the exception was raised in
24678 @file{stb.adb} at line 5, which was reached from a procedure call in
24679 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
24680 which contains the call to the main program.
24681 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
24682 and the output will vary from platform to platform.
24683
24684 It is also possible to use @code{GDB} with these traceback addresses to debug
24685 the program. For example, we can break at a given code location, as reported
24686 in the stack traceback:
24687
24688 @smallexample
24689 $ gdb -nw stb
24690 @ifclear vms
24691 @noindent
24692 Furthermore, this feature is not implemented inside Windows DLL. Only
24693 the non-symbolic traceback is reported in this case.
24694 @end ifclear
24695
24696 (gdb) break *0x401373
24697 Breakpoint 1 at 0x401373: file stb.adb, line 5.
24698 @end smallexample
24699
24700 @noindent
24701 It is important to note that the stack traceback addresses
24702 do not change when debug information is included. This is particularly useful
24703 because it makes it possible to release software without debug information (to
24704 minimize object size), get a field report that includes a stack traceback
24705 whenever an internal bug occurs, and then be able to retrieve the sequence
24706 of calls with the same program compiled with debug information.
24707
24708 @node Tracebacks From Exception Occurrences (non-symbolic)
24709 @subsubsection Tracebacks From Exception Occurrences
24710
24711 @noindent
24712 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
24713 The stack traceback is attached to the exception information string, and can
24714 be retrieved in an exception handler within the Ada program, by means of the
24715 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
24716
24717 @smallexample @c ada
24718 with Ada.Text_IO;
24719 with Ada.Exceptions;
24720
24721 procedure STB is
24722
24723    use Ada;
24724    use Ada.Exceptions;
24725
24726    procedure P1 is
24727       K : Positive := 1;
24728    begin
24729       K := K - 1;
24730    exception
24731       when E : others =>
24732          Text_IO.Put_Line (Exception_Information (E));
24733    end P1;
24734
24735    procedure P2 is
24736    begin
24737       P1;
24738    end P2;
24739
24740 begin
24741    P2;
24742 end STB;
24743 @end smallexample
24744
24745 @noindent
24746 This program will output:
24747
24748 @smallexample
24749 $ stb
24750
24751 Exception name: CONSTRAINT_ERROR
24752 Message: stb.adb:12
24753 Call stack traceback locations:
24754 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
24755 @end smallexample
24756
24757 @node Tracebacks From Anywhere in a Program (non-symbolic)
24758 @subsubsection Tracebacks From Anywhere in a Program
24759
24760 @noindent
24761 It is also possible to retrieve a stack traceback from anywhere in a
24762 program. For this you need to
24763 use the @code{GNAT.Traceback} API. This package includes a procedure called
24764 @code{Call_Chain} that computes a complete stack traceback, as well as useful
24765 display procedures described below. It is not necessary to use the
24766 @option{-E gnatbind} option in this case, because the stack traceback mechanism
24767 is invoked explicitly.
24768
24769 @noindent
24770 In the following example we compute a traceback at a specific location in
24771 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
24772 convert addresses to strings:
24773
24774 @smallexample @c ada
24775 with Ada.Text_IO;
24776 with GNAT.Traceback;
24777 with GNAT.Debug_Utilities;
24778
24779 procedure STB is
24780
24781    use Ada;
24782    use GNAT;
24783    use GNAT.Traceback;
24784
24785    procedure P1 is
24786       TB  : Tracebacks_Array (1 .. 10);
24787       --  We are asking for a maximum of 10 stack frames.
24788       Len : Natural;
24789       --  Len will receive the actual number of stack frames returned.
24790    begin
24791       Call_Chain (TB, Len);
24792
24793       Text_IO.Put ("In STB.P1 : ");
24794
24795       for K in 1 .. Len loop
24796          Text_IO.Put (Debug_Utilities.Image (TB (K)));
24797          Text_IO.Put (' ');
24798       end loop;
24799
24800       Text_IO.New_Line;
24801    end P1;
24802
24803    procedure P2 is
24804    begin
24805       P1;
24806    end P2;
24807
24808 begin
24809    P2;
24810 end STB;
24811 @end smallexample
24812
24813 @smallexample
24814 $ gnatmake -g stb
24815 $ stb
24816
24817 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
24818 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
24819 @end smallexample
24820
24821 @noindent
24822 You can then get further information by invoking the @code{addr2line}
24823 tool as described earlier (note that the hexadecimal addresses
24824 need to be specified in C format, with a leading ``0x'').
24825
24826 @node Symbolic Traceback
24827 @subsection Symbolic Traceback
24828 @cindex traceback, symbolic
24829
24830 @noindent
24831 A symbolic traceback is a stack traceback in which procedure names are
24832 associated with each code location.
24833
24834 @noindent
24835 Note that this feature is not supported on all platforms. See
24836 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
24837 list of currently supported platforms.
24838
24839 @noindent
24840 Note that the symbolic traceback requires that the program be compiled
24841 with debug information. If it is not compiled with debug information
24842 only the non-symbolic information will be valid.
24843
24844 @menu
24845 * Tracebacks From Exception Occurrences (symbolic)::
24846 * Tracebacks From Anywhere in a Program (symbolic)::
24847 @end menu
24848
24849 @node Tracebacks From Exception Occurrences (symbolic)
24850 @subsubsection Tracebacks From Exception Occurrences
24851
24852 @smallexample @c ada
24853 with Ada.Text_IO;
24854 with GNAT.Traceback.Symbolic;
24855
24856 procedure STB is
24857
24858    procedure P1 is
24859    begin
24860       raise Constraint_Error;
24861    end P1;
24862
24863    procedure P2 is
24864    begin
24865       P1;
24866    end P2;
24867
24868    procedure P3 is
24869    begin
24870       P2;
24871    end P3;
24872
24873 begin
24874    P3;
24875 exception
24876    when E : others =>
24877       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
24878 end STB;
24879 @end smallexample
24880
24881 @smallexample
24882 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
24883 $ stb
24884
24885 0040149F in stb.p1 at stb.adb:8
24886 004014B7 in stb.p2 at stb.adb:13
24887 004014CF in stb.p3 at stb.adb:18
24888 004015DD in ada.stb at stb.adb:22
24889 00401461 in main at b~stb.adb:168
24890 004011C4 in __mingw_CRTStartup at crt1.c:200
24891 004011F1 in mainCRTStartup at crt1.c:222
24892 77E892A4 in ?? at ??:0
24893 @end smallexample
24894
24895 @noindent
24896 In the above example the ``.\'' syntax in the @command{gnatmake} command
24897 is currently required by @command{addr2line} for files that are in
24898 the current working directory.
24899 Moreover, the exact sequence of linker options may vary from platform
24900 to platform.
24901 The above @option{-largs} section is for Windows platforms. By contrast,
24902 under Unix there is no need for the @option{-largs} section.
24903 Differences across platforms are due to details of linker implementation.
24904
24905 @node Tracebacks From Anywhere in a Program (symbolic)
24906 @subsubsection Tracebacks From Anywhere in a Program
24907
24908 @noindent
24909 It is possible to get a symbolic stack traceback
24910 from anywhere in a program, just as for non-symbolic tracebacks.
24911 The first step is to obtain a non-symbolic
24912 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
24913 information. Here is an example:
24914
24915 @smallexample @c ada
24916 with Ada.Text_IO;
24917 with GNAT.Traceback;
24918 with GNAT.Traceback.Symbolic;
24919
24920 procedure STB is
24921
24922    use Ada;
24923    use GNAT.Traceback;
24924    use GNAT.Traceback.Symbolic;
24925
24926    procedure P1 is
24927       TB  : Tracebacks_Array (1 .. 10);
24928       --  We are asking for a maximum of 10 stack frames.
24929       Len : Natural;
24930       --  Len will receive the actual number of stack frames returned.
24931    begin
24932       Call_Chain (TB, Len);
24933       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
24934    end P1;
24935
24936    procedure P2 is
24937    begin
24938       P1;
24939    end P2;
24940
24941 begin
24942    P2;
24943 end STB;
24944 @end smallexample
24945
24946 @c ******************************
24947 @ifset vms
24948 @node Compatibility with HP Ada
24949 @chapter Compatibility with HP Ada
24950 @cindex Compatibility
24951
24952 @noindent
24953 @cindex DEC Ada
24954 @cindex HP Ada
24955 @cindex Compatibility between GNAT and HP Ada
24956 This chapter compares HP Ada (formerly known as ``DEC Ada'')
24957 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
24958 GNAT is highly compatible
24959 with HP Ada, and it should generally be straightforward to port code
24960 from the HP Ada environment to GNAT. However, there are a few language
24961 and implementation differences of which the user must be aware. These
24962 differences are discussed in this chapter. In
24963 addition, the operating environment and command structure for the
24964 compiler are different, and these differences are also discussed.
24965
24966 For further details on these and other compatibility issues,
24967 see Appendix E of the HP publication
24968 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
24969
24970 Except where otherwise indicated, the description of GNAT for OpenVMS
24971 applies to both the Alpha and I64 platforms.
24972
24973 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
24974 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24975
24976 The discussion in this chapter addresses specifically the implementation
24977 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
24978 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
24979 GNAT always follows the Alpha implementation.
24980
24981 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
24982 attributes are recognized, although only a subset of them can sensibly
24983 be implemented.  The description of pragmas in
24984 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
24985 indicates whether or not they are applicable to non-VMS systems.
24986
24987 @menu
24988 * Ada Language Compatibility::
24989 * Differences in the Definition of Package System::
24990 * Language-Related Features::
24991 * The Package STANDARD::
24992 * The Package SYSTEM::
24993 * Tasking and Task-Related Features::
24994 * Pragmas and Pragma-Related Features::
24995 * Library of Predefined Units::
24996 * Bindings::
24997 * Main Program Definition::
24998 * Implementation-Defined Attributes::
24999 * Compiler and Run-Time Interfacing::
25000 * Program Compilation and Library Management::
25001 * Input-Output::
25002 * Implementation Limits::
25003 * Tools and Utilities::
25004 @end menu
25005
25006 @node Ada Language Compatibility
25007 @section Ada Language Compatibility
25008
25009 @noindent
25010 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
25011 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
25012 with Ada 83, and therefore Ada 83 programs will compile
25013 and run under GNAT with
25014 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
25015 provides details on specific incompatibilities.
25016
25017 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
25018 as well as the pragma @code{ADA_83}, to force the compiler to
25019 operate in Ada 83 mode. This mode does not guarantee complete
25020 conformance to Ada 83, but in practice is sufficient to
25021 eliminate most sources of incompatibilities.
25022 In particular, it eliminates the recognition of the
25023 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
25024 in Ada 83 programs is legal, and handles the cases of packages
25025 with optional bodies, and generics that instantiate unconstrained
25026 types without the use of @code{(<>)}.
25027
25028 @node Differences in the Definition of Package System
25029 @section Differences in the Definition of Package @code{System}
25030
25031 @noindent
25032 An Ada compiler is allowed to add
25033 implementation-dependent declarations to package @code{System}.
25034 In normal mode,
25035 GNAT does not take advantage of this permission, and the version of
25036 @code{System} provided by GNAT exactly matches that defined in the Ada
25037 Reference Manual.
25038
25039 However, HP Ada adds an extensive set of declarations to package
25040 @code{System},
25041 as fully documented in the HP Ada manuals. To minimize changes required
25042 for programs that make use of these extensions, GNAT provides the pragma
25043 @code{Extend_System} for extending the definition of package System. By using:
25044 @cindex pragma @code{Extend_System}
25045 @cindex @code{Extend_System} pragma
25046
25047 @smallexample @c ada
25048 @group
25049 @cartouche
25050 pragma Extend_System (Aux_DEC);
25051 @end cartouche
25052 @end group
25053 @end smallexample
25054
25055 @noindent
25056 the set of definitions in @code{System} is extended to include those in
25057 package @code{System.Aux_DEC}.
25058 @cindex @code{System.Aux_DEC} package
25059 @cindex @code{Aux_DEC} package (child of @code{System})
25060 These definitions are incorporated directly into package @code{System},
25061 as though they had been declared there. For a
25062 list of the declarations added, see the spec of this package,
25063 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
25064 @cindex @file{s-auxdec.ads} file
25065 The pragma @code{Extend_System} is a configuration pragma, which means that
25066 it can be placed in the file @file{gnat.adc}, so that it will automatically
25067 apply to all subsequent compilations. See @ref{Configuration Pragmas},
25068 for further details.
25069
25070 An alternative approach that avoids the use of the non-standard
25071 @code{Extend_System} pragma is to add a context clause to the unit that
25072 references these facilities:
25073
25074 @smallexample @c ada
25075 @cartouche
25076 with System.Aux_DEC;
25077 use  System.Aux_DEC;
25078 @end cartouche
25079 @end smallexample
25080
25081 @noindent
25082 The effect is not quite semantically identical to incorporating
25083 the declarations directly into package @code{System},
25084 but most programs will not notice a difference
25085 unless they use prefix notation (e.g.@: @code{System.Integer_8})
25086 to reference the entities directly in package @code{System}.
25087 For units containing such references,
25088 the prefixes must either be removed, or the pragma @code{Extend_System}
25089 must be used.
25090
25091 @node Language-Related Features
25092 @section Language-Related Features
25093
25094 @noindent
25095 The following sections highlight differences in types,
25096 representations of types, operations, alignment, and
25097 related topics.
25098
25099 @menu
25100 * Integer Types and Representations::
25101 * Floating-Point Types and Representations::
25102 * Pragmas Float_Representation and Long_Float::
25103 * Fixed-Point Types and Representations::
25104 * Record and Array Component Alignment::
25105 * Address Clauses::
25106 * Other Representation Clauses::
25107 @end menu
25108
25109 @node Integer Types and Representations
25110 @subsection Integer Types and Representations
25111
25112 @noindent
25113 The set of predefined integer types is identical in HP Ada and GNAT.
25114 Furthermore the representation of these integer types is also identical,
25115 including the capability of size clauses forcing biased representation.
25116
25117 In addition,
25118 HP Ada for OpenVMS Alpha systems has defined the
25119 following additional integer types in package @code{System}:
25120
25121 @itemize @bullet
25122
25123 @item
25124 @code{INTEGER_8}
25125
25126 @item
25127 @code{INTEGER_16}
25128
25129 @item
25130 @code{INTEGER_32}
25131
25132 @item
25133 @code{INTEGER_64}
25134
25135 @item
25136 @code{LARGEST_INTEGER}
25137 @end itemize
25138
25139 @noindent
25140 In GNAT, the first four of these types may be obtained from the
25141 standard Ada package @code{Interfaces}.
25142 Alternatively, by use of the pragma @code{Extend_System}, identical
25143 declarations can be referenced directly in package @code{System}.
25144 On both GNAT and HP Ada, the maximum integer size is 64 bits.
25145
25146 @node Floating-Point Types and Representations
25147 @subsection Floating-Point Types and Representations
25148 @cindex Floating-Point types
25149
25150 @noindent
25151 The set of predefined floating-point types is identical in HP Ada and GNAT.
25152 Furthermore the representation of these floating-point
25153 types is also identical. One important difference is that the default
25154 representation for HP Ada is @code{VAX_Float}, but the default representation
25155 for GNAT is IEEE.
25156
25157 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
25158 pragma @code{Float_Representation} as described in the HP Ada
25159 documentation.
25160 For example, the declarations:
25161
25162 @smallexample @c ada
25163 @cartouche
25164 type F_Float is digits 6;
25165 pragma Float_Representation (VAX_Float, F_Float);
25166 @end cartouche
25167 @end smallexample
25168
25169 @noindent
25170 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
25171 format.
25172 This set of declarations actually appears in @code{System.Aux_DEC},
25173 which contains
25174 the full set of additional floating-point declarations provided in
25175 the HP Ada version of package @code{System}.
25176 This and similar declarations may be accessed in a user program
25177 by using pragma @code{Extend_System}. The use of this
25178 pragma, and the related pragma @code{Long_Float} is described in further
25179 detail in the following section.
25180
25181 @node Pragmas Float_Representation and Long_Float
25182 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
25183
25184 @noindent
25185 HP Ada provides the pragma @code{Float_Representation}, which
25186 acts as a program library switch to allow control over
25187 the internal representation chosen for the predefined
25188 floating-point types declared in the package @code{Standard}.
25189 The format of this pragma is as follows:
25190
25191 @smallexample @c ada
25192 @cartouche
25193 pragma Float_Representation(VAX_Float | IEEE_Float);
25194 @end cartouche
25195 @end smallexample
25196
25197 @noindent
25198 This pragma controls the representation of floating-point
25199 types as follows:
25200
25201 @itemize @bullet
25202 @item
25203 @code{VAX_Float} specifies that floating-point
25204 types are represented by default with the VAX system hardware types
25205 @code{F-floating}, @code{D-floating}, @code{G-floating}.
25206 Note that the @code{H-floating}
25207 type was available only on VAX systems, and is not available
25208 in either HP Ada or GNAT.
25209
25210 @item
25211 @code{IEEE_Float} specifies that floating-point
25212 types are represented by default with the IEEE single and
25213 double floating-point types.
25214 @end itemize
25215
25216 @noindent
25217 GNAT provides an identical implementation of the pragma
25218 @code{Float_Representation}, except that it functions as a
25219 configuration pragma. Note that the
25220 notion of configuration pragma corresponds closely to the
25221 HP Ada notion of a program library switch.
25222
25223 When no pragma is used in GNAT, the default is @code{IEEE_Float},
25224 which is different
25225 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
25226 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
25227 advisable to change the format of numbers passed to standard library
25228 routines, and if necessary explicit type conversions may be needed.
25229
25230 The use of @code{IEEE_Float} is recommended in GNAT since it is more
25231 efficient, and (given that it conforms to an international standard)
25232 potentially more portable.
25233 The situation in which @code{VAX_Float} may be useful is in interfacing
25234 to existing code and data that expect the use of @code{VAX_Float}.
25235 In such a situation use the predefined @code{VAX_Float}
25236 types in package @code{System}, as extended by
25237 @code{Extend_System}. For example, use @code{System.F_Float}
25238 to specify the 32-bit @code{F-Float} format.
25239
25240 @noindent
25241 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
25242 to allow control over the internal representation chosen
25243 for the predefined type @code{Long_Float} and for floating-point
25244 type declarations with digits specified in the range 7 .. 15.
25245 The format of this pragma is as follows:
25246
25247 @smallexample @c ada
25248 @cartouche
25249 pragma Long_Float (D_FLOAT | G_FLOAT);
25250 @end cartouche
25251 @end smallexample
25252
25253 @node Fixed-Point Types and Representations
25254 @subsection Fixed-Point Types and Representations
25255
25256 @noindent
25257 On HP Ada for OpenVMS Alpha systems, rounding is
25258 away from zero for both positive and negative numbers.
25259 Therefore, @code{+0.5} rounds to @code{1},
25260 and @code{-0.5} rounds to @code{-1}.
25261
25262 On GNAT the results of operations
25263 on fixed-point types are in accordance with the Ada
25264 rules. In particular, results of operations on decimal
25265 fixed-point types are truncated.
25266
25267 @node Record and Array Component Alignment
25268 @subsection Record and Array Component Alignment
25269
25270 @noindent
25271 On HP Ada for OpenVMS Alpha, all non-composite components
25272 are aligned on natural boundaries. For example, 1-byte
25273 components are aligned on byte boundaries, 2-byte
25274 components on 2-byte boundaries, 4-byte components on 4-byte
25275 byte boundaries, and so on. The OpenVMS Alpha hardware
25276 runs more efficiently with naturally aligned data.
25277
25278 On GNAT, alignment rules are compatible
25279 with HP Ada for OpenVMS Alpha.
25280
25281 @node Address Clauses
25282 @subsection Address Clauses
25283
25284 @noindent
25285 In HP Ada and GNAT, address clauses are supported for
25286 objects and imported subprograms.
25287 The predefined type @code{System.Address} is a private type
25288 in both compilers on Alpha OpenVMS, with the same representation
25289 (it is simply a machine pointer). Addition, subtraction, and comparison
25290 operations are available in the standard Ada package
25291 @code{System.Storage_Elements}, or in package @code{System}
25292 if it is extended to include @code{System.Aux_DEC} using a
25293 pragma @code{Extend_System} as previously described.
25294
25295 Note that code that @code{with}'s both this extended package @code{System}
25296 and the package @code{System.Storage_Elements} should not @code{use}
25297 both packages, or ambiguities will result. In general it is better
25298 not to mix these two sets of facilities. The Ada package was
25299 designed specifically to provide the kind of features that HP Ada
25300 adds directly to package @code{System}.
25301
25302 The type @code{System.Address} is a 64-bit integer type in GNAT for
25303 I64 OpenVMS.  For more information,
25304 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
25305
25306 GNAT is compatible with HP Ada in its handling of address
25307 clauses, except for some limitations in
25308 the form of address clauses for composite objects with
25309 initialization. Such address clauses are easily replaced
25310 by the use of an explicitly-defined constant as described
25311 in the Ada Reference Manual (13.1(22)). For example, the sequence
25312 of declarations:
25313
25314 @smallexample @c ada
25315 @cartouche
25316 X, Y : Integer := Init_Func;
25317 Q : String (X .. Y) := "abc";
25318 @dots{}
25319 for Q'Address use Compute_Address;
25320 @end cartouche
25321 @end smallexample
25322
25323 @noindent
25324 will be rejected by GNAT, since the address cannot be computed at the time
25325 that @code{Q} is declared. To achieve the intended effect, write instead:
25326
25327 @smallexample @c ada
25328 @group
25329 @cartouche
25330 X, Y : Integer := Init_Func;
25331 Q_Address : constant Address := Compute_Address;
25332 Q : String (X .. Y) := "abc";
25333 @dots{}
25334 for Q'Address use Q_Address;
25335 @end cartouche
25336 @end group
25337 @end smallexample
25338
25339 @noindent
25340 which will be accepted by GNAT (and other Ada compilers), and is also
25341 compatible with Ada 83. A fuller description of the restrictions
25342 on address specifications is found in @ref{Top, GNAT Reference Manual,
25343 About This Guide, gnat_rm, GNAT Reference Manual}.
25344
25345 @node Other Representation Clauses
25346 @subsection Other Representation Clauses
25347
25348 @noindent
25349 GNAT implements in a compatible manner all the representation
25350 clauses supported by HP Ada. In addition, GNAT
25351 implements the representation clause forms that were introduced in Ada 95,
25352 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
25353
25354 @node The Package STANDARD
25355 @section The Package @code{STANDARD}
25356
25357 @noindent
25358 The package @code{STANDARD}, as implemented by HP Ada, is fully
25359 described in the @cite{Ada Reference Manual} and in the
25360 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
25361 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
25362
25363 In addition, HP Ada supports the Latin-1 character set in
25364 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
25365 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
25366 the type @code{WIDE_CHARACTER}.
25367
25368 The floating-point types supported by GNAT are those
25369 supported by HP Ada, but the defaults are different, and are controlled by
25370 pragmas. See @ref{Floating-Point Types and Representations}, for details.
25371
25372 @node The Package SYSTEM
25373 @section The Package @code{SYSTEM}
25374
25375 @noindent
25376 HP Ada provides a specific version of the package
25377 @code{SYSTEM} for each platform on which the language is implemented.
25378 For the complete spec of the package @code{SYSTEM}, see
25379 Appendix F of the @cite{HP Ada Language Reference Manual}.
25380
25381 On HP Ada, the package @code{SYSTEM} includes the following conversion
25382 functions:
25383 @itemize @bullet
25384 @item @code{TO_ADDRESS(INTEGER)}
25385
25386 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
25387
25388 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
25389
25390 @item @code{TO_INTEGER(ADDRESS)}
25391
25392 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
25393
25394 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
25395 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
25396 @end itemize
25397
25398 @noindent
25399 By default, GNAT supplies a version of @code{SYSTEM} that matches
25400 the definition given in the @cite{Ada Reference Manual}.
25401 This
25402 is a subset of the HP system definitions, which is as
25403 close as possible to the original definitions. The only difference
25404 is that the definition of @code{SYSTEM_NAME} is different:
25405
25406 @smallexample @c ada
25407 @cartouche
25408 type Name is (SYSTEM_NAME_GNAT);
25409 System_Name : constant Name := SYSTEM_NAME_GNAT;
25410 @end cartouche
25411 @end smallexample
25412
25413 @noindent
25414 Also, GNAT adds the Ada declarations for
25415 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
25416
25417 However, the use of the following pragma causes GNAT
25418 to extend the definition of package @code{SYSTEM} so that it
25419 encompasses the full set of HP-specific extensions,
25420 including the functions listed above:
25421
25422 @smallexample @c ada
25423 @cartouche
25424 pragma Extend_System (Aux_DEC);
25425 @end cartouche
25426 @end smallexample
25427
25428 @noindent
25429 The pragma @code{Extend_System} is a configuration pragma that
25430 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
25431 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
25432
25433 HP Ada does not allow the recompilation of the package
25434 @code{SYSTEM}. Instead HP Ada provides several pragmas
25435 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
25436 to modify values in the package @code{SYSTEM}.
25437 On OpenVMS Alpha systems, the pragma
25438 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
25439 its single argument.
25440
25441 GNAT does permit the recompilation of package @code{SYSTEM} using
25442 the special switch @option{-gnatg}, and this switch can be used if
25443 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
25444 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
25445 or @code{MEMORY_SIZE} by any other means.
25446
25447 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
25448 enumeration literal @code{SYSTEM_NAME_GNAT}.
25449
25450 The definitions provided by the use of
25451
25452 @smallexample @c ada
25453 pragma Extend_System (AUX_Dec);
25454 @end smallexample
25455
25456 @noindent
25457 are virtually identical to those provided by the HP Ada 83 package
25458 @code{SYSTEM}. One important difference is that the name of the
25459 @code{TO_ADDRESS}
25460 function for type @code{UNSIGNED_LONGWORD} is changed to
25461 @code{TO_ADDRESS_LONG}.
25462 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
25463 discussion of why this change was necessary.
25464
25465 @noindent
25466 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
25467 is in fact
25468 an extension to Ada 83 not strictly compatible with the reference manual.
25469 GNAT, in order to be exactly compatible with the standard,
25470 does not provide this capability. In HP Ada 83, the
25471 point of this definition is to deal with a call like:
25472
25473 @smallexample @c ada
25474 TO_ADDRESS (16#12777#);
25475 @end smallexample
25476
25477 @noindent
25478 Normally, according to Ada 83 semantics, one would expect this to be
25479 ambiguous, since it matches both the @code{INTEGER} and
25480 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
25481 However, in HP Ada 83, there is no ambiguity, since the
25482 definition using @i{universal_integer} takes precedence.
25483
25484 In GNAT, since the version with @i{universal_integer} cannot be supplied,
25485 it is
25486 not possible to be 100% compatible. Since there are many programs using
25487 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
25488 GNAT was
25489 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
25490 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
25491
25492 @smallexample @c ada
25493 function To_Address (X : Integer) return Address;
25494 pragma Pure_Function (To_Address);
25495
25496 function To_Address_Long (X : Unsigned_Longword) return Address;
25497 pragma Pure_Function (To_Address_Long);
25498 @end smallexample
25499
25500 @noindent
25501 This means that programs using @code{TO_ADDRESS} for
25502 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
25503
25504 @node Tasking and Task-Related Features
25505 @section Tasking and Task-Related Features
25506
25507 @noindent
25508 This section compares the treatment of tasking in GNAT
25509 and in HP Ada for OpenVMS Alpha.
25510 The GNAT description applies to both Alpha and I64 OpenVMS.
25511 For detailed information on tasking in
25512 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
25513 relevant run-time reference manual.
25514
25515 @menu
25516 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
25517 * Assigning Task IDs::
25518 * Task IDs and Delays::
25519 * Task-Related Pragmas::
25520 * Scheduling and Task Priority::
25521 * The Task Stack::
25522 * External Interrupts::
25523 @end menu
25524
25525 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25526 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25527
25528 @noindent
25529 On OpenVMS Alpha systems, each Ada task (except a passive
25530 task) is implemented as a single stream of execution
25531 that is created and managed by the kernel. On these
25532 systems, HP Ada tasking support is based on DECthreads,
25533 an implementation of the POSIX standard for threads.
25534
25535 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
25536 code that calls DECthreads routines can be used together.
25537 The interaction between Ada tasks and DECthreads routines
25538 can have some benefits. For example when on OpenVMS Alpha,
25539 HP Ada can call C code that is already threaded.
25540
25541 GNAT uses the facilities of DECthreads,
25542 and Ada tasks are mapped to threads.
25543
25544 @node Assigning Task IDs
25545 @subsection Assigning Task IDs
25546
25547 @noindent
25548 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
25549 the environment task that executes the main program. On
25550 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
25551 that have been created but are not yet activated.
25552
25553 On OpenVMS Alpha systems, task IDs are assigned at
25554 activation. On GNAT systems, task IDs are also assigned at
25555 task creation but do not have the same form or values as
25556 task ID values in HP Ada. There is no null task, and the
25557 environment task does not have a specific task ID value.
25558
25559 @node Task IDs and Delays
25560 @subsection Task IDs and Delays
25561
25562 @noindent
25563 On OpenVMS Alpha systems, tasking delays are implemented
25564 using Timer System Services. The Task ID is used for the
25565 identification of the timer request (the @code{REQIDT} parameter).
25566 If Timers are used in the application take care not to use
25567 @code{0} for the identification, because cancelling such a timer
25568 will cancel all timers and may lead to unpredictable results.
25569
25570 @node Task-Related Pragmas
25571 @subsection Task-Related Pragmas
25572
25573 @noindent
25574 Ada supplies the pragma @code{TASK_STORAGE}, which allows
25575 specification of the size of the guard area for a task
25576 stack. (The guard area forms an area of memory that has no
25577 read or write access and thus helps in the detection of
25578 stack overflow.) On OpenVMS Alpha systems, if the pragma
25579 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
25580 area is created. In the absence of a pragma @code{TASK_STORAGE},
25581 a default guard area is created.
25582
25583 GNAT supplies the following task-related pragmas:
25584
25585 @itemize @bullet
25586 @item  @code{TASK_INFO}
25587
25588 This pragma appears within a task definition and
25589 applies to the task in which it appears. The argument
25590 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
25591
25592 @item  @code{TASK_STORAGE}
25593
25594 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
25595 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
25596 @code{SUPPRESS}, and @code{VOLATILE}.
25597 @end itemize
25598 @node Scheduling and Task Priority
25599 @subsection Scheduling and Task Priority
25600
25601 @noindent
25602 HP Ada implements the Ada language requirement that
25603 when two tasks are eligible for execution and they have
25604 different priorities, the lower priority task does not
25605 execute while the higher priority task is waiting. The HP
25606 Ada Run-Time Library keeps a task running until either the
25607 task is suspended or a higher priority task becomes ready.
25608
25609 On OpenVMS Alpha systems, the default strategy is round-
25610 robin with preemption. Tasks of equal priority take turns
25611 at the processor. A task is run for a certain period of
25612 time and then placed at the tail of the ready queue for
25613 its priority level.
25614
25615 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
25616 which can be used to enable or disable round-robin
25617 scheduling of tasks with the same priority.
25618 See the relevant HP Ada run-time reference manual for
25619 information on using the pragmas to control HP Ada task
25620 scheduling.
25621
25622 GNAT follows the scheduling rules of Annex D (Real-Time
25623 Annex) of the @cite{Ada Reference Manual}. In general, this
25624 scheduling strategy is fully compatible with HP Ada
25625 although it provides some additional constraints (as
25626 fully documented in Annex D).
25627 GNAT implements time slicing control in a manner compatible with
25628 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
25629 are identical to the HP Ada 83 pragma of the same name.
25630 Note that it is not possible to mix GNAT tasking and
25631 HP Ada 83 tasking in the same program, since the two run-time
25632 libraries are not compatible.
25633
25634 @node The Task Stack
25635 @subsection The Task Stack
25636
25637 @noindent
25638 In HP Ada, a task stack is allocated each time a
25639 non-passive task is activated. As soon as the task is
25640 terminated, the storage for the task stack is deallocated.
25641 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
25642 a default stack size is used. Also, regardless of the size
25643 specified, some additional space is allocated for task
25644 management purposes. On OpenVMS Alpha systems, at least
25645 one page is allocated.
25646
25647 GNAT handles task stacks in a similar manner. In accordance with
25648 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
25649 an alternative method for controlling the task stack size.
25650 The specification of the attribute @code{T'STORAGE_SIZE} is also
25651 supported in a manner compatible with HP Ada.
25652
25653 @node External Interrupts
25654 @subsection External Interrupts
25655
25656 @noindent
25657 On HP Ada, external interrupts can be associated with task entries.
25658 GNAT is compatible with HP Ada in its handling of external interrupts.
25659
25660 @node Pragmas and Pragma-Related Features
25661 @section Pragmas and Pragma-Related Features
25662
25663 @noindent
25664 Both HP Ada and GNAT supply all language-defined pragmas
25665 as specified by the Ada 83 standard. GNAT also supplies all
25666 language-defined pragmas introduced by Ada 95 and Ada 2005.
25667 In addition, GNAT implements the implementation-defined pragmas
25668 from HP Ada 83.
25669
25670 @itemize @bullet
25671 @item  @code{AST_ENTRY}
25672
25673 @item  @code{COMMON_OBJECT}
25674
25675 @item  @code{COMPONENT_ALIGNMENT}
25676
25677 @item  @code{EXPORT_EXCEPTION}
25678
25679 @item  @code{EXPORT_FUNCTION}
25680
25681 @item  @code{EXPORT_OBJECT}
25682
25683 @item  @code{EXPORT_PROCEDURE}
25684
25685 @item  @code{EXPORT_VALUED_PROCEDURE}
25686
25687 @item  @code{FLOAT_REPRESENTATION}
25688
25689 @item  @code{IDENT}
25690
25691 @item  @code{IMPORT_EXCEPTION}
25692
25693 @item  @code{IMPORT_FUNCTION}
25694
25695 @item  @code{IMPORT_OBJECT}
25696
25697 @item  @code{IMPORT_PROCEDURE}
25698
25699 @item  @code{IMPORT_VALUED_PROCEDURE}
25700
25701 @item  @code{INLINE_GENERIC}
25702
25703 @item  @code{INTERFACE_NAME}
25704
25705 @item  @code{LONG_FLOAT}
25706
25707 @item  @code{MAIN_STORAGE}
25708
25709 @item  @code{PASSIVE}
25710
25711 @item  @code{PSECT_OBJECT}
25712
25713 @item  @code{SHARE_GENERIC}
25714
25715 @item  @code{SUPPRESS_ALL}
25716
25717 @item  @code{TASK_STORAGE}
25718
25719 @item  @code{TIME_SLICE}
25720
25721 @item  @code{TITLE}
25722 @end itemize
25723
25724 @noindent
25725 These pragmas are all fully implemented, with the exception of @code{TITLE},
25726 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
25727 recognized, but which have no
25728 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
25729 use of Ada protected objects. In GNAT, all generics are inlined.
25730
25731 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
25732 a separate subprogram specification which must appear before the
25733 subprogram body.
25734
25735 GNAT also supplies a number of implementation-defined pragmas as follows:
25736 @itemize @bullet
25737 @item  @code{ABORT_DEFER}
25738
25739 @item  @code{ADA_83}
25740
25741 @item  @code{ADA_95}
25742
25743 @item  @code{ADA_05}
25744
25745 @item  @code{ANNOTATE}
25746
25747 @item  @code{ASSERT}
25748
25749 @item  @code{C_PASS_BY_COPY}
25750
25751 @item  @code{CPP_CLASS}
25752
25753 @item  @code{CPP_CONSTRUCTOR}
25754
25755 @item  @code{CPP_DESTRUCTOR}
25756
25757 @item  @code{DEBUG}
25758
25759 @item  @code{EXTEND_SYSTEM}
25760
25761 @item  @code{LINKER_ALIAS}
25762
25763 @item  @code{LINKER_SECTION}
25764
25765 @item  @code{MACHINE_ATTRIBUTE}
25766
25767 @item  @code{NO_RETURN}
25768
25769 @item  @code{PURE_FUNCTION}
25770
25771 @item  @code{SOURCE_FILE_NAME}
25772
25773 @item  @code{SOURCE_REFERENCE}
25774
25775 @item  @code{TASK_INFO}
25776
25777 @item  @code{UNCHECKED_UNION}
25778
25779 @item  @code{UNIMPLEMENTED_UNIT}
25780
25781 @item  @code{UNIVERSAL_DATA}
25782
25783 @item  @code{UNSUPPRESS}
25784
25785 @item  @code{WARNINGS}
25786
25787 @item  @code{WEAK_EXTERNAL}
25788 @end itemize
25789
25790 @noindent
25791 For full details on these GNAT implementation-defined pragmas,
25792 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
25793 Manual}.
25794
25795 @menu
25796 * Restrictions on the Pragma INLINE::
25797 * Restrictions on the Pragma INTERFACE::
25798 * Restrictions on the Pragma SYSTEM_NAME::
25799 @end menu
25800
25801 @node Restrictions on the Pragma INLINE
25802 @subsection Restrictions on Pragma @code{INLINE}
25803
25804 @noindent
25805 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
25806 @itemize @bullet
25807 @item  Parameters cannot have a task type.
25808
25809 @item  Function results cannot be task types, unconstrained
25810 array types, or unconstrained types with discriminants.
25811
25812 @item  Bodies cannot declare the following:
25813 @itemize @bullet
25814 @item  Subprogram body or stub (imported subprogram is allowed)
25815
25816 @item  Tasks
25817
25818 @item  Generic declarations
25819
25820 @item  Instantiations
25821
25822 @item  Exceptions
25823
25824 @item  Access types (types derived from access types allowed)
25825
25826 @item  Array or record types
25827
25828 @item  Dependent tasks
25829
25830 @item  Direct recursive calls of subprogram or containing
25831 subprogram, directly or via a renaming
25832
25833 @end itemize
25834 @end itemize
25835
25836 @noindent
25837 In GNAT, the only restriction on pragma @code{INLINE} is that the
25838 body must occur before the call if both are in the same
25839 unit, and the size must be appropriately small. There are
25840 no other specific restrictions which cause subprograms to
25841 be incapable of being inlined.
25842
25843 @node  Restrictions on the Pragma INTERFACE
25844 @subsection  Restrictions on Pragma @code{INTERFACE}
25845
25846 @noindent
25847 The following restrictions on pragma @code{INTERFACE}
25848 are enforced by both HP Ada and GNAT:
25849 @itemize @bullet
25850 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
25851 Default is the default on OpenVMS Alpha systems.
25852
25853 @item  Parameter passing: Language specifies default
25854 mechanisms but can be overridden with an @code{EXPORT} pragma.
25855
25856 @itemize @bullet
25857 @item  Ada: Use internal Ada rules.
25858
25859 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
25860 record or task type. Result cannot be a string, an
25861 array, or a record.
25862
25863 @item  Fortran: Parameters cannot have a task type. Result cannot
25864 be a string, an array, or a record.
25865 @end itemize
25866 @end itemize
25867
25868 @noindent
25869 GNAT is entirely upwards compatible with HP Ada, and in addition allows
25870 record parameters for all languages.
25871
25872 @node  Restrictions on the Pragma SYSTEM_NAME
25873 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
25874
25875 @noindent
25876 For HP Ada for OpenVMS Alpha, the enumeration literal
25877 for the type @code{NAME} is @code{OPENVMS_AXP}.
25878 In GNAT, the enumeration
25879 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
25880
25881 @node  Library of Predefined Units
25882 @section  Library of Predefined Units
25883
25884 @noindent
25885 A library of predefined units is provided as part of the
25886 HP Ada and GNAT implementations. HP Ada does not provide
25887 the package @code{MACHINE_CODE} but instead recommends importing
25888 assembler code.
25889
25890 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
25891 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
25892 version.
25893 The HP Ada Predefined Library units are modified to remove post-Ada 83
25894 incompatibilities and to make them interoperable with GNAT
25895 (@pxref{Changes to DECLIB}, for details).
25896 The units are located in the @file{DECLIB} directory.
25897
25898 The GNAT RTL is contained in
25899 the @file{ADALIB} directory, and
25900 the default search path is set up to find @code{DECLIB} units in preference
25901 to @code{ADALIB} units with the same name (@code{TEXT_IO},
25902 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
25903
25904 @menu
25905 * Changes to DECLIB::
25906 @end menu
25907
25908 @node Changes to DECLIB
25909 @subsection Changes to @code{DECLIB}
25910
25911 @noindent
25912 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
25913 compatibility are minor and include the following:
25914
25915 @itemize @bullet
25916 @item  Adjusting the location of pragmas and record representation
25917 clauses to obey Ada 95 (and thus Ada 2005) rules
25918
25919 @item  Adding the proper notation to generic formal parameters
25920 that take unconstrained types in instantiation
25921
25922 @item  Adding pragma @code{ELABORATE_BODY} to package specs
25923 that have package bodies not otherwise allowed
25924
25925 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
25926 ``@code{PROTECTD}''.
25927 Currently these are found only in the @code{STARLET} package spec.
25928
25929 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
25930 where the address size is constrained to 32 bits.
25931 @end itemize
25932
25933 @noindent
25934 None of the above changes is visible to users.
25935
25936 @node Bindings
25937 @section Bindings
25938
25939 @noindent
25940 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
25941 @itemize @bullet
25942
25943 @item  Command Language Interpreter (CLI interface)
25944
25945 @item  DECtalk Run-Time Library (DTK interface)
25946
25947 @item  Librarian utility routines (LBR interface)
25948
25949 @item  General Purpose Run-Time Library (LIB interface)
25950
25951 @item  Math Run-Time Library (MTH interface)
25952
25953 @item  National Character Set Run-Time Library (NCS interface)
25954
25955 @item  Compiled Code Support Run-Time Library (OTS interface)
25956
25957 @item  Parallel Processing Run-Time Library (PPL interface)
25958
25959 @item  Screen Management Run-Time Library (SMG interface)
25960
25961 @item  Sort Run-Time Library (SOR interface)
25962
25963 @item  String Run-Time Library (STR interface)
25964
25965 @item STARLET System Library
25966 @findex Starlet
25967
25968 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
25969
25970 @item  X Windows Toolkit (XT interface)
25971
25972 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
25973 @end itemize
25974
25975 @noindent
25976 GNAT provides implementations of these HP bindings in the @code{DECLIB}
25977 directory, on both the Alpha and I64 OpenVMS platforms.
25978
25979 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
25980 in the
25981 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
25982 A pragma @code{Linker_Options} has been added to packages @code{Xm},
25983 @code{Xt}, and @code{X_Lib}
25984 causing the default X/Motif sharable image libraries to be linked in. This
25985 is done via options files named @file{xm.opt}, @file{xt.opt}, and
25986 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
25987
25988 It may be necessary to edit these options files to update or correct the
25989 library names if, for example, the newer X/Motif bindings from
25990 @file{ADA$EXAMPLES}
25991 had been (previous to installing GNAT) copied and renamed to supersede the
25992 default @file{ADA$PREDEFINED} versions.
25993
25994 @menu
25995 * Shared Libraries and Options Files::
25996 * Interfaces to C::
25997 @end menu
25998
25999 @node Shared Libraries and Options Files
26000 @subsection Shared Libraries and Options Files
26001
26002 @noindent
26003 When using the HP Ada
26004 predefined X and Motif bindings, the linking with their sharable images is
26005 done automatically by @command{GNAT LINK}.
26006 When using other X and Motif bindings, you need
26007 to add the corresponding sharable images to the command line for
26008 @code{GNAT LINK}. When linking with shared libraries, or with
26009 @file{.OPT} files, you must
26010 also add them to the command line for @command{GNAT LINK}.
26011
26012 A shared library to be used with GNAT is built in the same way as other
26013 libraries under VMS. The VMS Link command can be used in standard fashion.
26014
26015 @node Interfaces to C
26016 @subsection Interfaces to C
26017
26018 @noindent
26019 HP Ada
26020 provides the following Ada types and operations:
26021
26022 @itemize @bullet
26023 @item C types package (@code{C_TYPES})
26024
26025 @item C strings (@code{C_TYPES.NULL_TERMINATED})
26026
26027 @item Other_types (@code{SHORT_INT})
26028 @end itemize
26029
26030 @noindent
26031 Interfacing to C with GNAT, you can use the above approach
26032 described for HP Ada or the facilities of Annex B of
26033 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
26034 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
26035 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
26036
26037 The @option{-gnatF} qualifier forces default and explicit
26038 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
26039 to be uppercased for compatibility with the default behavior
26040 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
26041
26042 @node Main Program Definition
26043 @section Main Program Definition
26044
26045 @noindent
26046 The following section discusses differences in the
26047 definition of main programs on HP Ada and GNAT.
26048 On HP Ada, main programs are defined to meet the
26049 following conditions:
26050 @itemize @bullet
26051 @item  Procedure with no formal parameters (returns @code{0} upon
26052 normal completion)
26053
26054 @item  Procedure with no formal parameters (returns @code{42} when
26055 an unhandled exception is raised)
26056
26057 @item  Function with no formal parameters whose returned value
26058 is of a discrete type
26059
26060 @item  Procedure with one @code{out} formal of a discrete type for
26061 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
26062
26063 @end itemize
26064
26065 @noindent
26066 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
26067 a main function or main procedure returns a discrete
26068 value whose size is less than 64 bits (32 on VAX systems),
26069 the value is zero- or sign-extended as appropriate.
26070 On GNAT, main programs are defined as follows:
26071 @itemize @bullet
26072 @item  Must be a non-generic, parameterless subprogram that
26073 is either a procedure or function returning an Ada
26074 @code{STANDARD.INTEGER} (the predefined type)
26075
26076 @item  Cannot be a generic subprogram or an instantiation of a
26077 generic subprogram
26078 @end itemize
26079
26080 @node Implementation-Defined Attributes
26081 @section Implementation-Defined Attributes
26082
26083 @noindent
26084 GNAT provides all HP Ada implementation-defined
26085 attributes.
26086
26087 @node Compiler and Run-Time Interfacing
26088 @section Compiler and Run-Time Interfacing
26089
26090 @noindent
26091 HP Ada provides the following qualifiers to pass options to the linker
26092 (ACS LINK):
26093 @itemize @bullet
26094 @item  @option{/WAIT} and @option{/SUBMIT}
26095
26096 @item  @option{/COMMAND}
26097
26098 @item  @option{/@r{[}NO@r{]}MAP}
26099
26100 @item  @option{/OUTPUT=@var{file-spec}}
26101
26102 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26103 @end itemize
26104
26105 @noindent
26106 To pass options to the linker, GNAT provides the following
26107 switches:
26108
26109 @itemize @bullet
26110 @item   @option{/EXECUTABLE=@var{exec-name}}
26111
26112 @item   @option{/VERBOSE}
26113
26114 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26115 @end itemize
26116
26117 @noindent
26118 For more information on these switches, see
26119 @ref{Switches for gnatlink}.
26120 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
26121 to control optimization. HP Ada also supplies the
26122 following pragmas:
26123 @itemize @bullet
26124 @item  @code{OPTIMIZE}
26125
26126 @item  @code{INLINE}
26127
26128 @item  @code{INLINE_GENERIC}
26129
26130 @item  @code{SUPPRESS_ALL}
26131
26132 @item  @code{PASSIVE}
26133 @end itemize
26134
26135 @noindent
26136 In GNAT, optimization is controlled strictly by command
26137 line parameters, as described in the corresponding section of this guide.
26138 The HP pragmas for control of optimization are
26139 recognized but ignored.
26140
26141 Note that in GNAT, the default is optimization off, whereas in HP Ada
26142 the default is that optimization is turned on.
26143
26144 @node Program Compilation and Library Management
26145 @section Program Compilation and Library Management
26146
26147 @noindent
26148 HP Ada and GNAT provide a comparable set of commands to
26149 build programs. HP Ada also provides a program library,
26150 which is a concept that does not exist on GNAT. Instead,
26151 GNAT provides directories of sources that are compiled as
26152 needed.
26153
26154 The following table summarizes
26155 the HP Ada commands and provides
26156 equivalent GNAT commands. In this table, some GNAT
26157 equivalents reflect the fact that GNAT does not use the
26158 concept of a program library. Instead, it uses a model
26159 in which collections of source and object files are used
26160 in a manner consistent with other languages like C and
26161 Fortran. Therefore, standard system file commands are used
26162 to manipulate these elements. Those GNAT commands are marked with
26163 an asterisk.
26164 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
26165
26166 @need 1500
26167 @multitable @columnfractions .35 .65
26168
26169 @item @emph{HP Ada Command}
26170 @tab @emph{GNAT Equivalent / Description}
26171
26172 @item @command{ADA}
26173 @tab @command{GNAT COMPILE}@*
26174 Invokes the compiler to compile one or more Ada source files.
26175
26176 @item @command{ACS ATTACH}@*
26177 @tab [No equivalent]@*
26178 Switches control of terminal from current process running the program
26179 library manager.
26180
26181 @item @command{ACS CHECK}
26182 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
26183 Forms the execution closure of one
26184 or more compiled units and checks completeness and currency.
26185
26186 @item @command{ACS COMPILE}
26187 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26188 Forms the execution closure of one or
26189 more specified units, checks completeness and currency,
26190 identifies units that have revised source files, compiles same,
26191 and recompiles units that are or will become obsolete.
26192 Also completes incomplete generic instantiations.
26193
26194 @item @command{ACS COPY FOREIGN}
26195 @tab Copy (*)@*
26196 Copies a foreign object file into the program library as a
26197 library unit body.
26198
26199 @item @command{ACS COPY UNIT}
26200 @tab Copy (*)@*
26201 Copies a compiled unit from one program library to another.
26202
26203 @item @command{ACS CREATE LIBRARY}
26204 @tab Create /directory (*)@*
26205 Creates a program library.
26206
26207 @item @command{ACS CREATE SUBLIBRARY}
26208 @tab Create /directory (*)@*
26209 Creates a program sublibrary.
26210
26211 @item @command{ACS DELETE LIBRARY}
26212 @tab @*
26213 Deletes a program library and its contents.
26214
26215 @item @command{ACS DELETE SUBLIBRARY}
26216 @tab @*
26217 Deletes a program sublibrary and its contents.
26218
26219 @item @command{ACS DELETE UNIT}
26220 @tab Delete file (*)@*
26221 On OpenVMS systems, deletes one or more compiled units from
26222 the current program library.
26223
26224 @item @command{ACS DIRECTORY}
26225 @tab Directory (*)@*
26226 On OpenVMS systems, lists units contained in the current
26227 program library.
26228
26229 @item @command{ACS ENTER FOREIGN}
26230 @tab Copy (*)@*
26231 Allows the import of a foreign body as an Ada library
26232 spec and enters a reference to a pointer.
26233
26234 @item @command{ACS ENTER UNIT}
26235 @tab Copy (*)@*
26236 Enters a reference (pointer) from the current program library to
26237 a unit compiled into another program library.
26238
26239 @item @command{ACS EXIT}
26240 @tab [No equivalent]@*
26241 Exits from the program library manager.
26242
26243 @item @command{ACS EXPORT}
26244 @tab Copy (*)@*
26245 Creates an object file that contains system-specific object code
26246 for one or more units. With GNAT, object files can simply be copied
26247 into the desired directory.
26248
26249 @item @command{ACS EXTRACT SOURCE}
26250 @tab Copy (*)@*
26251 Allows access to the copied source file for each Ada compilation unit
26252
26253 @item @command{ACS HELP}
26254 @tab @command{HELP GNAT}@*
26255 Provides online help.
26256
26257 @item @command{ACS LINK}
26258 @tab @command{GNAT LINK}@*
26259 Links an object file containing Ada units into an executable file.
26260
26261 @item @command{ACS LOAD}
26262 @tab Copy (*)@*
26263 Loads (partially compiles) Ada units into the program library.
26264 Allows loading a program from a collection of files into a library
26265 without knowing the relationship among units.
26266
26267 @item @command{ACS MERGE}
26268 @tab Copy (*)@*
26269 Merges into the current program library, one or more units from
26270 another library where they were modified.
26271
26272 @item @command{ACS RECOMPILE}
26273 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26274 Recompiles from   external or copied source files any obsolete
26275 unit in the closure. Also, completes any incomplete generic
26276 instantiations.
26277
26278 @item @command{ACS REENTER}
26279 @tab @command{GNAT MAKE}@*
26280 Reenters current references to units compiled after last entered
26281 with the @command{ACS ENTER UNIT} command.
26282
26283 @item @command{ACS SET LIBRARY}
26284 @tab Set default (*)@*
26285 Defines a program library to be the compilation context as well
26286 as the target library for compiler output and commands in general.
26287
26288 @item @command{ACS SET PRAGMA}
26289 @tab Edit @file{gnat.adc} (*)@*
26290 Redefines specified  values of the library characteristics
26291 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
26292 and @code{Float_Representation}.
26293
26294 @item @command{ACS SET SOURCE}
26295 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
26296 Defines the source file search list for the @command{ACS COMPILE} command.
26297
26298 @item @command{ACS SHOW LIBRARY}
26299 @tab Directory (*)@*
26300 Lists information about one or more program libraries.
26301
26302 @item @command{ACS SHOW PROGRAM}
26303 @tab [No equivalent]@*
26304 Lists information about the execution closure of one or
26305 more units in the program library.
26306
26307 @item @command{ACS SHOW SOURCE}
26308 @tab Show logical @code{ADA_INCLUDE_PATH}@*
26309 Shows the source file search used when compiling units.
26310
26311 @item @command{ACS SHOW VERSION}
26312 @tab Compile with @option{VERBOSE} option
26313 Displays the version number of the compiler and program library
26314 manager used.
26315
26316 @item @command{ACS SPAWN}
26317 @tab [No equivalent]@*
26318 Creates a subprocess of the current process (same as @command{DCL SPAWN}
26319 command).
26320
26321 @item @command{ACS VERIFY}
26322 @tab [No equivalent]@*
26323 Performs a series of consistency checks on a program library to
26324 determine whether the library structure and library files are in
26325 valid form.
26326 @end multitable
26327
26328 @noindent
26329
26330 @node Input-Output
26331 @section Input-Output
26332
26333 @noindent
26334 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
26335 Management Services (RMS) to perform operations on
26336 external files.
26337
26338 @noindent
26339 HP Ada and GNAT predefine an identical set of input-
26340 output packages. To make the use of the
26341 generic @code{TEXT_IO} operations more convenient, HP Ada
26342 provides predefined library packages that instantiate the
26343 integer and floating-point operations for the predefined
26344 integer and floating-point types as shown in the following table.
26345
26346 @multitable @columnfractions .45 .55
26347 @item @emph{Package Name} @tab Instantiation
26348
26349 @item @code{INTEGER_TEXT_IO}
26350 @tab @code{INTEGER_IO(INTEGER)}
26351
26352 @item @code{SHORT_INTEGER_TEXT_IO}
26353 @tab @code{INTEGER_IO(SHORT_INTEGER)}
26354
26355 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
26356 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
26357
26358 @item @code{FLOAT_TEXT_IO}
26359 @tab @code{FLOAT_IO(FLOAT)}
26360
26361 @item @code{LONG_FLOAT_TEXT_IO}
26362 @tab @code{FLOAT_IO(LONG_FLOAT)}
26363 @end multitable
26364
26365 @noindent
26366 The HP Ada predefined packages and their operations
26367 are implemented using OpenVMS Alpha files and input-output
26368 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
26369 Familiarity with the following is recommended:
26370 @itemize @bullet
26371 @item  RMS file organizations and access methods
26372
26373 @item  OpenVMS file specifications and directories
26374
26375 @item  OpenVMS File Definition Language (FDL)
26376 @end itemize
26377
26378 @noindent
26379 GNAT provides I/O facilities that are completely
26380 compatible with HP Ada. The distribution includes the
26381 standard HP Ada versions of all I/O packages, operating
26382 in a manner compatible with HP Ada. In particular, the
26383 following packages are by default the HP Ada (Ada 83)
26384 versions of these packages rather than the renamings
26385 suggested in Annex J of the Ada Reference Manual:
26386 @itemize @bullet
26387 @item  @code{TEXT_IO}
26388
26389 @item  @code{SEQUENTIAL_IO}
26390
26391 @item  @code{DIRECT_IO}
26392 @end itemize
26393
26394 @noindent
26395 The use of the standard child package syntax (for
26396 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
26397 packages.
26398 GNAT provides HP-compatible predefined instantiations
26399 of the @code{TEXT_IO} packages, and also
26400 provides the standard predefined instantiations required
26401 by the @cite{Ada Reference Manual}.
26402
26403 For further information on how GNAT interfaces to the file
26404 system or how I/O is implemented in programs written in
26405 mixed languages, see @ref{Implementation of the Standard I/O,,,
26406 gnat_rm, GNAT Reference Manual}.
26407 This chapter covers the following:
26408 @itemize @bullet
26409 @item  Standard I/O packages
26410
26411 @item  @code{FORM} strings
26412
26413 @item  @code{ADA.DIRECT_IO}
26414
26415 @item  @code{ADA.SEQUENTIAL_IO}
26416
26417 @item  @code{ADA.TEXT_IO}
26418
26419 @item  Stream pointer positioning
26420
26421 @item  Reading and writing non-regular files
26422
26423 @item  @code{GET_IMMEDIATE}
26424
26425 @item  Treating @code{TEXT_IO} files as streams
26426
26427 @item  Shared files
26428
26429 @item  Open modes
26430 @end itemize
26431
26432 @node Implementation Limits
26433 @section Implementation Limits
26434
26435 @noindent
26436 The following table lists implementation limits for HP Ada
26437 and GNAT systems.
26438 @multitable @columnfractions .60 .20 .20
26439 @sp 1
26440 @item  @emph{Compilation Parameter}
26441 @tab   @emph{HP Ada}
26442 @tab   @emph{GNAT}
26443 @sp 1
26444
26445 @item  In a subprogram or entry  declaration, maximum number of
26446 formal parameters that are of an unconstrained record type
26447 @tab   32
26448 @tab   No set limit
26449 @sp 1
26450
26451 @item  Maximum identifier length (number of characters)
26452 @tab   255
26453 @tab   32766
26454 @sp 1
26455
26456 @item  Maximum number of characters in a source line
26457 @tab   255
26458 @tab   32766
26459 @sp 1
26460
26461 @item  Maximum collection size   (number of bytes)
26462 @tab   2**31-1
26463 @tab   2**31-1
26464 @sp 1
26465
26466 @item  Maximum number of discriminants for a record type
26467 @tab   245
26468 @tab   No set limit
26469 @sp 1
26470
26471 @item  Maximum number of formal parameters in an entry or
26472 subprogram declaration
26473 @tab   246
26474 @tab    No set limit
26475 @sp 1
26476
26477 @item  Maximum number of dimensions in an array type
26478 @tab   255
26479 @tab   No set limit
26480 @sp 1
26481
26482 @item  Maximum number of library  units and subunits in a compilation.
26483 @tab   4095
26484 @tab   No set limit
26485 @sp 1
26486
26487 @item  Maximum number of library units and subunits in an execution.
26488 @tab   16383
26489 @tab   No set limit
26490 @sp 1
26491
26492 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
26493 or @code{PSECT_OBJECT}
26494 @tab   32757
26495 @tab   No set limit
26496 @sp 1
26497
26498 @item  Maximum number of enumeration literals in an enumeration type
26499 definition
26500 @tab   65535
26501 @tab   No set limit
26502 @sp 1
26503
26504 @item  Maximum number of lines in a source file
26505 @tab   65534
26506 @tab   No set limit
26507 @sp 1
26508
26509 @item  Maximum number of bits in any object
26510 @tab   2**31-1
26511 @tab   2**31-1
26512 @sp 1
26513
26514 @item  Maximum size of the static portion of a stack frame (approximate)
26515 @tab   2**31-1
26516 @tab   2**31-1
26517 @end multitable
26518
26519 @node Tools and Utilities
26520 @section Tools and Utilities
26521
26522 @noindent
26523 The following table lists some of the OpenVMS development tools
26524 available for HP Ada, and the corresponding tools for
26525 use with @value{EDITION} on Alpha and I64 platforms.
26526 Aside from the debugger, all the OpenVMS tools identified are part
26527 of the DECset package.
26528
26529 @iftex
26530 @c Specify table in TeX since Texinfo does a poor job
26531 @tex
26532 \smallskip
26533 \smallskip
26534 \settabs\+Language-Sensitive Editor\quad
26535    &Product with HP Ada\quad
26536    &\cr
26537 \+\it Tool
26538    &\it Product with HP Ada
26539    & \it Product with GNAT Pro\cr
26540 \smallskip
26541 \+Code Management System
26542    &HP CMS
26543    & HP CMS\cr
26544 \smallskip
26545 \+Language-Sensitive Editor
26546    &HP LSE
26547    & emacs or HP LSE (Alpha)\cr
26548 \+
26549    &
26550    & HP LSE (I64)\cr
26551 \smallskip
26552 \+Debugger
26553    &OpenVMS Debug
26554    & gdb (Alpha),\cr
26555 \+
26556    &
26557    & OpenVMS Debug (I64)\cr
26558 \smallskip
26559 \+Source Code Analyzer /
26560    &HP SCA
26561    & GNAT XREF\cr
26562 \+Cross Referencer
26563    &
26564    &\cr
26565 \smallskip
26566 \+Test Manager
26567    &HP Digital Test
26568    & HP DTM\cr
26569 \+
26570    &Manager (DTM)
26571    &\cr
26572 \smallskip
26573 \+Performance and
26574    & HP PCA
26575    & HP PCA\cr
26576 \+Coverage Analyzer
26577    &
26578    &\cr
26579 \smallskip
26580 \+Module Management
26581    & HP MMS
26582    & Not applicable\cr
26583 \+ System
26584    &
26585    &\cr
26586 \smallskip
26587 \smallskip
26588 @end tex
26589 @end iftex
26590
26591 @ifnottex
26592 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
26593 @c the TeX version above for the printed version
26594 @flushleft
26595 @c @multitable @columnfractions .3 .4 .4
26596 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
26597 @item @i{Tool}
26598 @tab @i{Tool with HP Ada}
26599 @tab @i{Tool with @value{EDITION}}
26600 @item Code Management@*System
26601 @tab HP CMS
26602 @tab HP CMS
26603 @item Language-Sensitive@*Editor
26604 @tab HP LSE
26605 @tab emacs or HP LSE (Alpha)
26606 @item
26607 @tab
26608 @tab HP LSE (I64)
26609 @item Debugger
26610 @tab OpenVMS Debug
26611 @tab gdb (Alpha),
26612 @item
26613 @tab
26614 @tab OpenVMS Debug (I64)
26615 @item Source Code Analyzer /@*Cross Referencer
26616 @tab HP SCA
26617 @tab GNAT XREF
26618 @item Test Manager
26619 @tab HP Digital Test@*Manager (DTM)
26620 @tab HP DTM
26621 @item Performance and@*Coverage Analyzer
26622 @tab HP PCA
26623 @tab HP PCA
26624 @item Module Management@*System
26625 @tab HP MMS
26626 @tab Not applicable
26627 @end multitable
26628 @end flushleft
26629 @end ifnottex
26630
26631 @end ifset
26632
26633 @c **************************************
26634 @node Platform-Specific Information for the Run-Time Libraries
26635 @appendix Platform-Specific Information for the Run-Time Libraries
26636 @cindex Tasking and threads libraries
26637 @cindex Threads libraries and tasking
26638 @cindex Run-time libraries (platform-specific information)
26639
26640 @noindent
26641 The GNAT run-time implementation may vary with respect to both the
26642 underlying threads library and the exception handling scheme.
26643 For threads support, one or more of the following are supplied:
26644 @itemize @bullet
26645 @item @b{native threads library}, a binding to the thread package from
26646 the underlying operating system
26647
26648 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
26649 POSIX thread package
26650 @end itemize
26651
26652 @noindent
26653 For exception handling, either or both of two models are supplied:
26654 @itemize @bullet
26655 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
26656 Most programs should experience a substantial speed improvement by
26657 being compiled with a ZCX run-time.
26658 This is especially true for
26659 tasking applications or applications with many exception handlers.}
26660 @cindex Zero-Cost Exceptions
26661 @cindex ZCX (Zero-Cost Exceptions)
26662 which uses binder-generated tables that
26663 are interrogated at run time to locate a handler
26664
26665 @item @b{setjmp / longjmp} (``SJLJ''),
26666 @cindex setjmp/longjmp Exception Model
26667 @cindex SJLJ (setjmp/longjmp Exception Model)
26668 which uses dynamically-set data to establish
26669 the set of handlers
26670 @end itemize
26671
26672 @noindent
26673 This appendix summarizes which combinations of threads and exception support
26674 are supplied on various GNAT platforms.
26675 It then shows how to select a particular library either
26676 permanently or temporarily,
26677 explains the properties of (and tradeoffs among) the various threads
26678 libraries, and provides some additional
26679 information about several specific platforms.
26680
26681 @menu
26682 * Summary of Run-Time Configurations::
26683 * Specifying a Run-Time Library::
26684 * Choosing the Scheduling Policy::
26685 * Solaris-Specific Considerations::
26686 * Linux-Specific Considerations::
26687 * AIX-Specific Considerations::
26688 * Irix-Specific Considerations::
26689 * RTX-Specific Considerations::
26690 @end menu
26691
26692 @node Summary of Run-Time Configurations
26693 @section Summary of Run-Time Configurations
26694
26695 @multitable @columnfractions .30 .70
26696 @item @b{alpha-openvms}
26697 @item @code{@ @ }@i{rts-native (default)}
26698 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26699 @item @code{@ @ @ @ }Exceptions @tab ZCX
26700 @*
26701 @item @b{alpha-tru64}
26702 @item @code{@ @ }@i{rts-native (default)}
26703 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26704 @item @code{@ @ @ @ }Exceptions @tab ZCX
26705 @*
26706 @item @code{@ @ }@i{rts-sjlj}
26707 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26708 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26709 @*
26710 @item @b{ia64-hp_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{ia64-hpux}
26716 @item @code{@ @ }@i{rts-native (default)}
26717 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26718 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26719 @*
26720 @item @b{ia64-openvms}
26721 @item @code{@ @ }@i{rts-native (default)}
26722 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26723 @item @code{@ @ @ @ }Exceptions @tab ZCX
26724 @*
26725 @item @b{ia64-sgi_linux}
26726 @item @code{@ @ }@i{rts-native (default)}
26727 @item @code{@ @ @ @ }Tasking    @tab pthread library
26728 @item @code{@ @ @ @ }Exceptions @tab ZCX
26729 @*
26730 @item @b{mips-irix}
26731 @item @code{@ @ }@i{rts-native (default)}
26732 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
26733 @item @code{@ @ @ @ }Exceptions @tab ZCX
26734 @*
26735 @item @b{pa-hpux}
26736 @item @code{@ @ }@i{rts-native (default)}
26737 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26738 @item @code{@ @ @ @ }Exceptions @tab ZCX
26739 @*
26740 @item @code{@ @ }@i{rts-sjlj}
26741 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26742 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26743 @*
26744 @item @b{ppc-aix}
26745 @item @code{@ @ }@i{rts-native (default)}
26746 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
26747 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26748 @*
26749 @item @b{ppc-darwin}
26750 @item @code{@ @ }@i{rts-native (default)}
26751 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
26752 @item @code{@ @ @ @ }Exceptions @tab ZCX
26753 @*
26754 @item @b{sparc-solaris}  @tab
26755 @item @code{@ @ }@i{rts-native (default)}
26756 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26757 @item @code{@ @ @ @ }Exceptions @tab ZCX
26758 @*
26759 @item @code{@ @ }@i{rts-pthread}
26760 @item @code{@ @ @ @ }Tasking    @tab pthread library
26761 @item @code{@ @ @ @ }Exceptions @tab ZCX
26762 @*
26763 @item @code{@ @ }@i{rts-sjlj}
26764 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26765 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26766 @*
26767 @item @b{sparc64-solaris}  @tab
26768 @item @code{@ @ }@i{rts-native (default)}
26769 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26770 @item @code{@ @ @ @ }Exceptions @tab ZCX
26771 @*
26772 @item @b{x86-linux}
26773 @item @code{@ @ }@i{rts-native (default)}
26774 @item @code{@ @ @ @ }Tasking    @tab pthread library
26775 @item @code{@ @ @ @ }Exceptions @tab ZCX
26776 @*
26777 @item @code{@ @ }@i{rts-sjlj}
26778 @item @code{@ @ @ @ }Tasking    @tab pthread library
26779 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26780 @*
26781 @item @b{x86-lynx}
26782 @item @code{@ @ }@i{rts-native (default)}
26783 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
26784 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26785 @*
26786 @item @b{x86-solaris}
26787 @item @code{@ @ }@i{rts-native (default)}
26788 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
26789 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26790 @*
26791 @item @b{x86-windows}
26792 @item @code{@ @ }@i{rts-native (default)}
26793 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
26794 @item @code{@ @ @ @ }Exceptions @tab ZCX
26795 @*
26796 @item @code{@ @ }@i{rts-sjlj (default)}
26797 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
26798 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26799 @*
26800 @item @b{x86-windows-rtx}
26801 @item @code{@ @ }@i{rts-rtx-rtss (default)}
26802 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
26803 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26804 @*
26805 @item @code{@ @ }@i{rts-rtx-w32}
26806 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
26807 @item @code{@ @ @ @ }Exceptions @tab ZCX
26808 @*
26809 @item @b{x86_64-linux}
26810 @item @code{@ @ }@i{rts-native (default)}
26811 @item @code{@ @ @ @ }Tasking    @tab pthread library
26812 @item @code{@ @ @ @ }Exceptions @tab ZCX
26813 @*
26814 @item @code{@ @ }@i{rts-sjlj}
26815 @item @code{@ @ @ @ }Tasking    @tab pthread library
26816 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26817 @*
26818 @end multitable
26819
26820 @node Specifying a Run-Time Library
26821 @section Specifying a Run-Time Library
26822
26823 @noindent
26824 The @file{adainclude} subdirectory containing the sources of the GNAT
26825 run-time library, and the @file{adalib} subdirectory containing the
26826 @file{ALI} files and the static and/or shared GNAT library, are located
26827 in the gcc target-dependent area:
26828
26829 @smallexample
26830 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
26831 @end smallexample
26832
26833 @noindent
26834 As indicated above, on some platforms several run-time libraries are supplied.
26835 These libraries are installed in the target dependent area and
26836 contain a complete source and binary subdirectory. The detailed description
26837 below explains the differences between the different libraries in terms of
26838 their thread support.
26839
26840 The default run-time library (when GNAT is installed) is @emph{rts-native}.
26841 This default run time is selected by the means of soft links.
26842 For example on x86-linux:
26843
26844 @smallexample
26845 @group
26846  $(target-dir)
26847      |
26848      +--- adainclude----------+
26849      |                        |
26850      +--- adalib-----------+  |
26851      |                     |  |
26852      +--- rts-native       |  |
26853      |    |                |  |
26854      |    +--- adainclude <---+
26855      |    |                |
26856      |    +--- adalib <----+
26857      |
26858      +--- rts-sjlj
26859           |
26860           +--- adainclude
26861           |
26862           +--- adalib
26863 @end group
26864 @end smallexample
26865
26866 @noindent
26867 If the @i{rts-sjlj} library is to be selected on a permanent basis,
26868 these soft links can be modified with the following commands:
26869
26870 @smallexample
26871 $ cd $target
26872 $ rm -f adainclude adalib
26873 $ ln -s rts-sjlj/adainclude adainclude
26874 $ ln -s rts-sjlj/adalib adalib
26875 @end smallexample
26876
26877 @noindent
26878 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
26879 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
26880 @file{$target/ada_object_path}.
26881
26882 Selecting another run-time library temporarily can be
26883 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
26884 @cindex @option{--RTS} option
26885
26886 @node Choosing the Scheduling Policy
26887 @section Choosing the Scheduling Policy
26888
26889 @noindent
26890 When using a POSIX threads implementation, you have a choice of several
26891 scheduling policies: @code{SCHED_FIFO},
26892 @cindex @code{SCHED_FIFO} scheduling policy
26893 @code{SCHED_RR}
26894 @cindex @code{SCHED_RR} scheduling policy
26895 and @code{SCHED_OTHER}.
26896 @cindex @code{SCHED_OTHER} scheduling policy
26897 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
26898 or @code{SCHED_RR} requires special (e.g., root) privileges.
26899
26900 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
26901 @code{SCHED_FIFO},
26902 @cindex @code{SCHED_FIFO} scheduling policy
26903 you can use one of the following:
26904
26905 @itemize @bullet
26906 @item
26907 @code{pragma Time_Slice (0.0)}
26908 @cindex pragma Time_Slice
26909 @item
26910 the corresponding binder option @option{-T0}
26911 @cindex @option{-T0} option
26912 @item
26913 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
26914 @cindex pragma Task_Dispatching_Policy
26915 @end itemize
26916
26917 @noindent
26918 To specify @code{SCHED_RR},
26919 @cindex @code{SCHED_RR} scheduling policy
26920 you should use @code{pragma Time_Slice} with a
26921 value greater than @code{0.0}, or else use the corresponding @option{-T}
26922 binder option.
26923
26924 @node Solaris-Specific Considerations
26925 @section Solaris-Specific Considerations
26926 @cindex Solaris Sparc threads libraries
26927
26928 @noindent
26929 This section addresses some topics related to the various threads libraries
26930 on Sparc Solaris.
26931
26932 @menu
26933 * Solaris Threads Issues::
26934 @end menu
26935
26936 @node Solaris Threads Issues
26937 @subsection Solaris Threads Issues
26938
26939 @noindent
26940 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
26941 library based on POSIX threads --- @emph{rts-pthread}.
26942 @cindex rts-pthread threads library
26943 This run-time library has the advantage of being mostly shared across all
26944 POSIX-compliant thread implementations, and it also provides under
26945 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
26946 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
26947 and @code{PTHREAD_PRIO_PROTECT}
26948 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
26949 semantics that can be selected using the predefined pragma
26950 @code{Locking_Policy}
26951 @cindex pragma Locking_Policy (under rts-pthread)
26952 with respectively
26953 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
26954 @cindex @code{Inheritance_Locking} (under rts-pthread)
26955 @cindex @code{Ceiling_Locking} (under rts-pthread)
26956
26957 As explained above, the native run-time library is based on the Solaris thread
26958 library (@code{libthread}) and is the default library.
26959
26960 When the Solaris threads library is used (this is the default), programs
26961 compiled with GNAT can automatically take advantage of
26962 and can thus execute on multiple processors.
26963 The user can alternatively specify a processor on which the program should run
26964 to emulate a single-processor system. The multiprocessor / uniprocessor choice
26965 is made by
26966 setting the environment variable @env{GNAT_PROCESSOR}
26967 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
26968 to one of the following:
26969
26970 @table @code
26971 @item -2
26972 Use the default configuration (run the program on all
26973 available processors) - this is the same as having @code{GNAT_PROCESSOR}
26974 unset
26975
26976 @item -1
26977 Let the run-time implementation choose one processor and run the program on
26978 that processor
26979
26980 @item 0 .. Last_Proc
26981 Run the program on the specified processor.
26982 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
26983 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
26984 @end table
26985
26986 @node Linux-Specific Considerations
26987 @section Linux-Specific Considerations
26988 @cindex Linux threads libraries
26989
26990 @noindent
26991 On GNU/Linux without NPTL support (usually system with GNU C Library
26992 older than 2.3), the signal model is not POSIX compliant, which means
26993 that to send a signal to the process, you need to send the signal to all
26994 threads, e.g.@: by using @code{killpg()}.
26995
26996 @node AIX-Specific Considerations
26997 @section AIX-Specific Considerations
26998 @cindex AIX resolver library
26999
27000 @noindent
27001 On AIX, the resolver library initializes some internal structure on
27002 the first call to @code{get*by*} functions, which are used to implement
27003 @code{GNAT.Sockets.Get_Host_By_Name} and
27004 @code{GNAT.Sockets.Get_Host_By_Address}.
27005 If such initialization occurs within an Ada task, and the stack size for
27006 the task is the default size, a stack overflow may occur.
27007
27008 To avoid this overflow, the user should either ensure that the first call
27009 to @code{GNAT.Sockets.Get_Host_By_Name} or
27010 @code{GNAT.Sockets.Get_Host_By_Addrss}
27011 occurs in the environment task, or use @code{pragma Storage_Size} to
27012 specify a sufficiently large size for the stack of the task that contains
27013 this call.
27014
27015 @node Irix-Specific Considerations
27016 @section Irix-Specific Considerations
27017 @cindex Irix libraries
27018
27019 @noindent
27020 The GCC support libraries coming with the Irix compiler have moved to
27021 their canonical place with respect to the general Irix ABI related
27022 conventions. Running applications built with the default shared GNAT
27023 run-time now requires the LD_LIBRARY_PATH environment variable to
27024 include this location. A possible way to achieve this is to issue the
27025 following command line on a bash prompt:
27026
27027 @smallexample
27028 @group
27029 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
27030 @end group
27031 @end smallexample
27032
27033 @node RTX-Specific Considerations
27034 @section RTX-Specific Considerations
27035 @cindex RTX libraries
27036
27037 @noindent
27038 The Real-time Extension (RTX) to Windows is based on the Windows Win32
27039 API. Applications can be built to work in two different modes:
27040
27041 @itemize @bullet
27042 @item
27043 Windows executables that run in Ring 3 to utilize memory protection
27044 (@emph{rts-rtx-w32}).
27045
27046 @item
27047 Real-time subsystem (RTSS) executables that run in Ring 0, where
27048 performance can be optimized with RTSS applications taking precedent
27049 over all Windows applications (@emph{rts-rtx-rtss}).
27050
27051 @end itemize
27052
27053 @c *******************************
27054 @node Example of Binder Output File
27055 @appendix Example of Binder Output File
27056
27057 @noindent
27058 This Appendix displays the source code for @command{gnatbind}'s output
27059 file generated for a simple ``Hello World'' program.
27060 Comments have been added for clarification purposes.
27061
27062 @smallexample @c adanocomment
27063 @iftex
27064 @leftskip=0cm
27065 @end iftex
27066 --  The package is called Ada_Main unless this name is actually used
27067 --  as a unit name in the partition, in which case some other unique
27068 --  name is used.
27069
27070 with System;
27071 package ada_main is
27072
27073    Elab_Final_Code : Integer;
27074    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
27075
27076    --  The main program saves the parameters (argument count,
27077    --  argument values, environment pointer) in global variables
27078    --  for later access by other units including
27079    --  Ada.Command_Line.
27080
27081    gnat_argc : Integer;
27082    gnat_argv : System.Address;
27083    gnat_envp : System.Address;
27084
27085    --  The actual variables are stored in a library routine. This
27086    --  is useful for some shared library situations, where there
27087    --  are problems if variables are not in the library.
27088
27089    pragma Import (C, gnat_argc);
27090    pragma Import (C, gnat_argv);
27091    pragma Import (C, gnat_envp);
27092
27093    --  The exit status is similarly an external location
27094
27095    gnat_exit_status : Integer;
27096    pragma Import (C, gnat_exit_status);
27097
27098    GNAT_Version : constant String :=
27099                     "GNAT Version: 6.0.0w (20061115)";
27100    pragma Export (C, GNAT_Version, "__gnat_version");
27101
27102    --  This is the generated adafinal routine that performs
27103    --  finalization at the end of execution. In the case where
27104    --  Ada is the main program, this main program makes a call
27105    --  to adafinal at program termination.
27106
27107    procedure adafinal;
27108    pragma Export (C, adafinal, "adafinal");
27109
27110    --  This is the generated adainit routine that performs
27111    --  initialization at the start of execution. In the case
27112    --  where Ada is the main program, this main program makes
27113    --  a call to adainit at program startup.
27114
27115    procedure adainit;
27116    pragma Export (C, adainit, "adainit");
27117
27118    --  This routine is called at the start of execution. It is
27119    --  a dummy routine that is used by the debugger to breakpoint
27120    --  at the start of execution.
27121
27122    procedure Break_Start;
27123    pragma Import (C, Break_Start, "__gnat_break_start");
27124
27125    --  This is the actual generated main program (it would be
27126    --  suppressed if the no main program switch were used). As
27127    --  required by standard system conventions, this program has
27128    --  the external name main.
27129
27130    function main
27131      (argc : Integer;
27132       argv : System.Address;
27133       envp : System.Address)
27134       return Integer;
27135    pragma Export (C, main, "main");
27136
27137    --  The following set of constants give the version
27138    --  identification values for every unit in the bound
27139    --  partition. This identification is computed from all
27140    --  dependent semantic units, and corresponds to the
27141    --  string that would be returned by use of the
27142    --  Body_Version or Version attributes.
27143
27144    type Version_32 is mod 2 ** 32;
27145    u00001 : constant Version_32 := 16#7880BEB3#;
27146    u00002 : constant Version_32 := 16#0D24CBD0#;
27147    u00003 : constant Version_32 := 16#3283DBEB#;
27148    u00004 : constant Version_32 := 16#2359F9ED#;
27149    u00005 : constant Version_32 := 16#664FB847#;
27150    u00006 : constant Version_32 := 16#68E803DF#;
27151    u00007 : constant Version_32 := 16#5572E604#;
27152    u00008 : constant Version_32 := 16#46B173D8#;
27153    u00009 : constant Version_32 := 16#156A40CF#;
27154    u00010 : constant Version_32 := 16#033DABE0#;
27155    u00011 : constant Version_32 := 16#6AB38FEA#;
27156    u00012 : constant Version_32 := 16#22B6217D#;
27157    u00013 : constant Version_32 := 16#68A22947#;
27158    u00014 : constant Version_32 := 16#18CC4A56#;
27159    u00015 : constant Version_32 := 16#08258E1B#;
27160    u00016 : constant Version_32 := 16#367D5222#;
27161    u00017 : constant Version_32 := 16#20C9ECA4#;
27162    u00018 : constant Version_32 := 16#50D32CB6#;
27163    u00019 : constant Version_32 := 16#39A8BB77#;
27164    u00020 : constant Version_32 := 16#5CF8FA2B#;
27165    u00021 : constant Version_32 := 16#2F1EB794#;
27166    u00022 : constant Version_32 := 16#31AB6444#;
27167    u00023 : constant Version_32 := 16#1574B6E9#;
27168    u00024 : constant Version_32 := 16#5109C189#;
27169    u00025 : constant Version_32 := 16#56D770CD#;
27170    u00026 : constant Version_32 := 16#02F9DE3D#;
27171    u00027 : constant Version_32 := 16#08AB6B2C#;
27172    u00028 : constant Version_32 := 16#3FA37670#;
27173    u00029 : constant Version_32 := 16#476457A0#;
27174    u00030 : constant Version_32 := 16#731E1B6E#;
27175    u00031 : constant Version_32 := 16#23C2E789#;
27176    u00032 : constant Version_32 := 16#0F1BD6A1#;
27177    u00033 : constant Version_32 := 16#7C25DE96#;
27178    u00034 : constant Version_32 := 16#39ADFFA2#;
27179    u00035 : constant Version_32 := 16#571DE3E7#;
27180    u00036 : constant Version_32 := 16#5EB646AB#;
27181    u00037 : constant Version_32 := 16#4249379B#;
27182    u00038 : constant Version_32 := 16#0357E00A#;
27183    u00039 : constant Version_32 := 16#3784FB72#;
27184    u00040 : constant Version_32 := 16#2E723019#;
27185    u00041 : constant Version_32 := 16#623358EA#;
27186    u00042 : constant Version_32 := 16#107F9465#;
27187    u00043 : constant Version_32 := 16#6843F68A#;
27188    u00044 : constant Version_32 := 16#63305874#;
27189    u00045 : constant Version_32 := 16#31E56CE1#;
27190    u00046 : constant Version_32 := 16#02917970#;
27191    u00047 : constant Version_32 := 16#6CCBA70E#;
27192    u00048 : constant Version_32 := 16#41CD4204#;
27193    u00049 : constant Version_32 := 16#572E3F58#;
27194    u00050 : constant Version_32 := 16#20729FF5#;
27195    u00051 : constant Version_32 := 16#1D4F93E8#;
27196    u00052 : constant Version_32 := 16#30B2EC3D#;
27197    u00053 : constant Version_32 := 16#34054F96#;
27198    u00054 : constant Version_32 := 16#5A199860#;
27199    u00055 : constant Version_32 := 16#0E7F912B#;
27200    u00056 : constant Version_32 := 16#5760634A#;
27201    u00057 : constant Version_32 := 16#5D851835#;
27202
27203    --  The following Export pragmas export the version numbers
27204    --  with symbolic names ending in B (for body) or S
27205    --  (for spec) so that they can be located in a link. The
27206    --  information provided here is sufficient to track down
27207    --  the exact versions of units used in a given build.
27208
27209    pragma Export (C, u00001, "helloB");
27210    pragma Export (C, u00002, "system__standard_libraryB");
27211    pragma Export (C, u00003, "system__standard_libraryS");
27212    pragma Export (C, u00004, "adaS");
27213    pragma Export (C, u00005, "ada__text_ioB");
27214    pragma Export (C, u00006, "ada__text_ioS");
27215    pragma Export (C, u00007, "ada__exceptionsB");
27216    pragma Export (C, u00008, "ada__exceptionsS");
27217    pragma Export (C, u00009, "gnatS");
27218    pragma Export (C, u00010, "gnat__heap_sort_aB");
27219    pragma Export (C, u00011, "gnat__heap_sort_aS");
27220    pragma Export (C, u00012, "systemS");
27221    pragma Export (C, u00013, "system__exception_tableB");
27222    pragma Export (C, u00014, "system__exception_tableS");
27223    pragma Export (C, u00015, "gnat__htableB");
27224    pragma Export (C, u00016, "gnat__htableS");
27225    pragma Export (C, u00017, "system__exceptionsS");
27226    pragma Export (C, u00018, "system__machine_state_operationsB");
27227    pragma Export (C, u00019, "system__machine_state_operationsS");
27228    pragma Export (C, u00020, "system__machine_codeS");
27229    pragma Export (C, u00021, "system__storage_elementsB");
27230    pragma Export (C, u00022, "system__storage_elementsS");
27231    pragma Export (C, u00023, "system__secondary_stackB");
27232    pragma Export (C, u00024, "system__secondary_stackS");
27233    pragma Export (C, u00025, "system__parametersB");
27234    pragma Export (C, u00026, "system__parametersS");
27235    pragma Export (C, u00027, "system__soft_linksB");
27236    pragma Export (C, u00028, "system__soft_linksS");
27237    pragma Export (C, u00029, "system__stack_checkingB");
27238    pragma Export (C, u00030, "system__stack_checkingS");
27239    pragma Export (C, u00031, "system__tracebackB");
27240    pragma Export (C, u00032, "system__tracebackS");
27241    pragma Export (C, u00033, "ada__streamsS");
27242    pragma Export (C, u00034, "ada__tagsB");
27243    pragma Export (C, u00035, "ada__tagsS");
27244    pragma Export (C, u00036, "system__string_opsB");
27245    pragma Export (C, u00037, "system__string_opsS");
27246    pragma Export (C, u00038, "interfacesS");
27247    pragma Export (C, u00039, "interfaces__c_streamsB");
27248    pragma Export (C, u00040, "interfaces__c_streamsS");
27249    pragma Export (C, u00041, "system__file_ioB");
27250    pragma Export (C, u00042, "system__file_ioS");
27251    pragma Export (C, u00043, "ada__finalizationB");
27252    pragma Export (C, u00044, "ada__finalizationS");
27253    pragma Export (C, u00045, "system__finalization_rootB");
27254    pragma Export (C, u00046, "system__finalization_rootS");
27255    pragma Export (C, u00047, "system__finalization_implementationB");
27256    pragma Export (C, u00048, "system__finalization_implementationS");
27257    pragma Export (C, u00049, "system__string_ops_concat_3B");
27258    pragma Export (C, u00050, "system__string_ops_concat_3S");
27259    pragma Export (C, u00051, "system__stream_attributesB");
27260    pragma Export (C, u00052, "system__stream_attributesS");
27261    pragma Export (C, u00053, "ada__io_exceptionsS");
27262    pragma Export (C, u00054, "system__unsigned_typesS");
27263    pragma Export (C, u00055, "system__file_control_blockS");
27264    pragma Export (C, u00056, "ada__finalization__list_controllerB");
27265    pragma Export (C, u00057, "ada__finalization__list_controllerS");
27266
27267    -- BEGIN ELABORATION ORDER
27268    -- ada (spec)
27269    -- gnat (spec)
27270    -- gnat.heap_sort_a (spec)
27271    -- gnat.heap_sort_a (body)
27272    -- gnat.htable (spec)
27273    -- gnat.htable (body)
27274    -- interfaces (spec)
27275    -- system (spec)
27276    -- system.machine_code (spec)
27277    -- system.parameters (spec)
27278    -- system.parameters (body)
27279    -- interfaces.c_streams (spec)
27280    -- interfaces.c_streams (body)
27281    -- system.standard_library (spec)
27282    -- ada.exceptions (spec)
27283    -- system.exception_table (spec)
27284    -- system.exception_table (body)
27285    -- ada.io_exceptions (spec)
27286    -- system.exceptions (spec)
27287    -- system.storage_elements (spec)
27288    -- system.storage_elements (body)
27289    -- system.machine_state_operations (spec)
27290    -- system.machine_state_operations (body)
27291    -- system.secondary_stack (spec)
27292    -- system.stack_checking (spec)
27293    -- system.soft_links (spec)
27294    -- system.soft_links (body)
27295    -- system.stack_checking (body)
27296    -- system.secondary_stack (body)
27297    -- system.standard_library (body)
27298    -- system.string_ops (spec)
27299    -- system.string_ops (body)
27300    -- ada.tags (spec)
27301    -- ada.tags (body)
27302    -- ada.streams (spec)
27303    -- system.finalization_root (spec)
27304    -- system.finalization_root (body)
27305    -- system.string_ops_concat_3 (spec)
27306    -- system.string_ops_concat_3 (body)
27307    -- system.traceback (spec)
27308    -- system.traceback (body)
27309    -- ada.exceptions (body)
27310    -- system.unsigned_types (spec)
27311    -- system.stream_attributes (spec)
27312    -- system.stream_attributes (body)
27313    -- system.finalization_implementation (spec)
27314    -- system.finalization_implementation (body)
27315    -- ada.finalization (spec)
27316    -- ada.finalization (body)
27317    -- ada.finalization.list_controller (spec)
27318    -- ada.finalization.list_controller (body)
27319    -- system.file_control_block (spec)
27320    -- system.file_io (spec)
27321    -- system.file_io (body)
27322    -- ada.text_io (spec)
27323    -- ada.text_io (body)
27324    -- hello (body)
27325    -- END ELABORATION ORDER
27326
27327 end ada_main;
27328
27329 --  The following source file name pragmas allow the generated file
27330 --  names to be unique for different main programs. They are needed
27331 --  since the package name will always be Ada_Main.
27332
27333 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
27334 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
27335
27336 --  Generated package body for Ada_Main starts here
27337
27338 package body ada_main is
27339
27340    --  The actual finalization is performed by calling the
27341    --  library routine in System.Standard_Library.Adafinal
27342
27343    procedure Do_Finalize;
27344    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
27345
27346    -------------
27347    -- adainit --
27348    -------------
27349
27350 @findex adainit
27351    procedure adainit is
27352
27353       --  These booleans are set to True once the associated unit has
27354       --  been elaborated. It is also used to avoid elaborating the
27355       --  same unit twice.
27356
27357       E040 : Boolean;
27358       pragma Import (Ada, E040, "interfaces__c_streams_E");
27359
27360       E008 : Boolean;
27361       pragma Import (Ada, E008, "ada__exceptions_E");
27362
27363       E014 : Boolean;
27364       pragma Import (Ada, E014, "system__exception_table_E");
27365
27366       E053 : Boolean;
27367       pragma Import (Ada, E053, "ada__io_exceptions_E");
27368
27369       E017 : Boolean;
27370       pragma Import (Ada, E017, "system__exceptions_E");
27371
27372       E024 : Boolean;
27373       pragma Import (Ada, E024, "system__secondary_stack_E");
27374
27375       E030 : Boolean;
27376       pragma Import (Ada, E030, "system__stack_checking_E");
27377
27378       E028 : Boolean;
27379       pragma Import (Ada, E028, "system__soft_links_E");
27380
27381       E035 : Boolean;
27382       pragma Import (Ada, E035, "ada__tags_E");
27383
27384       E033 : Boolean;
27385       pragma Import (Ada, E033, "ada__streams_E");
27386
27387       E046 : Boolean;
27388       pragma Import (Ada, E046, "system__finalization_root_E");
27389
27390       E048 : Boolean;
27391       pragma Import (Ada, E048, "system__finalization_implementation_E");
27392
27393       E044 : Boolean;
27394       pragma Import (Ada, E044, "ada__finalization_E");
27395
27396       E057 : Boolean;
27397       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
27398
27399       E055 : Boolean;
27400       pragma Import (Ada, E055, "system__file_control_block_E");
27401
27402       E042 : Boolean;
27403       pragma Import (Ada, E042, "system__file_io_E");
27404
27405       E006 : Boolean;
27406       pragma Import (Ada, E006, "ada__text_io_E");
27407
27408       --  Set_Globals is a library routine that stores away the
27409       --  value of the indicated set of global values in global
27410       --  variables within the library.
27411
27412       procedure Set_Globals
27413         (Main_Priority            : Integer;
27414          Time_Slice_Value         : Integer;
27415          WC_Encoding              : Character;
27416          Locking_Policy           : Character;
27417          Queuing_Policy           : Character;
27418          Task_Dispatching_Policy  : Character;
27419          Adafinal                 : System.Address;
27420          Unreserve_All_Interrupts : Integer;
27421          Exception_Tracebacks     : Integer);
27422 @findex __gnat_set_globals
27423       pragma Import (C, Set_Globals, "__gnat_set_globals");
27424
27425       --  SDP_Table_Build is a library routine used to build the
27426       --  exception tables. See unit Ada.Exceptions in files
27427       --  a-except.ads/adb for full details of how zero cost
27428       --  exception handling works. This procedure, the call to
27429       --  it, and the two following tables are all omitted if the
27430       --  build is in longjmp/setjmp exception mode.
27431
27432 @findex SDP_Table_Build
27433 @findex Zero Cost Exceptions
27434       procedure SDP_Table_Build
27435         (SDP_Addresses   : System.Address;
27436          SDP_Count       : Natural;
27437          Elab_Addresses  : System.Address;
27438          Elab_Addr_Count : Natural);
27439       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
27440
27441       --  Table of Unit_Exception_Table addresses. Used for zero
27442       --  cost exception handling to build the top level table.
27443
27444       ST : aliased constant array (1 .. 23) of System.Address := (
27445         Hello'UET_Address,
27446         Ada.Text_Io'UET_Address,
27447         Ada.Exceptions'UET_Address,
27448         Gnat.Heap_Sort_A'UET_Address,
27449         System.Exception_Table'UET_Address,
27450         System.Machine_State_Operations'UET_Address,
27451         System.Secondary_Stack'UET_Address,
27452         System.Parameters'UET_Address,
27453         System.Soft_Links'UET_Address,
27454         System.Stack_Checking'UET_Address,
27455         System.Traceback'UET_Address,
27456         Ada.Streams'UET_Address,
27457         Ada.Tags'UET_Address,
27458         System.String_Ops'UET_Address,
27459         Interfaces.C_Streams'UET_Address,
27460         System.File_Io'UET_Address,
27461         Ada.Finalization'UET_Address,
27462         System.Finalization_Root'UET_Address,
27463         System.Finalization_Implementation'UET_Address,
27464         System.String_Ops_Concat_3'UET_Address,
27465         System.Stream_Attributes'UET_Address,
27466         System.File_Control_Block'UET_Address,
27467         Ada.Finalization.List_Controller'UET_Address);
27468
27469       --  Table of addresses of elaboration routines. Used for
27470       --  zero cost exception handling to make sure these
27471       --  addresses are included in the top level procedure
27472       --  address table.
27473
27474       EA : aliased constant array (1 .. 23) of System.Address := (
27475         adainit'Code_Address,
27476         Do_Finalize'Code_Address,
27477         Ada.Exceptions'Elab_Spec'Address,
27478         System.Exceptions'Elab_Spec'Address,
27479         Interfaces.C_Streams'Elab_Spec'Address,
27480         System.Exception_Table'Elab_Body'Address,
27481         Ada.Io_Exceptions'Elab_Spec'Address,
27482         System.Stack_Checking'Elab_Spec'Address,
27483         System.Soft_Links'Elab_Body'Address,
27484         System.Secondary_Stack'Elab_Body'Address,
27485         Ada.Tags'Elab_Spec'Address,
27486         Ada.Tags'Elab_Body'Address,
27487         Ada.Streams'Elab_Spec'Address,
27488         System.Finalization_Root'Elab_Spec'Address,
27489         Ada.Exceptions'Elab_Body'Address,
27490         System.Finalization_Implementation'Elab_Spec'Address,
27491         System.Finalization_Implementation'Elab_Body'Address,
27492         Ada.Finalization'Elab_Spec'Address,
27493         Ada.Finalization.List_Controller'Elab_Spec'Address,
27494         System.File_Control_Block'Elab_Spec'Address,
27495         System.File_Io'Elab_Body'Address,
27496         Ada.Text_Io'Elab_Spec'Address,
27497         Ada.Text_Io'Elab_Body'Address);
27498
27499    --  Start of processing for adainit
27500
27501    begin
27502
27503       --  Call SDP_Table_Build to build the top level procedure
27504       --  table for zero cost exception handling (omitted in
27505       --  longjmp/setjmp mode).
27506
27507       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
27508
27509       --  Call Set_Globals to record various information for
27510       --  this partition.  The values are derived by the binder
27511       --  from information stored in the ali files by the compiler.
27512
27513 @findex __gnat_set_globals
27514       Set_Globals
27515         (Main_Priority            => -1,
27516          --  Priority of main program, -1 if no pragma Priority used
27517
27518          Time_Slice_Value         => -1,
27519          --  Time slice from Time_Slice pragma, -1 if none used
27520
27521          WC_Encoding              => 'b',
27522          --  Wide_Character encoding used, default is brackets
27523
27524          Locking_Policy           => ' ',
27525          --  Locking_Policy used, default of space means not
27526          --  specified, otherwise it is the first character of
27527          --  the policy name.
27528
27529          Queuing_Policy           => ' ',
27530          --  Queuing_Policy used, default of space means not
27531          --  specified, otherwise it is the first character of
27532          --  the policy name.
27533
27534          Task_Dispatching_Policy  => ' ',
27535          --  Task_Dispatching_Policy used, default of space means
27536          --  not specified, otherwise first character of the
27537          --  policy name.
27538
27539          Adafinal                 => System.Null_Address,
27540          --  Address of Adafinal routine, not used anymore
27541
27542          Unreserve_All_Interrupts => 0,
27543          --  Set true if pragma Unreserve_All_Interrupts was used
27544
27545          Exception_Tracebacks     => 0);
27546          --  Indicates if exception tracebacks are enabled
27547
27548       Elab_Final_Code := 1;
27549
27550       --  Now we have the elaboration calls for all units in the partition.
27551       --  The Elab_Spec and Elab_Body attributes generate references to the
27552       --  implicit elaboration procedures generated by the compiler for
27553       --  each unit that requires elaboration.
27554
27555       if not E040 then
27556          Interfaces.C_Streams'Elab_Spec;
27557       end if;
27558       E040 := True;
27559       if not E008 then
27560          Ada.Exceptions'Elab_Spec;
27561       end if;
27562       if not E014 then
27563          System.Exception_Table'Elab_Body;
27564          E014 := True;
27565       end if;
27566       if not E053 then
27567          Ada.Io_Exceptions'Elab_Spec;
27568          E053 := True;
27569       end if;
27570       if not E017 then
27571          System.Exceptions'Elab_Spec;
27572          E017 := True;
27573       end if;
27574       if not E030 then
27575          System.Stack_Checking'Elab_Spec;
27576       end if;
27577       if not E028 then
27578          System.Soft_Links'Elab_Body;
27579          E028 := True;
27580       end if;
27581       E030 := True;
27582       if not E024 then
27583          System.Secondary_Stack'Elab_Body;
27584          E024 := True;
27585       end if;
27586       if not E035 then
27587          Ada.Tags'Elab_Spec;
27588       end if;
27589       if not E035 then
27590          Ada.Tags'Elab_Body;
27591          E035 := True;
27592       end if;
27593       if not E033 then
27594          Ada.Streams'Elab_Spec;
27595          E033 := True;
27596       end if;
27597       if not E046 then
27598          System.Finalization_Root'Elab_Spec;
27599       end if;
27600       E046 := True;
27601       if not E008 then
27602          Ada.Exceptions'Elab_Body;
27603          E008 := True;
27604       end if;
27605       if not E048 then
27606          System.Finalization_Implementation'Elab_Spec;
27607       end if;
27608       if not E048 then
27609          System.Finalization_Implementation'Elab_Body;
27610          E048 := True;
27611       end if;
27612       if not E044 then
27613          Ada.Finalization'Elab_Spec;
27614       end if;
27615       E044 := True;
27616       if not E057 then
27617          Ada.Finalization.List_Controller'Elab_Spec;
27618       end if;
27619       E057 := True;
27620       if not E055 then
27621          System.File_Control_Block'Elab_Spec;
27622          E055 := True;
27623       end if;
27624       if not E042 then
27625          System.File_Io'Elab_Body;
27626          E042 := True;
27627       end if;
27628       if not E006 then
27629          Ada.Text_Io'Elab_Spec;
27630       end if;
27631       if not E006 then
27632          Ada.Text_Io'Elab_Body;
27633          E006 := True;
27634       end if;
27635
27636       Elab_Final_Code := 0;
27637    end adainit;
27638
27639    --------------
27640    -- adafinal --
27641    --------------
27642
27643 @findex adafinal
27644    procedure adafinal is
27645    begin
27646       Do_Finalize;
27647    end adafinal;
27648
27649    ----------
27650    -- main --
27651    ----------
27652
27653    --  main is actually a function, as in the ANSI C standard,
27654    --  defined to return the exit status. The three parameters
27655    --  are the argument count, argument values and environment
27656    --  pointer.
27657
27658 @findex Main Program
27659    function main
27660      (argc : Integer;
27661       argv : System.Address;
27662       envp : System.Address)
27663       return Integer
27664    is
27665       --  The initialize routine performs low level system
27666       --  initialization using a standard library routine which
27667       --  sets up signal handling and performs any other
27668       --  required setup. The routine can be found in file
27669       --  a-init.c.
27670
27671 @findex __gnat_initialize
27672       procedure initialize;
27673       pragma Import (C, initialize, "__gnat_initialize");
27674
27675       --  The finalize routine performs low level system
27676       --  finalization using a standard library routine. The
27677       --  routine is found in file a-final.c and in the standard
27678       --  distribution is a dummy routine that does nothing, so
27679       --  really this is a hook for special user finalization.
27680
27681 @findex __gnat_finalize
27682       procedure finalize;
27683       pragma Import (C, finalize, "__gnat_finalize");
27684
27685       --  We get to the main program of the partition by using
27686       --  pragma Import because if we try to with the unit and
27687       --  call it Ada style, then not only do we waste time
27688       --  recompiling it, but also, we don't really know the right
27689       --  switches (e.g.@: identifier character set) to be used
27690       --  to compile it.
27691
27692       procedure Ada_Main_Program;
27693       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
27694
27695    --  Start of processing for main
27696
27697    begin
27698       --  Save global variables
27699
27700       gnat_argc := argc;
27701       gnat_argv := argv;
27702       gnat_envp := envp;
27703
27704       --  Call low level system initialization
27705
27706       Initialize;
27707
27708       --  Call our generated Ada initialization routine
27709
27710       adainit;
27711
27712       --  This is the point at which we want the debugger to get
27713       --  control
27714
27715       Break_Start;
27716
27717       --  Now we call the main program of the partition
27718
27719       Ada_Main_Program;
27720
27721       --  Perform Ada finalization
27722
27723       adafinal;
27724
27725       --  Perform low level system finalization
27726
27727       Finalize;
27728
27729       --  Return the proper exit status
27730       return (gnat_exit_status);
27731    end;
27732
27733 --  This section is entirely comments, so it has no effect on the
27734 --  compilation of the Ada_Main package. It provides the list of
27735 --  object files and linker options, as well as some standard
27736 --  libraries needed for the link. The gnatlink utility parses
27737 --  this b~hello.adb file to read these comment lines to generate
27738 --  the appropriate command line arguments for the call to the
27739 --  system linker. The BEGIN/END lines are used for sentinels for
27740 --  this parsing operation.
27741
27742 --  The exact file names will of course depend on the environment,
27743 --  host/target and location of files on the host system.
27744
27745 @findex Object file list
27746 -- BEGIN Object file/option list
27747    --   ./hello.o
27748    --   -L./
27749    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
27750    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
27751 -- END Object file/option list
27752
27753 end ada_main;
27754 @end smallexample
27755
27756 @noindent
27757 The Ada code in the above example is exactly what is generated by the
27758 binder. We have added comments to more clearly indicate the function
27759 of each part of the generated @code{Ada_Main} package.
27760
27761 The code is standard Ada in all respects, and can be processed by any
27762 tools that handle Ada. In particular, it is possible to use the debugger
27763 in Ada mode to debug the generated @code{Ada_Main} package. For example,
27764 suppose that for reasons that you do not understand, your program is crashing
27765 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
27766 you can place a breakpoint on the call:
27767
27768 @smallexample @c ada
27769 Ada.Text_Io'Elab_Body;
27770 @end smallexample
27771
27772 @noindent
27773 and trace the elaboration routine for this package to find out where
27774 the problem might be (more usually of course you would be debugging
27775 elaboration code in your own application).
27776
27777 @node Elaboration Order Handling in GNAT
27778 @appendix Elaboration Order Handling in GNAT
27779 @cindex Order of elaboration
27780 @cindex Elaboration control
27781
27782 @menu
27783 * Elaboration Code::
27784 * Checking the Elaboration Order::
27785 * Controlling the Elaboration Order::
27786 * Controlling Elaboration in GNAT - Internal Calls::
27787 * Controlling Elaboration in GNAT - External Calls::
27788 * Default Behavior in GNAT - Ensuring Safety::
27789 * Treatment of Pragma Elaborate::
27790 * Elaboration Issues for Library Tasks::
27791 * Mixing Elaboration Models::
27792 * What to Do If the Default Elaboration Behavior Fails::
27793 * Elaboration for Access-to-Subprogram Values::
27794 * Summary of Procedures for Elaboration Control::
27795 * Other Elaboration Order Considerations::
27796 @end menu
27797
27798 @noindent
27799 This chapter describes the handling of elaboration code in Ada and
27800 in GNAT, and discusses how the order of elaboration of program units can
27801 be controlled in GNAT, either automatically or with explicit programming
27802 features.
27803
27804 @node Elaboration Code
27805 @section Elaboration Code
27806
27807 @noindent
27808 Ada provides rather general mechanisms for executing code at elaboration
27809 time, that is to say before the main program starts executing. Such code arises
27810 in three contexts:
27811
27812 @table @asis
27813 @item Initializers for variables.
27814 Variables declared at the library level, in package specs or bodies, can
27815 require initialization that is performed at elaboration time, as in:
27816 @smallexample @c ada
27817 @cartouche
27818 Sqrt_Half : Float := Sqrt (0.5);
27819 @end cartouche
27820 @end smallexample
27821
27822 @item Package initialization code
27823 Code in a @code{BEGIN-END} section at the outer level of a package body is
27824 executed as part of the package body elaboration code.
27825
27826 @item Library level task allocators
27827 Tasks that are declared using task allocators at the library level
27828 start executing immediately and hence can execute at elaboration time.
27829 @end table
27830
27831 @noindent
27832 Subprogram calls are possible in any of these contexts, which means that
27833 any arbitrary part of the program may be executed as part of the elaboration
27834 code. It is even possible to write a program which does all its work at
27835 elaboration time, with a null main program, although stylistically this
27836 would usually be considered an inappropriate way to structure
27837 a program.
27838
27839 An important concern arises in the context of elaboration code:
27840 we have to be sure that it is executed in an appropriate order. What we
27841 have is a series of elaboration code sections, potentially one section
27842 for each unit in the program. It is important that these execute
27843 in the correct order. Correctness here means that, taking the above
27844 example of the declaration of @code{Sqrt_Half},
27845 if some other piece of
27846 elaboration code references @code{Sqrt_Half},
27847 then it must run after the
27848 section of elaboration code that contains the declaration of
27849 @code{Sqrt_Half}.
27850
27851 There would never be any order of elaboration problem if we made a rule
27852 that whenever you @code{with} a unit, you must elaborate both the spec and body
27853 of that unit before elaborating the unit doing the @code{with}'ing:
27854
27855 @smallexample @c ada
27856 @group
27857 @cartouche
27858 with Unit_1;
27859 package Unit_2 is @dots{}
27860 @end cartouche
27861 @end group
27862 @end smallexample
27863
27864 @noindent
27865 would require that both the body and spec of @code{Unit_1} be elaborated
27866 before the spec of @code{Unit_2}. However, a rule like that would be far too
27867 restrictive. In particular, it would make it impossible to have routines
27868 in separate packages that were mutually recursive.
27869
27870 You might think that a clever enough compiler could look at the actual
27871 elaboration code and determine an appropriate correct order of elaboration,
27872 but in the general case, this is not possible. Consider the following
27873 example.
27874
27875 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
27876 that references
27877 the variable @code{Sqrt_1}, which is declared in the elaboration code
27878 of the body of @code{Unit_1}:
27879
27880 @smallexample @c ada
27881 @cartouche
27882 Sqrt_1 : Float := Sqrt (0.1);
27883 @end cartouche
27884 @end smallexample
27885
27886 @noindent
27887 The elaboration code of the body of @code{Unit_1} also contains:
27888
27889 @smallexample @c ada
27890 @group
27891 @cartouche
27892 if expression_1 = 1 then
27893    Q := Unit_2.Func_2;
27894 end if;
27895 @end cartouche
27896 @end group
27897 @end smallexample
27898
27899 @noindent
27900 @code{Unit_2} is exactly parallel,
27901 it has a procedure @code{Func_2} that references
27902 the variable @code{Sqrt_2}, which is declared in the elaboration code of
27903 the body @code{Unit_2}:
27904
27905 @smallexample @c ada
27906 @cartouche
27907 Sqrt_2 : Float := Sqrt (0.1);
27908 @end cartouche
27909 @end smallexample
27910
27911 @noindent
27912 The elaboration code of the body of @code{Unit_2} also contains:
27913
27914 @smallexample @c ada
27915 @group
27916 @cartouche
27917 if expression_2 = 2 then
27918    Q := Unit_1.Func_1;
27919 end if;
27920 @end cartouche
27921 @end group
27922 @end smallexample
27923
27924 @noindent
27925 Now the question is, which of the following orders of elaboration is
27926 acceptable:
27927
27928 @smallexample
27929 @group
27930 Spec of Unit_1
27931 Spec of Unit_2
27932 Body of Unit_1
27933 Body of Unit_2
27934 @end group
27935 @end smallexample
27936
27937 @noindent
27938 or
27939
27940 @smallexample
27941 @group
27942 Spec of Unit_2
27943 Spec of Unit_1
27944 Body of Unit_2
27945 Body of Unit_1
27946 @end group
27947 @end smallexample
27948
27949 @noindent
27950 If you carefully analyze the flow here, you will see that you cannot tell
27951 at compile time the answer to this question.
27952 If @code{expression_1} is not equal to 1,
27953 and @code{expression_2} is not equal to 2,
27954 then either order is acceptable, because neither of the function calls is
27955 executed. If both tests evaluate to true, then neither order is acceptable
27956 and in fact there is no correct order.
27957
27958 If one of the two expressions is true, and the other is false, then one
27959 of the above orders is correct, and the other is incorrect. For example,
27960 if @code{expression_1} /= 1 and @code{expression_2} = 2,
27961 then the call to @code{Func_1}
27962 will occur, but not the call to @code{Func_2.}
27963 This means that it is essential
27964 to elaborate the body of @code{Unit_1} before
27965 the body of @code{Unit_2}, so the first
27966 order of elaboration is correct and the second is wrong.
27967
27968 By making @code{expression_1} and @code{expression_2}
27969 depend on input data, or perhaps
27970 the time of day, we can make it impossible for the compiler or binder
27971 to figure out which of these expressions will be true, and hence it
27972 is impossible to guarantee a safe order of elaboration at run time.
27973
27974 @node Checking the Elaboration Order
27975 @section Checking the Elaboration Order
27976
27977 @noindent
27978 In some languages that involve the same kind of elaboration problems,
27979 e.g.@: Java and C++, the programmer is expected to worry about these
27980 ordering problems himself, and it is common to
27981 write a program in which an incorrect elaboration order  gives
27982 surprising results, because it references variables before they
27983 are initialized.
27984 Ada is designed to be a safe language, and a programmer-beware approach is
27985 clearly not sufficient. Consequently, the language provides three lines
27986 of defense:
27987
27988 @table @asis
27989 @item Standard rules
27990 Some standard rules restrict the possible choice of elaboration
27991 order. In particular, if you @code{with} a unit, then its spec is always
27992 elaborated before the unit doing the @code{with}. Similarly, a parent
27993 spec is always elaborated before the child spec, and finally
27994 a spec is always elaborated before its corresponding body.
27995
27996 @item Dynamic elaboration checks
27997 @cindex Elaboration checks
27998 @cindex Checks, elaboration
27999 Dynamic checks are made at run time, so that if some entity is accessed
28000 before it is elaborated (typically  by means of a subprogram call)
28001 then the exception (@code{Program_Error}) is raised.
28002
28003 @item Elaboration control
28004 Facilities are provided for the programmer to specify the desired order
28005 of elaboration.
28006 @end table
28007
28008 Let's look at these facilities in more detail. First, the rules for
28009 dynamic checking. One possible rule would be simply to say that the
28010 exception is raised if you access a variable which has not yet been
28011 elaborated. The trouble with this approach is that it could require
28012 expensive checks on every variable reference. Instead Ada has two
28013 rules which are a little more restrictive, but easier to check, and
28014 easier to state:
28015
28016 @table @asis
28017 @item Restrictions on calls
28018 A subprogram can only be called at elaboration time if its body
28019 has been elaborated. The rules for elaboration given above guarantee
28020 that the spec of the subprogram has been elaborated before the
28021 call, but not the body. If this rule is violated, then the
28022 exception @code{Program_Error} is raised.
28023
28024 @item Restrictions on instantiations
28025 A generic unit can only be instantiated if the body of the generic
28026 unit has been elaborated. Again, the rules for elaboration given above
28027 guarantee that the spec of the generic unit has been elaborated
28028 before the instantiation, but not the body. If this rule is
28029 violated, then the exception @code{Program_Error} is raised.
28030 @end table
28031
28032 @noindent
28033 The idea is that if the body has been elaborated, then any variables
28034 it references must have been elaborated; by checking for the body being
28035 elaborated we guarantee that none of its references causes any
28036 trouble. As we noted above, this is a little too restrictive, because a
28037 subprogram that has no non-local references in its body may in fact be safe
28038 to call. However, it really would be unsafe to rely on this, because
28039 it would mean that the caller was aware of details of the implementation
28040 in the body. This goes against the basic tenets of Ada.
28041
28042 A plausible implementation can be described as follows.
28043 A Boolean variable is associated with each subprogram
28044 and each generic unit. This variable is initialized to False, and is set to
28045 True at the point body is elaborated. Every call or instantiation checks the
28046 variable, and raises @code{Program_Error} if the variable is False.
28047
28048 Note that one might think that it would be good enough to have one Boolean
28049 variable for each package, but that would not deal with cases of trying
28050 to call a body in the same package as the call
28051 that has not been elaborated yet.
28052 Of course a compiler may be able to do enough analysis to optimize away
28053 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
28054 does such optimizations, but still the easiest conceptual model is to
28055 think of there being one variable per subprogram.
28056
28057 @node Controlling the Elaboration Order
28058 @section Controlling the Elaboration Order
28059
28060 @noindent
28061 In the previous section we discussed the rules in Ada which ensure
28062 that @code{Program_Error} is raised if an incorrect elaboration order is
28063 chosen. This prevents erroneous executions, but we need mechanisms to
28064 specify a correct execution and avoid the exception altogether.
28065 To achieve this, Ada provides a number of features for controlling
28066 the order of elaboration. We discuss these features in this section.
28067
28068 First, there are several ways of indicating to the compiler that a given
28069 unit has no elaboration problems:
28070
28071 @table @asis
28072 @item packages that do not require a body
28073 A library package that does not require a body does not permit
28074 a body (this rule was introduced in Ada 95).
28075 Thus if we have a such a package, as in:
28076
28077 @smallexample @c ada
28078 @group
28079 @cartouche
28080 package Definitions is
28081    generic
28082       type m is new integer;
28083    package Subp is
28084       type a is array (1 .. 10) of m;
28085       type b is array (1 .. 20) of m;
28086    end Subp;
28087 end Definitions;
28088 @end cartouche
28089 @end group
28090 @end smallexample
28091
28092 @noindent
28093 A package that @code{with}'s @code{Definitions} may safely instantiate
28094 @code{Definitions.Subp} because the compiler can determine that there
28095 definitely is no package body to worry about in this case
28096
28097 @item pragma Pure
28098 @cindex pragma Pure
28099 @findex Pure
28100 Places sufficient restrictions on a unit to guarantee that
28101 no call to any subprogram in the unit can result in an
28102 elaboration problem. This means that the compiler does not need
28103 to worry about the point of elaboration of such units, and in
28104 particular, does not need to check any calls to any subprograms
28105 in this unit.
28106
28107 @item pragma Preelaborate
28108 @findex Preelaborate
28109 @cindex pragma Preelaborate
28110 This pragma places slightly less stringent restrictions on a unit than
28111 does pragma Pure,
28112 but these restrictions are still sufficient to ensure that there
28113 are no elaboration problems with any calls to the unit.
28114
28115 @item pragma Elaborate_Body
28116 @findex Elaborate_Body
28117 @cindex pragma Elaborate_Body
28118 This pragma requires that the body of a unit be elaborated immediately
28119 after its spec. Suppose a unit @code{A} has such a pragma,
28120 and unit @code{B} does
28121 a @code{with} of unit @code{A}. Recall that the standard rules require
28122 the spec of unit @code{A}
28123 to be elaborated before the @code{with}'ing unit; given the pragma in
28124 @code{A}, we also know that the body of @code{A}
28125 will be elaborated before @code{B}, so
28126 that calls to @code{A} are safe and do not need a check.
28127 @end table
28128
28129 @noindent
28130 Note that,
28131 unlike pragma @code{Pure} and pragma @code{Preelaborate},
28132 the use of
28133 @code{Elaborate_Body} does not guarantee that the program is
28134 free of elaboration problems, because it may not be possible
28135 to satisfy the requested elaboration order.
28136 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
28137 If a programmer
28138 marks @code{Unit_1} as @code{Elaborate_Body},
28139 and not @code{Unit_2,} then the order of
28140 elaboration will be:
28141
28142 @smallexample
28143 @group
28144 Spec of Unit_2
28145 Spec of Unit_1
28146 Body of Unit_1
28147 Body of Unit_2
28148 @end group
28149 @end smallexample
28150
28151 @noindent
28152 Now that means that the call to @code{Func_1} in @code{Unit_2}
28153 need not be checked,
28154 it must be safe. But the call to @code{Func_2} in
28155 @code{Unit_1} may still fail if
28156 @code{Expression_1} is equal to 1,
28157 and the programmer must still take
28158 responsibility for this not being the case.
28159
28160 If all units carry a pragma @code{Elaborate_Body}, then all problems are
28161 eliminated, except for calls entirely within a body, which are
28162 in any case fully under programmer control. However, using the pragma
28163 everywhere is not always possible.
28164 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
28165 we marked both of them as having pragma @code{Elaborate_Body}, then
28166 clearly there would be no possible elaboration order.
28167
28168 The above pragmas allow a server to guarantee safe use by clients, and
28169 clearly this is the preferable approach. Consequently a good rule
28170 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
28171 and if this is not possible,
28172 mark them as @code{Elaborate_Body} if possible.
28173 As we have seen, there are situations where neither of these
28174 three pragmas can be used.
28175 So we also provide methods for clients to control the
28176 order of elaboration of the servers on which they depend:
28177
28178 @table @asis
28179 @item pragma Elaborate (unit)
28180 @findex Elaborate
28181 @cindex pragma Elaborate
28182 This pragma is placed in the context clause, after a @code{with} clause,
28183 and it requires that the body of the named unit be elaborated before
28184 the unit in which the pragma occurs. The idea is to use this pragma
28185 if the current unit calls at elaboration time, directly or indirectly,
28186 some subprogram in the named unit.
28187
28188 @item pragma Elaborate_All (unit)
28189 @findex Elaborate_All
28190 @cindex pragma Elaborate_All
28191 This is a stronger version of the Elaborate pragma. Consider the
28192 following example:
28193
28194 @smallexample
28195 Unit A @code{with}'s unit B and calls B.Func in elab code
28196 Unit B @code{with}'s unit C, and B.Func calls C.Func
28197 @end smallexample
28198
28199 @noindent
28200 Now if we put a pragma @code{Elaborate (B)}
28201 in unit @code{A}, this ensures that the
28202 body of @code{B} is elaborated before the call, but not the
28203 body of @code{C}, so
28204 the call to @code{C.Func} could still cause @code{Program_Error} to
28205 be raised.
28206
28207 The effect of a pragma @code{Elaborate_All} is stronger, it requires
28208 not only that the body of the named unit be elaborated before the
28209 unit doing the @code{with}, but also the bodies of all units that the
28210 named unit uses, following @code{with} links transitively. For example,
28211 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
28212 then it requires
28213 not only that the body of @code{B} be elaborated before @code{A},
28214 but also the
28215 body of @code{C}, because @code{B} @code{with}'s @code{C}.
28216 @end table
28217
28218 @noindent
28219 We are now in a position to give a usage rule in Ada for avoiding
28220 elaboration problems, at least if dynamic dispatching and access to
28221 subprogram values are not used. We will handle these cases separately
28222 later.
28223
28224 The rule is simple. If a unit has elaboration code that can directly or
28225 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
28226 a generic package in a @code{with}'ed unit,
28227 then if the @code{with}'ed unit does not have
28228 pragma @code{Pure} or @code{Preelaborate}, then the client should have
28229 a pragma @code{Elaborate_All}
28230 for the @code{with}'ed unit. By following this rule a client is
28231 assured that calls can be made without risk of an exception.
28232
28233 For generic subprogram instantiations, the rule can be relaxed to
28234 require only a pragma @code{Elaborate} since elaborating the body
28235 of a subprogram cannot cause any transitive elaboration (we are
28236 not calling the subprogram in this case, just elaborating its
28237 declaration).
28238
28239 If this rule is not followed, then a program may be in one of four
28240 states:
28241
28242 @table @asis
28243 @item No order exists
28244 No order of elaboration exists which follows the rules, taking into
28245 account any @code{Elaborate}, @code{Elaborate_All},
28246 or @code{Elaborate_Body} pragmas. In
28247 this case, an Ada compiler must diagnose the situation at bind
28248 time, and refuse to build an executable program.
28249
28250 @item One or more orders exist, all incorrect
28251 One or more acceptable elaboration orders exist, and all of them
28252 generate an elaboration order problem. In this case, the binder
28253 can build an executable program, but @code{Program_Error} will be raised
28254 when the program is run.
28255
28256 @item Several orders exist, some right, some incorrect
28257 One or more acceptable elaboration orders exists, and some of them
28258 work, and some do not. The programmer has not controlled
28259 the order of elaboration, so the binder may or may not pick one of
28260 the correct orders, and the program may or may not raise an
28261 exception when it is run. This is the worst case, because it means
28262 that the program may fail when moved to another compiler, or even
28263 another version of the same compiler.
28264
28265 @item One or more orders exists, all correct
28266 One ore more acceptable elaboration orders exist, and all of them
28267 work. In this case the program runs successfully. This state of
28268 affairs can be guaranteed by following the rule we gave above, but
28269 may be true even if the rule is not followed.
28270 @end table
28271
28272 @noindent
28273 Note that one additional advantage of following our rules on the use
28274 of @code{Elaborate} and @code{Elaborate_All}
28275 is that the program continues to stay in the ideal (all orders OK) state
28276 even if maintenance
28277 changes some bodies of some units. Conversely, if a program that does
28278 not follow this rule happens to be safe at some point, this state of affairs
28279 may deteriorate silently as a result of maintenance changes.
28280
28281 You may have noticed that the above discussion did not mention
28282 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
28283 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
28284 code in the body makes calls to some other unit, so it is still necessary
28285 to use @code{Elaborate_All} on such units.
28286
28287 @node Controlling Elaboration in GNAT - Internal Calls
28288 @section Controlling Elaboration in GNAT - Internal Calls
28289
28290 @noindent
28291 In the case of internal calls, i.e., calls within a single package, the
28292 programmer has full control over the order of elaboration, and it is up
28293 to the programmer to elaborate declarations in an appropriate order. For
28294 example writing:
28295
28296 @smallexample @c ada
28297 @group
28298 @cartouche
28299 function One return Float;
28300
28301 Q : Float := One;
28302
28303 function One return Float is
28304 begin
28305      return 1.0;
28306 end One;
28307 @end cartouche
28308 @end group
28309 @end smallexample
28310
28311 @noindent
28312 will obviously raise @code{Program_Error} at run time, because function
28313 One will be called before its body is elaborated. In this case GNAT will
28314 generate a warning that the call will raise @code{Program_Error}:
28315
28316 @smallexample
28317 @group
28318 @cartouche
28319  1. procedure y is
28320  2.    function One return Float;
28321  3.
28322  4.    Q : Float := One;
28323                     |
28324     >>> warning: cannot call "One" before body is elaborated
28325     >>> warning: Program_Error will be raised at run time
28326
28327  5.
28328  6.    function One return Float is
28329  7.    begin
28330  8.         return 1.0;
28331  9.    end One;
28332 10.
28333 11. begin
28334 12.    null;
28335 13. end;
28336 @end cartouche
28337 @end group
28338 @end smallexample
28339
28340 @noindent
28341 Note that in this particular case, it is likely that the call is safe, because
28342 the function @code{One} does not access any global variables.
28343 Nevertheless in Ada, we do not want the validity of the check to depend on
28344 the contents of the body (think about the separate compilation case), so this
28345 is still wrong, as we discussed in the previous sections.
28346
28347 The error is easily corrected by rearranging the declarations so that the
28348 body of @code{One} appears before the declaration containing the call
28349 (note that in Ada 95 and Ada 2005,
28350 declarations can appear in any order, so there is no restriction that
28351 would prevent this reordering, and if we write:
28352
28353 @smallexample @c ada
28354 @group
28355 @cartouche
28356 function One return Float;
28357
28358 function One return Float is
28359 begin
28360      return 1.0;
28361 end One;
28362
28363 Q : Float := One;
28364 @end cartouche
28365 @end group
28366 @end smallexample
28367
28368 @noindent
28369 then all is well, no warning is generated, and no
28370 @code{Program_Error} exception
28371 will be raised.
28372 Things are more complicated when a chain of subprograms is executed:
28373
28374 @smallexample @c ada
28375 @group
28376 @cartouche
28377 function A return Integer;
28378 function B return Integer;
28379 function C return Integer;
28380
28381 function B return Integer is begin return A; end;
28382 function C return Integer is begin return B; end;
28383
28384 X : Integer := C;
28385
28386 function A return Integer is begin return 1; end;
28387 @end cartouche
28388 @end group
28389 @end smallexample
28390
28391 @noindent
28392 Now the call to @code{C}
28393 at elaboration time in the declaration of @code{X} is correct, because
28394 the body of @code{C} is already elaborated,
28395 and the call to @code{B} within the body of
28396 @code{C} is correct, but the call
28397 to @code{A} within the body of @code{B} is incorrect, because the body
28398 of @code{A} has not been elaborated, so @code{Program_Error}
28399 will be raised on the call to @code{A}.
28400 In this case GNAT will generate a
28401 warning that @code{Program_Error} may be
28402 raised at the point of the call. Let's look at the warning:
28403
28404 @smallexample
28405 @group
28406 @cartouche
28407  1. procedure x is
28408  2.    function A return Integer;
28409  3.    function B return Integer;
28410  4.    function C return Integer;
28411  5.
28412  6.    function B return Integer is begin return A; end;
28413                                                     |
28414     >>> warning: call to "A" before body is elaborated may
28415                  raise Program_Error
28416     >>> warning: "B" called at line 7
28417     >>> warning: "C" called at line 9
28418
28419  7.    function C return Integer is begin return B; end;
28420  8.
28421  9.    X : Integer := C;
28422 10.
28423 11.    function A return Integer is begin return 1; end;
28424 12.
28425 13. begin
28426 14.    null;
28427 15. end;
28428 @end cartouche
28429 @end group
28430 @end smallexample
28431
28432 @noindent
28433 Note that the message here says ``may raise'', instead of the direct case,
28434 where the message says ``will be raised''. That's because whether
28435 @code{A} is
28436 actually called depends in general on run-time flow of control.
28437 For example, if the body of @code{B} said
28438
28439 @smallexample @c ada
28440 @group
28441 @cartouche
28442 function B return Integer is
28443 begin
28444    if some-condition-depending-on-input-data then
28445       return A;
28446    else
28447       return 1;
28448    end if;
28449 end B;
28450 @end cartouche
28451 @end group
28452 @end smallexample
28453
28454 @noindent
28455 then we could not know until run time whether the incorrect call to A would
28456 actually occur, so @code{Program_Error} might
28457 or might not be raised. It is possible for a compiler to
28458 do a better job of analyzing bodies, to
28459 determine whether or not @code{Program_Error}
28460 might be raised, but it certainly
28461 couldn't do a perfect job (that would require solving the halting problem
28462 and is provably impossible), and because this is a warning anyway, it does
28463 not seem worth the effort to do the analysis. Cases in which it
28464 would be relevant are rare.
28465
28466 In practice, warnings of either of the forms given
28467 above will usually correspond to
28468 real errors, and should be examined carefully and eliminated.
28469 In the rare case where a warning is bogus, it can be suppressed by any of
28470 the following methods:
28471
28472 @itemize @bullet
28473 @item
28474 Compile with the @option{-gnatws} switch set
28475
28476 @item
28477 Suppress @code{Elaboration_Check} for the called subprogram
28478
28479 @item
28480 Use pragma @code{Warnings_Off} to turn warnings off for the call
28481 @end itemize
28482
28483 @noindent
28484 For the internal elaboration check case,
28485 GNAT by default generates the
28486 necessary run-time checks to ensure
28487 that @code{Program_Error} is raised if any
28488 call fails an elaboration check. Of course this can only happen if a
28489 warning has been issued as described above. The use of pragma
28490 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
28491 some of these checks, meaning that it may be possible (but is not
28492 guaranteed) for a program to be able to call a subprogram whose body
28493 is not yet elaborated, without raising a @code{Program_Error} exception.
28494
28495 @node Controlling Elaboration in GNAT - External Calls
28496 @section Controlling Elaboration in GNAT - External Calls
28497
28498 @noindent
28499 The previous section discussed the case in which the execution of a
28500 particular thread of elaboration code occurred entirely within a
28501 single unit. This is the easy case to handle, because a programmer
28502 has direct and total control over the order of elaboration, and
28503 furthermore, checks need only be generated in cases which are rare
28504 and which the compiler can easily detect.
28505 The situation is more complex when separate compilation is taken into account.
28506 Consider the following:
28507
28508 @smallexample @c ada
28509 @cartouche
28510 @group
28511 package Math is
28512    function Sqrt (Arg : Float) return Float;
28513 end Math;
28514
28515 package body Math is
28516    function Sqrt (Arg : Float) return Float is
28517    begin
28518          @dots{}
28519    end Sqrt;
28520 end Math;
28521 @end group
28522 @group
28523 with Math;
28524 package Stuff is
28525    X : Float := Math.Sqrt (0.5);
28526 end Stuff;
28527
28528 with Stuff;
28529 procedure Main is
28530 begin
28531    @dots{}
28532 end Main;
28533 @end group
28534 @end cartouche
28535 @end smallexample
28536
28537 @noindent
28538 where @code{Main} is the main program. When this program is executed, the
28539 elaboration code must first be executed, and one of the jobs of the
28540 binder is to determine the order in which the units of a program are
28541 to be elaborated. In this case we have four units: the spec and body
28542 of @code{Math},
28543 the spec of @code{Stuff} and the body of @code{Main}).
28544 In what order should the four separate sections of elaboration code
28545 be executed?
28546
28547 There are some restrictions in the order of elaboration that the binder
28548 can choose. In particular, if unit U has a @code{with}
28549 for a package @code{X}, then you
28550 are assured that the spec of @code{X}
28551 is elaborated before U , but you are
28552 not assured that the body of @code{X}
28553 is elaborated before U.
28554 This means that in the above case, the binder is allowed to choose the
28555 order:
28556
28557 @smallexample
28558 spec of Math
28559 spec of Stuff
28560 body of Math
28561 body of Main
28562 @end smallexample
28563
28564 @noindent
28565 but that's not good, because now the call to @code{Math.Sqrt}
28566 that happens during
28567 the elaboration of the @code{Stuff}
28568 spec happens before the body of @code{Math.Sqrt} is
28569 elaborated, and hence causes @code{Program_Error} exception to be raised.
28570 At first glance, one might say that the binder is misbehaving, because
28571 obviously you want to elaborate the body of something you @code{with}
28572 first, but
28573 that is not a general rule that can be followed in all cases. Consider
28574
28575 @smallexample @c ada
28576 @group
28577 @cartouche
28578 package X is @dots{}
28579
28580 package Y is @dots{}
28581
28582 with X;
28583 package body Y is @dots{}
28584
28585 with Y;
28586 package body X is @dots{}
28587 @end cartouche
28588 @end group
28589 @end smallexample
28590
28591 @noindent
28592 This is a common arrangement, and, apart from the order of elaboration
28593 problems that might arise in connection with elaboration code, this works fine.
28594 A rule that says that you must first elaborate the body of anything you
28595 @code{with} cannot work in this case:
28596 the body of @code{X} @code{with}'s @code{Y},
28597 which means you would have to
28598 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
28599 which means
28600 you have to elaborate the body of @code{X} first, but @dots{} and we have a
28601 loop that cannot be broken.
28602
28603 It is true that the binder can in many cases guess an order of elaboration
28604 that is unlikely to cause a @code{Program_Error}
28605 exception to be raised, and it tries to do so (in the
28606 above example of @code{Math/Stuff/Spec}, the GNAT binder will
28607 by default
28608 elaborate the body of @code{Math} right after its spec, so all will be well).
28609
28610 However, a program that blindly relies on the binder to be helpful can
28611 get into trouble, as we discussed in the previous sections, so
28612 GNAT
28613 provides a number of facilities for assisting the programmer in
28614 developing programs that are robust with respect to elaboration order.
28615
28616 @node Default Behavior in GNAT - Ensuring Safety
28617 @section Default Behavior in GNAT - Ensuring Safety
28618
28619 @noindent
28620 The default behavior in GNAT ensures elaboration safety. In its
28621 default mode GNAT implements the
28622 rule we previously described as the right approach. Let's restate it:
28623
28624 @itemize
28625 @item
28626 @emph{If a unit has elaboration code that can directly or indirectly make a
28627 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
28628 package in a @code{with}'ed unit, then if the @code{with}'ed unit
28629 does not have pragma @code{Pure} or
28630 @code{Preelaborate}, then the client should have an
28631 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
28632
28633 @emph{In the case of instantiating a generic subprogram, it is always
28634 sufficient to have only an @code{Elaborate} pragma for the
28635 @code{with}'ed unit.}
28636 @end itemize
28637
28638 @noindent
28639 By following this rule a client is assured that calls and instantiations
28640 can be made without risk of an exception.
28641
28642 In this mode GNAT traces all calls that are potentially made from
28643 elaboration code, and puts in any missing implicit @code{Elaborate}
28644 and @code{Elaborate_All} pragmas.
28645 The advantage of this approach is that no elaboration problems
28646 are possible if the binder can find an elaboration order that is
28647 consistent with these implicit @code{Elaborate} and
28648 @code{Elaborate_All} pragmas. The
28649 disadvantage of this approach is that no such order may exist.
28650
28651 If the binder does not generate any diagnostics, then it means that it has
28652 found an elaboration order that is guaranteed to be safe. However, the binder
28653 may still be relying on implicitly generated @code{Elaborate} and
28654 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
28655 guaranteed.
28656
28657 If it is important to guarantee portability, then the compilations should
28658 use the
28659 @option{-gnatwl}
28660 (warn on elaboration problems) switch. This will cause warning messages
28661 to be generated indicating the missing @code{Elaborate} and
28662 @code{Elaborate_All} pragmas.
28663 Consider the following source program:
28664
28665 @smallexample @c ada
28666 @group
28667 @cartouche
28668 with k;
28669 package j is
28670   m : integer := k.r;
28671 end;
28672 @end cartouche
28673 @end group
28674 @end smallexample
28675
28676 @noindent
28677 where it is clear that there
28678 should be a pragma @code{Elaborate_All}
28679 for unit @code{k}. An implicit pragma will be generated, and it is
28680 likely that the binder will be able to honor it. However, if you want
28681 to port this program to some other Ada compiler than GNAT.
28682 it is safer to include the pragma explicitly in the source. If this
28683 unit is compiled with the
28684 @option{-gnatwl}
28685 switch, then the compiler outputs a warning:
28686
28687 @smallexample
28688 @group
28689 @cartouche
28690 1. with k;
28691 2. package j is
28692 3.   m : integer := k.r;
28693                      |
28694    >>> warning: call to "r" may raise Program_Error
28695    >>> warning: missing pragma Elaborate_All for "k"
28696
28697 4. end;
28698 @end cartouche
28699 @end group
28700 @end smallexample
28701
28702 @noindent
28703 and these warnings can be used as a guide for supplying manually
28704 the missing pragmas. It is usually a bad idea to use this warning
28705 option during development. That's because it will warn you when
28706 you need to put in a pragma, but cannot warn you when it is time
28707 to take it out. So the use of pragma @code{Elaborate_All} may lead to
28708 unnecessary dependencies and even false circularities.
28709
28710 This default mode is more restrictive than the Ada Reference
28711 Manual, and it is possible to construct programs which will compile
28712 using the dynamic model described there, but will run into a
28713 circularity using the safer static model we have described.
28714
28715 Of course any Ada compiler must be able to operate in a mode
28716 consistent with the requirements of the Ada Reference Manual,
28717 and in particular must have the capability of implementing the
28718 standard dynamic model of elaboration with run-time checks.
28719
28720 In GNAT, this standard mode can be achieved either by the use of
28721 the @option{-gnatE} switch on the compiler (@command{gcc} or
28722 @command{gnatmake}) command, or by the use of the configuration pragma:
28723
28724 @smallexample @c ada
28725 pragma Elaboration_Checks (DYNAMIC);
28726 @end smallexample
28727
28728 @noindent
28729 Either approach will cause the unit affected to be compiled using the
28730 standard dynamic run-time elaboration checks described in the Ada
28731 Reference Manual. The static model is generally preferable, since it
28732 is clearly safer to rely on compile and link time checks rather than
28733 run-time checks. However, in the case of legacy code, it may be
28734 difficult to meet the requirements of the static model. This
28735 issue is further discussed in
28736 @ref{What to Do If the Default Elaboration Behavior Fails}.
28737
28738 Note that the static model provides a strict subset of the allowed
28739 behavior and programs of the Ada Reference Manual, so if you do
28740 adhere to the static model and no circularities exist,
28741 then you are assured that your program will
28742 work using the dynamic model, providing that you remove any
28743 pragma Elaborate statements from the source.
28744
28745 @node Treatment of Pragma Elaborate
28746 @section Treatment of Pragma Elaborate
28747 @cindex Pragma Elaborate
28748
28749 @noindent
28750 The use of @code{pragma Elaborate}
28751 should generally be avoided in Ada 95 and Ada 2005 programs,
28752 since there is no guarantee that transitive calls
28753 will be properly handled. Indeed at one point, this pragma was placed
28754 in Annex J (Obsolescent Features), on the grounds that it is never useful.
28755
28756 Now that's a bit restrictive. In practice, the case in which
28757 @code{pragma Elaborate} is useful is when the caller knows that there
28758 are no transitive calls, or that the called unit contains all necessary
28759 transitive @code{pragma Elaborate} statements, and legacy code often
28760 contains such uses.
28761
28762 Strictly speaking the static mode in GNAT should ignore such pragmas,
28763 since there is no assurance at compile time that the necessary safety
28764 conditions are met. In practice, this would cause GNAT to be incompatible
28765 with correctly written Ada 83 code that had all necessary
28766 @code{pragma Elaborate} statements in place. Consequently, we made the
28767 decision that GNAT in its default mode will believe that if it encounters
28768 a @code{pragma Elaborate} then the programmer knows what they are doing,
28769 and it will trust that no elaboration errors can occur.
28770
28771 The result of this decision is two-fold. First to be safe using the
28772 static mode, you should remove all @code{pragma Elaborate} statements.
28773 Second, when fixing circularities in existing code, you can selectively
28774 use @code{pragma Elaborate} statements to convince the static mode of
28775 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
28776 statement.
28777
28778 When using the static mode with @option{-gnatwl}, any use of
28779 @code{pragma Elaborate} will generate a warning about possible
28780 problems.
28781
28782 @node Elaboration Issues for Library Tasks
28783 @section Elaboration Issues for Library Tasks
28784 @cindex Library tasks, elaboration issues
28785 @cindex Elaboration of library tasks
28786
28787 @noindent
28788 In this section we examine special elaboration issues that arise for
28789 programs that declare library level tasks.
28790
28791 Generally the model of execution of an Ada program is that all units are
28792 elaborated, and then execution of the program starts. However, the
28793 declaration of library tasks definitely does not fit this model. The
28794 reason for this is that library tasks start as soon as they are declared
28795 (more precisely, as soon as the statement part of the enclosing package
28796 body is reached), that is to say before elaboration
28797 of the program is complete. This means that if such a task calls a
28798 subprogram, or an entry in another task, the callee may or may not be
28799 elaborated yet, and in the standard
28800 Reference Manual model of dynamic elaboration checks, you can even
28801 get timing dependent Program_Error exceptions, since there can be
28802 a race between the elaboration code and the task code.
28803
28804 The static model of elaboration in GNAT seeks to avoid all such
28805 dynamic behavior, by being conservative, and the conservative
28806 approach in this particular case is to assume that all the code
28807 in a task body is potentially executed at elaboration time if
28808 a task is declared at the library level.
28809
28810 This can definitely result in unexpected circularities. Consider
28811 the following example
28812
28813 @smallexample @c ada
28814 package Decls is
28815   task Lib_Task is
28816      entry Start;
28817   end Lib_Task;
28818
28819   type My_Int is new Integer;
28820
28821   function Ident (M : My_Int) return My_Int;
28822 end Decls;
28823
28824 with Utils;
28825 package body Decls is
28826   task body Lib_Task is
28827   begin
28828      accept Start;
28829      Utils.Put_Val (2);
28830   end Lib_Task;
28831
28832   function Ident (M : My_Int) return My_Int is
28833   begin
28834      return M;
28835   end Ident;
28836 end Decls;
28837
28838 with Decls;
28839 package Utils is
28840   procedure Put_Val (Arg : Decls.My_Int);
28841 end Utils;
28842
28843 with Text_IO;
28844 package body Utils is
28845   procedure Put_Val (Arg : Decls.My_Int) is
28846   begin
28847      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28848   end Put_Val;
28849 end Utils;
28850
28851 with Decls;
28852 procedure Main is
28853 begin
28854    Decls.Lib_Task.Start;
28855 end;
28856 @end smallexample
28857
28858 @noindent
28859 If the above example is compiled in the default static elaboration
28860 mode, then a circularity occurs. The circularity comes from the call
28861 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
28862 this call occurs in elaboration code, we need an implicit pragma
28863 @code{Elaborate_All} for @code{Utils}. This means that not only must
28864 the spec and body of @code{Utils} be elaborated before the body
28865 of @code{Decls}, but also the spec and body of any unit that is
28866 @code{with'ed} by the body of @code{Utils} must also be elaborated before
28867 the body of @code{Decls}. This is the transitive implication of
28868 pragma @code{Elaborate_All} and it makes sense, because in general
28869 the body of @code{Put_Val} might have a call to something in a
28870 @code{with'ed} unit.
28871
28872 In this case, the body of Utils (actually its spec) @code{with's}
28873 @code{Decls}. Unfortunately this means that the body of @code{Decls}
28874 must be elaborated before itself, in case there is a call from the
28875 body of @code{Utils}.
28876
28877 Here is the exact chain of events we are worrying about:
28878
28879 @enumerate
28880 @item
28881 In the body of @code{Decls} a call is made from within the body of a library
28882 task to a subprogram in the package @code{Utils}. Since this call may
28883 occur at elaboration time (given that the task is activated at elaboration
28884 time), we have to assume the worst, i.e., that the
28885 call does happen at elaboration time.
28886
28887 @item
28888 This means that the body and spec of @code{Util} must be elaborated before
28889 the body of @code{Decls} so that this call does not cause an access before
28890 elaboration.
28891
28892 @item
28893 Within the body of @code{Util}, specifically within the body of
28894 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
28895 by this package.
28896
28897 @item
28898 One such @code{with}'ed package is package @code{Decls}, so there
28899 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
28900 In fact there is such a call in this example, but we would have to
28901 assume that there was such a call even if it were not there, since
28902 we are not supposed to write the body of @code{Decls} knowing what
28903 is in the body of @code{Utils}; certainly in the case of the
28904 static elaboration model, the compiler does not know what is in
28905 other bodies and must assume the worst.
28906
28907 @item
28908 This means that the spec and body of @code{Decls} must also be
28909 elaborated before we elaborate the unit containing the call, but
28910 that unit is @code{Decls}! This means that the body of @code{Decls}
28911 must be elaborated before itself, and that's a circularity.
28912 @end enumerate
28913
28914 @noindent
28915 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
28916 the body of @code{Decls} you will get a true Ada Reference Manual
28917 circularity that makes the program illegal.
28918
28919 In practice, we have found that problems with the static model of
28920 elaboration in existing code often arise from library tasks, so
28921 we must address this particular situation.
28922
28923 Note that if we compile and run the program above, using the dynamic model of
28924 elaboration (that is to say use the @option{-gnatE} switch),
28925 then it compiles, binds,
28926 links, and runs, printing the expected result of 2. Therefore in some sense
28927 the circularity here is only apparent, and we need to capture
28928 the properties of this program that  distinguish it from other library-level
28929 tasks that have real elaboration problems.
28930
28931 We have four possible answers to this question:
28932
28933 @itemize @bullet
28934
28935 @item
28936 Use the dynamic model of elaboration.
28937
28938 If we use the @option{-gnatE} switch, then as noted above, the program works.
28939 Why is this? If we examine the task body, it is apparent that the task cannot
28940 proceed past the
28941 @code{accept} statement until after elaboration has been completed, because
28942 the corresponding entry call comes from the main program, not earlier.
28943 This is why the dynamic model works here. But that's really giving
28944 up on a precise analysis, and we prefer to take this approach only if we cannot
28945 solve the
28946 problem in any other manner. So let us examine two ways to reorganize
28947 the program to avoid the potential elaboration problem.
28948
28949 @item
28950 Split library tasks into separate packages.
28951
28952 Write separate packages, so that library tasks are isolated from
28953 other declarations as much as possible. Let us look at a variation on
28954 the above program.
28955
28956 @smallexample @c ada
28957 package Decls1 is
28958   task Lib_Task is
28959      entry Start;
28960   end Lib_Task;
28961 end Decls1;
28962
28963 with Utils;
28964 package body Decls1 is
28965   task body Lib_Task is
28966   begin
28967      accept Start;
28968      Utils.Put_Val (2);
28969   end Lib_Task;
28970 end Decls1;
28971
28972 package Decls2 is
28973   type My_Int is new Integer;
28974   function Ident (M : My_Int) return My_Int;
28975 end Decls2;
28976
28977 with Utils;
28978 package body Decls2 is
28979   function Ident (M : My_Int) return My_Int is
28980   begin
28981      return M;
28982   end Ident;
28983 end Decls2;
28984
28985 with Decls2;
28986 package Utils is
28987   procedure Put_Val (Arg : Decls2.My_Int);
28988 end Utils;
28989
28990 with Text_IO;
28991 package body Utils is
28992   procedure Put_Val (Arg : Decls2.My_Int) is
28993   begin
28994      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
28995   end Put_Val;
28996 end Utils;
28997
28998 with Decls1;
28999 procedure Main is
29000 begin
29001    Decls1.Lib_Task.Start;
29002 end;
29003 @end smallexample
29004
29005 @noindent
29006 All we have done is to split @code{Decls} into two packages, one
29007 containing the library task, and one containing everything else. Now
29008 there is no cycle, and the program compiles, binds, links and executes
29009 using the default static model of elaboration.
29010
29011 @item
29012 Declare separate task types.
29013
29014 A significant part of the problem arises because of the use of the
29015 single task declaration form. This means that the elaboration of
29016 the task type, and the elaboration of the task itself (i.e.@: the
29017 creation of the task) happen at the same time. A good rule
29018 of style in Ada is to always create explicit task types. By
29019 following the additional step of placing task objects in separate
29020 packages from the task type declaration, many elaboration problems
29021 are avoided. Here is another modified example of the example program:
29022
29023 @smallexample @c ada
29024 package Decls is
29025   task type Lib_Task_Type is
29026      entry Start;
29027   end Lib_Task_Type;
29028
29029   type My_Int is new Integer;
29030
29031   function Ident (M : My_Int) return My_Int;
29032 end Decls;
29033
29034 with Utils;
29035 package body Decls is
29036   task body Lib_Task_Type is
29037   begin
29038      accept Start;
29039      Utils.Put_Val (2);
29040   end Lib_Task_Type;
29041
29042   function Ident (M : My_Int) return My_Int is
29043   begin
29044      return M;
29045   end Ident;
29046 end Decls;
29047
29048 with Decls;
29049 package Utils is
29050   procedure Put_Val (Arg : Decls.My_Int);
29051 end Utils;
29052
29053 with Text_IO;
29054 package body Utils is
29055   procedure Put_Val (Arg : Decls.My_Int) is
29056   begin
29057      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
29058   end Put_Val;
29059 end Utils;
29060
29061 with Decls;
29062 package Declst is
29063    Lib_Task : Decls.Lib_Task_Type;
29064 end Declst;
29065
29066 with Declst;
29067 procedure Main is
29068 begin
29069    Declst.Lib_Task.Start;
29070 end;
29071 @end smallexample
29072
29073 @noindent
29074 What we have done here is to replace the @code{task} declaration in
29075 package @code{Decls} with a @code{task type} declaration. Then we
29076 introduce a separate package @code{Declst} to contain the actual
29077 task object. This separates the elaboration issues for
29078 the @code{task type}
29079 declaration, which causes no trouble, from the elaboration issues
29080 of the task object, which is also unproblematic, since it is now independent
29081 of the elaboration of  @code{Utils}.
29082 This separation of concerns also corresponds to
29083 a generally sound engineering principle of separating declarations
29084 from instances. This version of the program also compiles, binds, links,
29085 and executes, generating the expected output.
29086
29087 @item
29088 Use No_Entry_Calls_In_Elaboration_Code restriction.
29089 @cindex No_Entry_Calls_In_Elaboration_Code
29090
29091 The previous two approaches described how a program can be restructured
29092 to avoid the special problems caused by library task bodies. in practice,
29093 however, such restructuring may be difficult to apply to existing legacy code,
29094 so we must consider solutions that do not require massive rewriting.
29095
29096 Let us consider more carefully why our original sample program works
29097 under the dynamic model of elaboration. The reason is that the code
29098 in the task body blocks immediately on the @code{accept}
29099 statement. Now of course there is nothing to prohibit elaboration
29100 code from making entry calls (for example from another library level task),
29101 so we cannot tell in isolation that
29102 the task will not execute the accept statement  during elaboration.
29103
29104 However, in practice it is very unusual to see elaboration code
29105 make any entry calls, and the pattern of tasks starting
29106 at elaboration time and then immediately blocking on @code{accept} or
29107 @code{select} statements is very common. What this means is that
29108 the compiler is being too pessimistic when it analyzes the
29109 whole package body as though it might be executed at elaboration
29110 time.
29111
29112 If we know that the elaboration code contains no entry calls, (a very safe
29113 assumption most of the time, that could almost be made the default
29114 behavior), then we can compile all units of the program under control
29115 of the following configuration pragma:
29116
29117 @smallexample
29118 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
29119 @end smallexample
29120
29121 @noindent
29122 This pragma can be placed in the @file{gnat.adc} file in the usual
29123 manner. If we take our original unmodified program and compile it
29124 in the presence of a @file{gnat.adc} containing the above pragma,
29125 then once again, we can compile, bind, link, and execute, obtaining
29126 the expected result. In the presence of this pragma, the compiler does
29127 not trace calls in a task body, that appear after the first @code{accept}
29128 or @code{select} statement, and therefore does not report a potential
29129 circularity in the original program.
29130
29131 The compiler will check to the extent it can that the above
29132 restriction is not violated, but it is not always possible to do a
29133 complete check at compile time, so it is important to use this
29134 pragma only if the stated restriction is in fact met, that is to say
29135 no task receives an entry call before elaboration of all units is completed.
29136
29137 @end itemize
29138
29139 @node Mixing Elaboration Models
29140 @section Mixing Elaboration Models
29141 @noindent
29142 So far, we have assumed that the entire program is either compiled
29143 using the dynamic model or static model, ensuring consistency. It
29144 is possible to mix the two models, but rules have to be followed
29145 if this mixing is done to ensure that elaboration checks are not
29146 omitted.
29147
29148 The basic rule is that @emph{a unit compiled with the static model cannot
29149 be @code{with'ed} by a unit compiled with the dynamic model}. The
29150 reason for this is that in the static model, a unit assumes that
29151 its clients guarantee to use (the equivalent of) pragma
29152 @code{Elaborate_All} so that no elaboration checks are required
29153 in inner subprograms, and this assumption is violated if the
29154 client is compiled with dynamic checks.
29155
29156 The precise rule is as follows. A unit that is compiled with dynamic
29157 checks can only @code{with} a unit that meets at least one of the
29158 following criteria:
29159
29160 @itemize @bullet
29161
29162 @item
29163 The @code{with'ed} unit is itself compiled with dynamic elaboration
29164 checks (that is with the @option{-gnatE} switch.
29165
29166 @item
29167 The @code{with'ed} unit is an internal GNAT implementation unit from
29168 the System, Interfaces, Ada, or GNAT hierarchies.
29169
29170 @item
29171 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
29172
29173 @item
29174 The @code{with'ing} unit (that is the client) has an explicit pragma
29175 @code{Elaborate_All} for the @code{with'ed} unit.
29176
29177 @end itemize
29178
29179 @noindent
29180 If this rule is violated, that is if a unit with dynamic elaboration
29181 checks @code{with's} a unit that does not meet one of the above four
29182 criteria, then the binder (@code{gnatbind}) will issue a warning
29183 similar to that in the following example:
29184
29185 @smallexample
29186 warning: "x.ads" has dynamic elaboration checks and with's
29187 warning:   "y.ads" which has static elaboration checks
29188 @end smallexample
29189
29190 @noindent
29191 These warnings indicate that the rule has been violated, and that as a result
29192 elaboration checks may be missed in the resulting executable file.
29193 This warning may be suppressed using the @option{-ws} binder switch
29194 in the usual manner.
29195
29196 One useful application of this mixing rule is in the case of a subsystem
29197 which does not itself @code{with} units from the remainder of the
29198 application. In this case, the entire subsystem can be compiled with
29199 dynamic checks to resolve a circularity in the subsystem, while
29200 allowing the main application that uses this subsystem to be compiled
29201 using the more reliable default static model.
29202
29203 @node What to Do If the Default Elaboration Behavior Fails
29204 @section What to Do If the Default Elaboration Behavior Fails
29205
29206 @noindent
29207 If the binder cannot find an acceptable order, it outputs detailed
29208 diagnostics. For example:
29209 @smallexample
29210 @group
29211 @iftex
29212 @leftskip=0cm
29213 @end iftex
29214 error: elaboration circularity detected
29215 info:   "proc (body)" must be elaborated before "pack (body)"
29216 info:     reason: Elaborate_All probably needed in unit "pack (body)"
29217 info:     recompile "pack (body)" with -gnatwl
29218 info:                             for full details
29219 info:       "proc (body)"
29220 info:         is needed by its spec:
29221 info:       "proc (spec)"
29222 info:         which is withed by:
29223 info:       "pack (body)"
29224 info:  "pack (body)" must be elaborated before "proc (body)"
29225 info:     reason: pragma Elaborate in unit "proc (body)"
29226 @end group
29227
29228 @end smallexample
29229
29230 @noindent
29231 In this case we have a cycle that the binder cannot break. On the one
29232 hand, there is an explicit pragma Elaborate in @code{proc} for
29233 @code{pack}. This means that the body of @code{pack} must be elaborated
29234 before the body of @code{proc}. On the other hand, there is elaboration
29235 code in @code{pack} that calls a subprogram in @code{proc}. This means
29236 that for maximum safety, there should really be a pragma
29237 Elaborate_All in @code{pack} for @code{proc} which would require that
29238 the body of @code{proc} be elaborated before the body of
29239 @code{pack}. Clearly both requirements cannot be satisfied.
29240 Faced with a circularity of this kind, you have three different options.
29241
29242 @table @asis
29243 @item Fix the program
29244 The most desirable option from the point of view of long-term maintenance
29245 is to rearrange the program so that the elaboration problems are avoided.
29246 One useful technique is to place the elaboration code into separate
29247 child packages. Another is to move some of the initialization code to
29248 explicitly called subprograms, where the program controls the order
29249 of initialization explicitly. Although this is the most desirable option,
29250 it may be impractical and involve too much modification, especially in
29251 the case of complex legacy code.
29252
29253 @item Perform dynamic checks
29254 If the compilations are done using the
29255 @option{-gnatE}
29256 (dynamic elaboration check) switch, then GNAT behaves in a quite different
29257 manner. Dynamic checks are generated for all calls that could possibly result
29258 in raising an exception. With this switch, the compiler does not generate
29259 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
29260 exactly as specified in the @cite{Ada Reference Manual}.
29261 The binder will generate
29262 an executable program that may or may not raise @code{Program_Error}, and then
29263 it is the programmer's job to ensure that it does not raise an exception. Note
29264 that it is important to compile all units with the switch, it cannot be used
29265 selectively.
29266
29267 @item Suppress checks
29268 The drawback of dynamic checks is that they generate a
29269 significant overhead at run time, both in space and time. If you
29270 are absolutely sure that your program cannot raise any elaboration
29271 exceptions, and you still want to use the dynamic elaboration model,
29272 then you can use the configuration pragma
29273 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
29274 example this pragma could be placed in the @file{gnat.adc} file.
29275
29276 @item Suppress checks selectively
29277 When you know that certain calls or instantiations in elaboration code cannot
29278 possibly lead to an elaboration error, and the binder nevertheless complains
29279 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
29280 elaboration circularities, it is possible to remove those warnings locally and
29281 obtain a program that will bind. Clearly this can be unsafe, and it is the
29282 responsibility of the programmer to make sure that the resulting program has no
29283 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
29284 used with different granularity to suppress warnings and break elaboration
29285 circularities:
29286
29287 @itemize @bullet
29288 @item
29289 Place the pragma that names the called subprogram in the declarative part
29290 that contains the call.
29291
29292 @item
29293 Place the pragma in the declarative part, without naming an entity. This
29294 disables warnings on all calls in the corresponding  declarative region.
29295
29296 @item
29297 Place the pragma in the package spec that declares the called subprogram,
29298 and name the subprogram. This disables warnings on all elaboration calls to
29299 that subprogram.
29300
29301 @item
29302 Place the pragma in the package spec that declares the called subprogram,
29303 without naming any entity. This disables warnings on all elaboration calls to
29304 all subprograms declared in this spec.
29305
29306 @item Use Pragma Elaborate
29307 As previously described in section @xref{Treatment of Pragma Elaborate},
29308 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
29309 that no elaboration checks are required on calls to the designated unit.
29310 There may be cases in which the caller knows that no transitive calls
29311 can occur, so that a @code{pragma Elaborate} will be sufficient in a
29312 case where @code{pragma Elaborate_All} would cause a circularity.
29313 @end itemize
29314
29315 @noindent
29316 These five cases are listed in order of decreasing safety, and therefore
29317 require increasing programmer care in their application. Consider the
29318 following program:
29319
29320 @smallexample @c adanocomment
29321 package Pack1 is
29322   function F1 return Integer;
29323   X1 : Integer;
29324 end Pack1;
29325
29326 package Pack2 is
29327   function F2 return Integer;
29328   function Pure (x : integer) return integer;
29329   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
29330   --  pragma Suppress (Elaboration_Check);              -- (4)
29331 end Pack2;
29332
29333 with Pack2;
29334 package body Pack1 is
29335   function F1 return Integer is
29336   begin
29337     return 100;
29338   end F1;
29339   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
29340 begin
29341   declare
29342     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
29343     --  pragma Suppress(Elaboration_Check);             -- (2)
29344   begin
29345     X1 := Pack2.F2 + 1;                --  Elab. call (2)
29346   end;
29347 end Pack1;
29348
29349 with Pack1;
29350 package body Pack2 is
29351   function F2 return Integer is
29352   begin
29353      return Pack1.F1;
29354   end F2;
29355   function Pure (x : integer) return integer is
29356   begin
29357      return x ** 3 - 3 * x;
29358   end;
29359 end Pack2;
29360
29361 with Pack1, Ada.Text_IO;
29362 procedure Proc3 is
29363 begin
29364   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
29365 end Proc3;
29366 @end smallexample
29367 In the absence of any pragmas, an attempt to bind this program produces
29368 the following diagnostics:
29369 @smallexample
29370 @group
29371 @iftex
29372 @leftskip=.5cm
29373 @end iftex
29374 error: elaboration circularity detected
29375 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
29376 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
29377 info:       recompile "pack1 (body)" with -gnatwl for full details
29378 info:          "pack1 (body)"
29379 info:             must be elaborated along with its spec:
29380 info:          "pack1 (spec)"
29381 info:             which is withed by:
29382 info:          "pack2 (body)"
29383 info:             which must be elaborated along with its spec:
29384 info:          "pack2 (spec)"
29385 info:             which is withed by:
29386 info:          "pack1 (body)"
29387 @end group
29388 @end smallexample
29389 The sources of the circularity are the two calls to @code{Pack2.Pure} and
29390 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
29391 F2 is safe, even though F2 calls F1, because the call appears after the
29392 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
29393 remove the warning on the call. It is also possible to use pragma (2)
29394 because there are no other potentially unsafe calls in the block.
29395
29396 @noindent
29397 The call to @code{Pure} is safe because this function does not depend on the
29398 state of @code{Pack2}. Therefore any call to this function is safe, and it
29399 is correct to place pragma (3) in the corresponding package spec.
29400
29401 @noindent
29402 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
29403 warnings on all calls to functions declared therein. Note that this is not
29404 necessarily safe, and requires more detailed examination of the subprogram
29405 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
29406 be already elaborated.
29407 @end table
29408
29409 @noindent
29410 It is hard to generalize on which of these four approaches should be
29411 taken. Obviously if it is possible to fix the program so that the default
29412 treatment works, this is preferable, but this may not always be practical.
29413 It is certainly simple enough to use
29414 @option{-gnatE}
29415 but the danger in this case is that, even if the GNAT binder
29416 finds a correct elaboration order, it may not always do so,
29417 and certainly a binder from another Ada compiler might not. A
29418 combination of testing and analysis (for which the warnings generated
29419 with the
29420 @option{-gnatwl}
29421 switch can be useful) must be used to ensure that the program is free
29422 of errors. One switch that is useful in this testing is the
29423 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
29424 switch for
29425 @code{gnatbind}.
29426 Normally the binder tries to find an order that has the best chance
29427 of avoiding elaboration problems. However, if this switch is used, the binder
29428 plays a devil's advocate role, and tries to choose the order that
29429 has the best chance of failing. If your program works even with this
29430 switch, then it has a better chance of being error free, but this is still
29431 not a guarantee.
29432
29433 For an example of this approach in action, consider the C-tests (executable
29434 tests) from the ACVC suite. If these are compiled and run with the default
29435 treatment, then all but one of them succeed without generating any error
29436 diagnostics from the binder. However, there is one test that fails, and
29437 this is not surprising, because the whole point of this test is to ensure
29438 that the compiler can handle cases where it is impossible to determine
29439 a correct order statically, and it checks that an exception is indeed
29440 raised at run time.
29441
29442 This one test must be compiled and run using the
29443 @option{-gnatE}
29444 switch, and then it passes. Alternatively, the entire suite can
29445 be run using this switch. It is never wrong to run with the dynamic
29446 elaboration switch if your code is correct, and we assume that the
29447 C-tests are indeed correct (it is less efficient, but efficiency is
29448 not a factor in running the ACVC tests.)
29449
29450 @node Elaboration for Access-to-Subprogram Values
29451 @section Elaboration for Access-to-Subprogram Values
29452 @cindex Access-to-subprogram
29453
29454 @noindent
29455 Access-to-subprogram types (introduced in Ada 95) complicate
29456 the handling of elaboration. The trouble is that it becomes
29457 impossible to tell at compile time which procedure
29458 is being called. This means that it is not possible for the binder
29459 to analyze the elaboration requirements in this case.
29460
29461 If at the point at which the access value is created
29462 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
29463 the body of the subprogram is
29464 known to have been elaborated, then the access value is safe, and its use
29465 does not require a check. This may be achieved by appropriate arrangement
29466 of the order of declarations if the subprogram is in the current unit,
29467 or, if the subprogram is in another unit, by using pragma
29468 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
29469 on the referenced unit.
29470
29471 If the referenced body is not known to have been elaborated at the point
29472 the access value is created, then any use of the access value must do a
29473 dynamic check, and this dynamic check will fail and raise a
29474 @code{Program_Error} exception if the body has not been elaborated yet.
29475 GNAT will generate the necessary checks, and in addition, if the
29476 @option{-gnatwl}
29477 switch is set, will generate warnings that such checks are required.
29478
29479 The use of dynamic dispatching for tagged types similarly generates
29480 a requirement for dynamic checks, and premature calls to any primitive
29481 operation of a tagged type before the body of the operation has been
29482 elaborated, will result in the raising of @code{Program_Error}.
29483
29484 @node Summary of Procedures for Elaboration Control
29485 @section Summary of Procedures for Elaboration Control
29486 @cindex Elaboration control
29487
29488 @noindent
29489 First, compile your program with the default options, using none of
29490 the special elaboration control switches. If the binder successfully
29491 binds your program, then you can be confident that, apart from issues
29492 raised by the use of access-to-subprogram types and dynamic dispatching,
29493 the program is free of elaboration errors. If it is important that the
29494 program be portable, then use the
29495 @option{-gnatwl}
29496 switch to generate warnings about missing @code{Elaborate} or
29497 @code{Elaborate_All} pragmas, and supply the missing pragmas.
29498
29499 If the program fails to bind using the default static elaboration
29500 handling, then you can fix the program to eliminate the binder
29501 message, or recompile the entire program with the
29502 @option{-gnatE} switch to generate dynamic elaboration checks,
29503 and, if you are sure there really are no elaboration problems,
29504 use a global pragma @code{Suppress (Elaboration_Check)}.
29505
29506 @node Other Elaboration Order Considerations
29507 @section Other Elaboration Order Considerations
29508 @noindent
29509 This section has been entirely concerned with the issue of finding a valid
29510 elaboration order, as defined by the Ada Reference Manual. In a case
29511 where several elaboration orders are valid, the task is to find one
29512 of the possible valid elaboration orders (and the static model in GNAT
29513 will ensure that this is achieved).
29514
29515 The purpose of the elaboration rules in the Ada Reference Manual is to
29516 make sure that no entity is accessed before it has been elaborated. For
29517 a subprogram, this means that the spec and body must have been elaborated
29518 before the subprogram is called. For an object, this means that the object
29519 must have been elaborated before its value is read or written. A violation
29520 of either of these two requirements is an access before elaboration order,
29521 and this section has been all about avoiding such errors.
29522
29523 In the case where more than one order of elaboration is possible, in the
29524 sense that access before elaboration errors are avoided, then any one of
29525 the orders is ``correct'' in the sense that it meets the requirements of
29526 the Ada Reference Manual, and no such error occurs.
29527
29528 However, it may be the case for a given program, that there are
29529 constraints on the order of elaboration that come not from consideration
29530 of avoiding elaboration errors, but rather from extra-lingual logic
29531 requirements. Consider this example:
29532
29533 @smallexample @c ada
29534 with Init_Constants;
29535 package Constants is
29536    X : Integer := 0;
29537    Y : Integer := 0;
29538 end Constants;
29539
29540 package Init_Constants is
29541    procedure P; -- require a body
29542 end Init_Constants;
29543
29544 with Constants;
29545 package body Init_Constants is
29546    procedure P is begin null; end;
29547 begin
29548    Constants.X := 3;
29549    Constants.Y := 4;
29550 end Init_Constants;
29551
29552 with Constants;
29553 package Calc is
29554    Z : Integer := Constants.X + Constants.Y;
29555 end Calc;
29556
29557 with Calc;
29558 with Text_IO; use Text_IO;
29559 procedure Main is
29560 begin
29561    Put_Line (Calc.Z'Img);
29562 end Main;
29563 @end smallexample
29564
29565 @noindent
29566 In this example, there is more than one valid order of elaboration. For
29567 example both the following are correct orders:
29568
29569 @smallexample
29570 Init_Constants spec
29571 Constants spec
29572 Calc spec
29573 Init_Constants body
29574 Main body
29575
29576   and
29577
29578 Init_Constants spec
29579 Init_Constants body
29580 Constants spec
29581 Calc spec
29582 Main body
29583 @end smallexample
29584
29585 @noindent
29586 There is no language rule to prefer one or the other, both are correct
29587 from an order of elaboration point of view. But the programmatic effects
29588 of the two orders are very different. In the first, the elaboration routine
29589 of @code{Calc} initializes @code{Z} to zero, and then the main program
29590 runs with this value of zero. But in the second order, the elaboration
29591 routine of @code{Calc} runs after the body of Init_Constants has set
29592 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
29593 runs.
29594
29595 One could perhaps by applying pretty clever non-artificial intelligence
29596 to the situation guess that it is more likely that the second order of
29597 elaboration is the one desired, but there is no formal linguistic reason
29598 to prefer one over the other. In fact in this particular case, GNAT will
29599 prefer the second order, because of the rule that bodies are elaborated
29600 as soon as possible, but it's just luck that this is what was wanted
29601 (if indeed the second order was preferred).
29602
29603 If the program cares about the order of elaboration routines in a case like
29604 this, it is important to specify the order required. In this particular
29605 case, that could have been achieved by adding to the spec of Calc:
29606
29607 @smallexample @c ada
29608 pragma Elaborate_All (Constants);
29609 @end smallexample
29610
29611 @noindent
29612 which requires that the body (if any) and spec of @code{Constants},
29613 as well as the body and spec of any unit @code{with}'ed by
29614 @code{Constants} be elaborated before @code{Calc} is elaborated.
29615
29616 Clearly no automatic method can always guess which alternative you require,
29617 and if you are working with legacy code that had constraints of this kind
29618 which were not properly specified by adding @code{Elaborate} or
29619 @code{Elaborate_All} pragmas, then indeed it is possible that two different
29620 compilers can choose different orders.
29621
29622 However, GNAT does attempt to diagnose the common situation where there
29623 are uninitialized variables in the visible part of a package spec, and the
29624 corresponding package body has an elaboration block that directly or
29625 indirectly initialized one or more of these variables. This is the situation
29626 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
29627 a warning that suggests this addition if it detects this situation.
29628
29629 The @code{gnatbind}
29630 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
29631 out problems. This switch causes bodies to be elaborated as late as possible
29632 instead of as early as possible. In the example above, it would have forced
29633 the choice of the first elaboration order. If you get different results
29634 when using this switch, and particularly if one set of results is right,
29635 and one is wrong as far as you are concerned, it shows that you have some
29636 missing @code{Elaborate} pragmas. For the example above, we have the
29637 following output:
29638
29639 @smallexample
29640 gnatmake -f -q main
29641 main
29642  7
29643 gnatmake -f -q main -bargs -p
29644 main
29645  0
29646 @end smallexample
29647
29648 @noindent
29649 It is of course quite unlikely that both these results are correct, so
29650 it is up to you in a case like this to investigate the source of the
29651 difference, by looking at the two elaboration orders that are chosen,
29652 and figuring out which is correct, and then adding the necessary
29653 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
29654
29655
29656
29657 @c *******************************
29658 @node Conditional Compilation
29659 @appendix Conditional Compilation
29660 @c *******************************
29661 @cindex Conditional compilation
29662
29663 @noindent
29664 It is often necessary to arrange for a single source program
29665 to serve multiple purposes, where it is compiled in different
29666 ways to achieve these different goals. Some examples of the
29667 need for this feature are
29668
29669 @itemize @bullet
29670 @item  Adapting a program to a different hardware environment
29671 @item  Adapting a program to a different target architecture
29672 @item  Turning debugging features on and off
29673 @item  Arranging for a program to compile with different compilers
29674 @end itemize
29675
29676 @noindent
29677 In C, or C++, the typical approach would be to use the preprocessor
29678 that is defined as part of the language. The Ada language does not
29679 contain such a feature. This is not an oversight, but rather a very
29680 deliberate design decision, based on the experience that overuse of
29681 the preprocessing features in C and C++ can result in programs that
29682 are extremely difficult to maintain. For example, if we have ten
29683 switches that can be on or off, this means that there are a thousand
29684 separate programs, any one of which might not even be syntactically
29685 correct, and even if syntactically correct, the resulting program
29686 might not work correctly. Testing all combinations can quickly become
29687 impossible.
29688
29689 Nevertheless, the need to tailor programs certainly exists, and in
29690 this Appendix we will discuss how this can
29691 be achieved using Ada in general, and GNAT in particular.
29692
29693 @menu
29694 * Use of Boolean Constants::
29695 * Debugging - A Special Case::
29696 * Conditionalizing Declarations::
29697 * Use of Alternative Implementations::
29698 * Preprocessing::
29699 @end menu
29700
29701 @node Use of Boolean Constants
29702 @section Use of Boolean Constants
29703
29704 @noindent
29705 In the case where the difference is simply which code
29706 sequence is executed, the cleanest solution is to use Boolean
29707 constants to control which code is executed.
29708
29709 @smallexample @c ada
29710 @group
29711 FP_Initialize_Required : constant Boolean := True;
29712 @dots{}
29713 if FP_Initialize_Required then
29714 @dots{}
29715 end if;
29716 @end group
29717 @end smallexample
29718
29719 @noindent
29720 Not only will the code inside the @code{if} statement not be executed if
29721 the constant Boolean is @code{False}, but it will also be completely
29722 deleted from the program.
29723 However, the code is only deleted after the @code{if} statement
29724 has been checked for syntactic and semantic correctness.
29725 (In contrast, with preprocessors the code is deleted before the
29726 compiler ever gets to see it, so it is not checked until the switch
29727 is turned on.)
29728 @cindex Preprocessors (contrasted with conditional compilation)
29729
29730 Typically the Boolean constants will be in a separate package,
29731 something like:
29732
29733 @smallexample @c ada
29734 @group
29735 package Config is
29736    FP_Initialize_Required : constant Boolean := True;
29737    Reset_Available        : constant Boolean := False;
29738    @dots{}
29739 end Config;
29740 @end group
29741 @end smallexample
29742
29743 @noindent
29744 The @code{Config} package exists in multiple forms for the various targets,
29745 with an appropriate script selecting the version of @code{Config} needed.
29746 Then any other unit requiring conditional compilation can do a @code{with}
29747 of @code{Config} to make the constants visible.
29748
29749
29750 @node Debugging - A Special Case
29751 @section Debugging - A Special Case
29752
29753 @noindent
29754 A common use of conditional code is to execute statements (for example
29755 dynamic checks, or output of intermediate results) under control of a
29756 debug switch, so that the debugging behavior can be turned on and off.
29757 This can be done using a Boolean constant to control whether the code
29758 is active:
29759
29760 @smallexample @c ada
29761 @group
29762 if Debugging then
29763    Put_Line ("got to the first stage!");
29764 end if;
29765 @end group
29766 @end smallexample
29767
29768 @noindent
29769 or
29770
29771 @smallexample @c ada
29772 @group
29773 if Debugging and then Temperature > 999.0 then
29774    raise Temperature_Crazy;
29775 end if;
29776 @end group
29777 @end smallexample
29778
29779 @noindent
29780 Since this is a common case, there are special features to deal with
29781 this in a convenient manner. For the case of tests, Ada 2005 has added
29782 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
29783 @cindex pragma @code{Assert}
29784 on the @code{Assert} pragma that has always been available in GNAT, so this
29785 feature may be used with GNAT even if you are not using Ada 2005 features.
29786 The use of pragma @code{Assert} is described in
29787 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
29788 example, the last test could be written:
29789
29790 @smallexample @c ada
29791 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
29792 @end smallexample
29793
29794 @noindent
29795 or simply
29796
29797 @smallexample @c ada
29798 pragma Assert (Temperature <= 999.0);
29799 @end smallexample
29800
29801 @noindent
29802 In both cases, if assertions are active and the temperature is excessive,
29803 the exception @code{Assert_Failure} will be raised, with the given string in
29804 the first case or a string indicating the location of the pragma in the second
29805 case used as the exception message.
29806
29807 You can turn assertions on and off by using the @code{Assertion_Policy}
29808 pragma.
29809 @cindex pragma @code{Assertion_Policy}
29810 This is an Ada 2005 pragma which is implemented in all modes by
29811 GNAT, but only in the latest versions of GNAT which include Ada 2005
29812 capability. Alternatively, you can use the @option{-gnata} switch
29813 @cindex @option{-gnata} switch
29814 to enable assertions from the command line (this is recognized by all versions
29815 of GNAT).
29816
29817 For the example above with the @code{Put_Line}, the GNAT-specific pragma
29818 @code{Debug} can be used:
29819 @cindex pragma @code{Debug}
29820
29821 @smallexample @c ada
29822 pragma Debug (Put_Line ("got to the first stage!"));
29823 @end smallexample
29824
29825 @noindent
29826 If debug pragmas are enabled, the argument, which must be of the form of
29827 a procedure call, is executed (in this case, @code{Put_Line} will be called).
29828 Only one call can be present, but of course a special debugging procedure
29829 containing any code you like can be included in the program and then
29830 called in a pragma @code{Debug} argument as needed.
29831
29832 One advantage of pragma @code{Debug} over the @code{if Debugging then}
29833 construct is that pragma @code{Debug} can appear in declarative contexts,
29834 such as at the very beginning of a procedure, before local declarations have
29835 been elaborated.
29836
29837 Debug pragmas are enabled using either the @option{-gnata} switch that also
29838 controls assertions, or with a separate Debug_Policy pragma.
29839 @cindex pragma @code{Debug_Policy}
29840 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
29841 in Ada 95 and Ada 83 programs as well), and is analogous to
29842 pragma @code{Assertion_Policy} to control assertions.
29843
29844 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
29845 and thus they can appear in @file{gnat.adc} if you are not using a
29846 project file, or in the file designated to contain configuration pragmas
29847 in a project file.
29848 They then apply to all subsequent compilations. In practice the use of
29849 the @option{-gnata} switch is often the most convenient method of controlling
29850 the status of these pragmas.
29851
29852 Note that a pragma is not a statement, so in contexts where a statement
29853 sequence is required, you can't just write a pragma on its own. You have
29854 to add a @code{null} statement.
29855
29856 @smallexample @c ada
29857 @group
29858 if @dots{} then
29859    @dots{} -- some statements
29860 else
29861    pragma Assert (Num_Cases < 10);
29862    null;
29863 end if;
29864 @end group
29865 @end smallexample
29866
29867
29868 @node Conditionalizing Declarations
29869 @section Conditionalizing Declarations
29870
29871 @noindent
29872 In some cases, it may be necessary to conditionalize declarations to meet
29873 different requirements. For example we might want a bit string whose length
29874 is set to meet some hardware message requirement.
29875
29876 In some cases, it may be possible to do this using declare blocks controlled
29877 by conditional constants:
29878
29879 @smallexample @c ada
29880 @group
29881 if Small_Machine then
29882    declare
29883       X : Bit_String (1 .. 10);
29884    begin
29885       @dots{}
29886    end;
29887 else
29888    declare
29889       X : Large_Bit_String (1 .. 1000);
29890    begin
29891       @dots{}
29892    end;
29893 end if;
29894 @end group
29895 @end smallexample
29896
29897 @noindent
29898 Note that in this approach, both declarations are analyzed by the
29899 compiler so this can only be used where both declarations are legal,
29900 even though one of them will not be used.
29901
29902 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
29903 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
29904 that are parameterized by these constants. For example
29905
29906 @smallexample @c ada
29907 @group
29908 for Rec use
29909   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
29910 end record;
29911 @end group
29912 @end smallexample
29913
29914 @noindent
29915 If @code{Bits_Per_Word} is set to 32, this generates either
29916
29917 @smallexample @c ada
29918 @group
29919 for Rec use
29920   Field1 at 0 range 0 .. 32;
29921 end record;
29922 @end group
29923 @end smallexample
29924
29925 @noindent
29926 for the big endian case, or
29927
29928 @smallexample @c ada
29929 @group
29930 for Rec use record
29931   Field1 at 0 range 10 .. 32;
29932 end record;
29933 @end group
29934 @end smallexample
29935
29936 @noindent
29937 for the little endian case. Since a powerful subset of Ada expression
29938 notation is usable for creating static constants, clever use of this
29939 feature can often solve quite difficult problems in conditionalizing
29940 compilation (note incidentally that in Ada 95, the little endian
29941 constant was introduced as @code{System.Default_Bit_Order}, so you do not
29942 need to define this one yourself).
29943
29944
29945 @node Use of Alternative Implementations
29946 @section Use of Alternative Implementations
29947
29948 @noindent
29949 In some cases, none of the approaches described above are adequate. This
29950 can occur for example if the set of declarations required is radically
29951 different for two different configurations.
29952
29953 In this situation, the official Ada way of dealing with conditionalizing
29954 such code is to write separate units for the different cases. As long as
29955 this does not result in excessive duplication of code, this can be done
29956 without creating maintenance problems. The approach is to share common
29957 code as far as possible, and then isolate the code and declarations
29958 that are different. Subunits are often a convenient method for breaking
29959 out a piece of a unit that is to be conditionalized, with separate files
29960 for different versions of the subunit for different targets, where the
29961 build script selects the right one to give to the compiler.
29962 @cindex Subunits (and conditional compilation)
29963
29964 As an example, consider a situation where a new feature in Ada 2005
29965 allows something to be done in a really nice way. But your code must be able
29966 to compile with an Ada 95 compiler. Conceptually you want to say:
29967
29968 @smallexample @c ada
29969 @group
29970 if Ada_2005 then
29971    @dots{} neat Ada 2005 code
29972 else
29973    @dots{} not quite as neat Ada 95 code
29974 end if;
29975 @end group
29976 @end smallexample
29977
29978 @noindent
29979 where @code{Ada_2005} is a Boolean constant.
29980
29981 But this won't work when @code{Ada_2005} is set to @code{False},
29982 since the @code{then} clause will be illegal for an Ada 95 compiler.
29983 (Recall that although such unreachable code would eventually be deleted
29984 by the compiler, it still needs to be legal.  If it uses features
29985 introduced in Ada 2005, it will be illegal in Ada 95.)
29986
29987 So instead we write
29988
29989 @smallexample @c ada
29990 procedure Insert is separate;
29991 @end smallexample
29992
29993 @noindent
29994 Then we have two files for the subunit @code{Insert}, with the two sets of
29995 code.
29996 If the package containing this is called @code{File_Queries}, then we might
29997 have two files
29998
29999 @itemize @bullet
30000 @item    @file{file_queries-insert-2005.adb}
30001 @item    @file{file_queries-insert-95.adb}
30002 @end itemize
30003
30004 @noindent
30005 and the build script renames the appropriate file to
30006
30007 @smallexample
30008 file_queries-insert.adb
30009 @end smallexample
30010
30011 @noindent
30012 and then carries out the compilation.
30013
30014 This can also be done with project files' naming schemes. For example:
30015
30016 @smallexample @c project
30017 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
30018 @end smallexample
30019
30020 @noindent
30021 Note also that with project files it is desirable to use a different extension
30022 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
30023 conflict may arise through another commonly used feature: to declare as part
30024 of the project a set of directories containing all the sources obeying the
30025 default naming scheme.
30026
30027 The use of alternative units is certainly feasible in all situations,
30028 and for example the Ada part of the GNAT run-time is conditionalized
30029 based on the target architecture using this approach. As a specific example,
30030 consider the implementation of the AST feature in VMS. There is one
30031 spec:
30032
30033 @smallexample
30034 s-asthan.ads
30035 @end smallexample
30036
30037 @noindent
30038 which is the same for all architectures, and three bodies:
30039
30040 @table @file
30041 @item    s-asthan.adb
30042 used for all non-VMS operating systems
30043 @item    s-asthan-vms-alpha.adb
30044 used for VMS on the Alpha
30045 @item    s-asthan-vms-ia64.adb
30046 used for VMS on the ia64
30047 @end table
30048
30049 @noindent
30050 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
30051 this operating system feature is not available, and the two remaining
30052 versions interface with the corresponding versions of VMS to provide
30053 VMS-compatible AST handling. The GNAT build script knows the architecture
30054 and operating system, and automatically selects the right version,
30055 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
30056
30057 Another style for arranging alternative implementations is through Ada's
30058 access-to-subprogram facility.
30059 In case some functionality is to be conditionally included,
30060 you can declare an access-to-procedure variable @code{Ref} that is initialized
30061 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
30062 when appropriate.
30063 In some library package, set @code{Ref} to @code{Proc'Access} for some
30064 procedure @code{Proc} that performs the relevant processing.
30065 The initialization only occurs if the library package is included in the
30066 program.
30067 The same idea can also be implemented using tagged types and dispatching
30068 calls.
30069
30070
30071 @node Preprocessing
30072 @section Preprocessing
30073 @cindex Preprocessing
30074
30075 @noindent
30076 Although it is quite possible to conditionalize code without the use of
30077 C-style preprocessing, as described earlier in this section, it is
30078 nevertheless convenient in some cases to use the C approach. Moreover,
30079 older Ada compilers have often provided some preprocessing capability,
30080 so legacy code may depend on this approach, even though it is not
30081 standard.
30082
30083 To accommodate such use, GNAT provides a preprocessor (modeled to a large
30084 extent on the various preprocessors that have been used
30085 with legacy code on other compilers, to enable easier transition).
30086
30087 The preprocessor may be used in two separate modes. It can be used quite
30088 separately from the compiler, to generate a separate output source file
30089 that is then fed to the compiler as a separate step. This is the
30090 @code{gnatprep} utility, whose use is fully described in
30091 @ref{Preprocessing Using gnatprep}.
30092 @cindex @code{gnatprep}
30093
30094 The preprocessing language allows such constructs as
30095
30096 @smallexample
30097 @group
30098 #if DEBUG or PRIORITY > 4 then
30099    bunch of declarations
30100 #else
30101    completely different bunch of declarations
30102 #end if;
30103 @end group
30104 @end smallexample
30105
30106 @noindent
30107 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
30108 defined either on the command line or in a separate file.
30109
30110 The other way of running the preprocessor is even closer to the C style and
30111 often more convenient. In this approach the preprocessing is integrated into
30112 the compilation process. The compiler is fed the preprocessor input which
30113 includes @code{#if} lines etc, and then the compiler carries out the
30114 preprocessing internally and processes the resulting output.
30115 For more details on this approach, see @ref{Integrated Preprocessing}.
30116
30117
30118 @c *******************************
30119 @node Inline Assembler
30120 @appendix Inline Assembler
30121 @c *******************************
30122
30123 @noindent
30124 If you need to write low-level software that interacts directly
30125 with the hardware, Ada provides two ways to incorporate assembly
30126 language code into your program.  First, you can import and invoke
30127 external routines written in assembly language, an Ada feature fully
30128 supported by GNAT@.  However, for small sections of code it may be simpler
30129 or more efficient to include assembly language statements directly
30130 in your Ada source program, using the facilities of the implementation-defined
30131 package @code{System.Machine_Code}, which incorporates the gcc
30132 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
30133 including the following:
30134
30135 @itemize @bullet
30136 @item No need to use non-Ada tools
30137 @item Consistent interface over different targets
30138 @item Automatic usage of the proper calling conventions
30139 @item Access to Ada constants and variables
30140 @item Definition of intrinsic routines
30141 @item Possibility of inlining a subprogram comprising assembler code
30142 @item Code optimizer can take Inline Assembler code into account
30143 @end itemize
30144
30145 This chapter presents a series of examples to show you how to use
30146 the Inline Assembler.  Although it focuses on the Intel x86,
30147 the general approach applies also to other processors.
30148 It is assumed that you are familiar with Ada
30149 and with assembly language programming.
30150
30151 @menu
30152 * Basic Assembler Syntax::
30153 * A Simple Example of Inline Assembler::
30154 * Output Variables in Inline Assembler::
30155 * Input Variables in Inline Assembler::
30156 * Inlining Inline Assembler Code::
30157 * Other Asm Functionality::
30158 @end menu
30159
30160 @c ---------------------------------------------------------------------------
30161 @node Basic Assembler Syntax
30162 @section Basic Assembler Syntax
30163
30164 @noindent
30165 The assembler used by GNAT and gcc is based not on the Intel assembly
30166 language, but rather on a language that descends from the AT&T Unix
30167 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
30168 The following table summarizes the main features of @emph{as} syntax
30169 and points out the differences from the Intel conventions.
30170 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
30171 pre-processor) documentation for further information.
30172
30173 @table @asis
30174 @item Register names
30175 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
30176 @*
30177 Intel: No extra punctuation; for example @code{eax}
30178
30179 @item Immediate operand
30180 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
30181 @*
30182 Intel: No extra punctuation; for example @code{4}
30183
30184 @item Address
30185 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
30186 @*
30187 Intel: No extra punctuation; for example @code{loc}
30188
30189 @item Memory contents
30190 gcc / @emph{as}: No extra punctuation; for example @code{loc}
30191 @*
30192 Intel: Square brackets; for example @code{[loc]}
30193
30194 @item Register contents
30195 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
30196 @*
30197 Intel: Square brackets; for example @code{[eax]}
30198
30199 @item Hexadecimal numbers
30200 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
30201 @*
30202 Intel: Trailing ``h''; for example @code{A0h}
30203
30204 @item Operand size
30205 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
30206 a 16-bit word
30207 @*
30208 Intel: Implicit, deduced by assembler; for example @code{mov}
30209
30210 @item Instruction repetition
30211 gcc / @emph{as}: Split into two lines; for example
30212 @*
30213 @code{rep}
30214 @*
30215 @code{stosl}
30216 @*
30217 Intel: Keep on one line; for example @code{rep stosl}
30218
30219 @item Order of operands
30220 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
30221 @*
30222 Intel: Destination first; for example @code{mov eax, 4}
30223 @end table
30224
30225 @c ---------------------------------------------------------------------------
30226 @node A Simple Example of Inline Assembler
30227 @section A Simple Example of Inline Assembler
30228
30229 @noindent
30230 The following example will generate a single assembly language statement,
30231 @code{nop}, which does nothing.  Despite its lack of run-time effect,
30232 the example will be useful in illustrating the basics of
30233 the Inline Assembler facility.
30234
30235 @smallexample @c ada
30236 @group
30237 with System.Machine_Code; use System.Machine_Code;
30238 procedure Nothing is
30239 begin
30240    Asm ("nop");
30241 end Nothing;
30242 @end group
30243 @end smallexample
30244
30245 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
30246 here it takes one parameter, a @emph{template string} that must be a static
30247 expression and that will form the generated instruction.
30248 @code{Asm} may be regarded as a compile-time procedure that parses
30249 the template string and additional parameters (none here),
30250 from which it generates a sequence of assembly language instructions.
30251
30252 The examples in this chapter will illustrate several of the forms
30253 for invoking @code{Asm}; a complete specification of the syntax
30254 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
30255 Manual}.
30256
30257 Under the standard GNAT conventions, the @code{Nothing} procedure
30258 should be in a file named @file{nothing.adb}.
30259 You can build the executable in the usual way:
30260 @smallexample
30261 gnatmake nothing
30262 @end smallexample
30263 However, the interesting aspect of this example is not its run-time behavior
30264 but rather the generated assembly code.
30265 To see this output, invoke the compiler as follows:
30266 @smallexample
30267    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
30268 @end smallexample
30269 where the options are:
30270
30271 @table @code
30272 @item -c
30273 compile only (no bind or link)
30274 @item -S
30275 generate assembler listing
30276 @item -fomit-frame-pointer
30277 do not set up separate stack frames
30278 @item -gnatp
30279 do not add runtime checks
30280 @end table
30281
30282 This gives a human-readable assembler version of the code. The resulting
30283 file will have the same name as the Ada source file, but with a @code{.s}
30284 extension. In our example, the file @file{nothing.s} has the following
30285 contents:
30286
30287 @smallexample
30288 @group
30289 .file "nothing.adb"
30290 gcc2_compiled.:
30291 ___gnu_compiled_ada:
30292 .text
30293    .align 4
30294 .globl __ada_nothing
30295 __ada_nothing:
30296 #APP
30297    nop
30298 #NO_APP
30299    jmp L1
30300    .align 2,0x90
30301 L1:
30302    ret
30303 @end group
30304 @end smallexample
30305
30306 The assembly code you included is clearly indicated by
30307 the compiler, between the @code{#APP} and @code{#NO_APP}
30308 delimiters. The character before the 'APP' and 'NOAPP'
30309 can differ on different targets. For example, GNU/Linux uses '#APP' while
30310 on NT you will see '/APP'.
30311
30312 If you make a mistake in your assembler code (such as using the
30313 wrong size modifier, or using a wrong operand for the instruction) GNAT
30314 will report this error in a temporary file, which will be deleted when
30315 the compilation is finished.  Generating an assembler file will help
30316 in such cases, since you can assemble this file separately using the
30317 @emph{as} assembler that comes with gcc.
30318
30319 Assembling the file using the command
30320
30321 @smallexample
30322 as @file{nothing.s}
30323 @end smallexample
30324 @noindent
30325 will give you error messages whose lines correspond to the assembler
30326 input file, so you can easily find and correct any mistakes you made.
30327 If there are no errors, @emph{as} will generate an object file
30328 @file{nothing.out}.
30329
30330 @c ---------------------------------------------------------------------------
30331 @node Output Variables in Inline Assembler
30332 @section Output Variables in Inline Assembler
30333
30334 @noindent
30335 The examples in this section, showing how to access the processor flags,
30336 illustrate how to specify the destination operands for assembly language
30337 statements.
30338
30339 @smallexample @c ada
30340 @group
30341 with Interfaces; use Interfaces;
30342 with Ada.Text_IO; use Ada.Text_IO;
30343 with System.Machine_Code; use System.Machine_Code;
30344 procedure Get_Flags is
30345    Flags : Unsigned_32;
30346    use ASCII;
30347 begin
30348    Asm ("pushfl"          & LF & HT & -- push flags on stack
30349         "popl %%eax"      & LF & HT & -- load eax with flags
30350         "movl %%eax, %0",             -- store flags in variable
30351         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30352    Put_Line ("Flags register:" & Flags'Img);
30353 end Get_Flags;
30354 @end group
30355 @end smallexample
30356
30357 In order to have a nicely aligned assembly listing, we have separated
30358 multiple assembler statements in the Asm template string with linefeed
30359 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
30360 The resulting section of the assembly output file is:
30361
30362 @smallexample
30363 @group
30364 #APP
30365    pushfl
30366    popl %eax
30367    movl %eax, -40(%ebp)
30368 #NO_APP
30369 @end group
30370 @end smallexample
30371
30372 It would have been legal to write the Asm invocation as:
30373
30374 @smallexample
30375 Asm ("pushfl popl %%eax movl %%eax, %0")
30376 @end smallexample
30377
30378 but in the generated assembler file, this would come out as:
30379
30380 @smallexample
30381 #APP
30382    pushfl popl %eax movl %eax, -40(%ebp)
30383 #NO_APP
30384 @end smallexample
30385
30386 which is not so convenient for the human reader.
30387
30388 We use Ada comments
30389 at the end of each line to explain what the assembler instructions
30390 actually do.  This is a useful convention.
30391
30392 When writing Inline Assembler instructions, you need to precede each register
30393 and variable name with a percent sign.  Since the assembler already requires
30394 a percent sign at the beginning of a register name, you need two consecutive
30395 percent signs for such names in the Asm template string, thus @code{%%eax}.
30396 In the generated assembly code, one of the percent signs will be stripped off.
30397
30398 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
30399 variables: operands you later define using @code{Input} or @code{Output}
30400 parameters to @code{Asm}.
30401 An output variable is illustrated in
30402 the third statement in the Asm template string:
30403 @smallexample
30404 movl %%eax, %0
30405 @end smallexample
30406 The intent is to store the contents of the eax register in a variable that can
30407 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
30408 necessarily work, since the compiler might optimize by using a register
30409 to hold Flags, and the expansion of the @code{movl} instruction would not be
30410 aware of this optimization.  The solution is not to store the result directly
30411 but rather to advise the compiler to choose the correct operand form;
30412 that is the purpose of the @code{%0} output variable.
30413
30414 Information about the output variable is supplied in the @code{Outputs}
30415 parameter to @code{Asm}:
30416 @smallexample
30417 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30418 @end smallexample
30419
30420 The output is defined by the @code{Asm_Output} attribute of the target type;
30421 the general format is
30422 @smallexample
30423 Type'Asm_Output (constraint_string, variable_name)
30424 @end smallexample
30425
30426 The constraint string directs the compiler how
30427 to store/access the associated variable.  In the example
30428 @smallexample
30429 Unsigned_32'Asm_Output ("=m", Flags);
30430 @end smallexample
30431 the @code{"m"} (memory) constraint tells the compiler that the variable
30432 @code{Flags} should be stored in a memory variable, thus preventing
30433 the optimizer from keeping it in a register.  In contrast,
30434 @smallexample
30435 Unsigned_32'Asm_Output ("=r", Flags);
30436 @end smallexample
30437 uses the @code{"r"} (register) constraint, telling the compiler to
30438 store the variable in a register.
30439
30440 If the constraint is preceded by the equal character (@strong{=}), it tells
30441 the compiler that the variable will be used to store data into it.
30442
30443 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
30444 allowing the optimizer to choose whatever it deems best.
30445
30446 There are a fairly large number of constraints, but the ones that are
30447 most useful (for the Intel x86 processor) are the following:
30448
30449 @table @code
30450 @item =
30451 output constraint
30452 @item g
30453 global (i.e.@: can be stored anywhere)
30454 @item m
30455 in memory
30456 @item I
30457 a constant
30458 @item a
30459 use eax
30460 @item b
30461 use ebx
30462 @item c
30463 use ecx
30464 @item d
30465 use edx
30466 @item S
30467 use esi
30468 @item D
30469 use edi
30470 @item r
30471 use one of eax, ebx, ecx or edx
30472 @item q
30473 use one of eax, ebx, ecx, edx, esi or edi
30474 @end table
30475
30476 The full set of constraints is described in the gcc and @emph{as}
30477 documentation; note that it is possible to combine certain constraints
30478 in one constraint string.
30479
30480 You specify the association of an output variable with an assembler operand
30481 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
30482 integer.  Thus in
30483 @smallexample @c ada
30484 @group
30485 Asm ("pushfl"          & LF & HT & -- push flags on stack
30486      "popl %%eax"      & LF & HT & -- load eax with flags
30487      "movl %%eax, %0",             -- store flags in variable
30488      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30489 @end group
30490 @end smallexample
30491 @noindent
30492 @code{%0} will be replaced in the expanded code by the appropriate operand,
30493 whatever
30494 the compiler decided for the @code{Flags} variable.
30495
30496 In general, you may have any number of output variables:
30497 @itemize @bullet
30498 @item
30499 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
30500 @item
30501 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
30502 of @code{Asm_Output} attributes
30503 @end itemize
30504
30505 For example:
30506 @smallexample @c ada
30507 @group
30508 Asm ("movl %%eax, %0" & LF & HT &
30509      "movl %%ebx, %1" & LF & HT &
30510      "movl %%ecx, %2",
30511      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
30512                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
30513                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
30514 @end group
30515 @end smallexample
30516 @noindent
30517 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
30518 in the Ada program.
30519
30520 As a variation on the @code{Get_Flags} example, we can use the constraints
30521 string to direct the compiler to store the eax register into the @code{Flags}
30522 variable, instead of including the store instruction explicitly in the
30523 @code{Asm} template string:
30524
30525 @smallexample @c ada
30526 @group
30527 with Interfaces; use Interfaces;
30528 with Ada.Text_IO; use Ada.Text_IO;
30529 with System.Machine_Code; use System.Machine_Code;
30530 procedure Get_Flags_2 is
30531    Flags : Unsigned_32;
30532    use ASCII;
30533 begin
30534    Asm ("pushfl"      & LF & HT & -- push flags on stack
30535         "popl %%eax",             -- save flags in eax
30536         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
30537    Put_Line ("Flags register:" & Flags'Img);
30538 end Get_Flags_2;
30539 @end group
30540 @end smallexample
30541
30542 @noindent
30543 The @code{"a"} constraint tells the compiler that the @code{Flags}
30544 variable will come from the eax register. Here is the resulting code:
30545
30546 @smallexample
30547 @group
30548 #APP
30549    pushfl
30550    popl %eax
30551 #NO_APP
30552    movl %eax,-40(%ebp)
30553 @end group
30554 @end smallexample
30555
30556 @noindent
30557 The compiler generated the store of eax into Flags after
30558 expanding the assembler code.
30559
30560 Actually, there was no need to pop the flags into the eax register;
30561 more simply, we could just pop the flags directly into the program variable:
30562
30563 @smallexample @c ada
30564 @group
30565 with Interfaces; use Interfaces;
30566 with Ada.Text_IO; use Ada.Text_IO;
30567 with System.Machine_Code; use System.Machine_Code;
30568 procedure Get_Flags_3 is
30569    Flags : Unsigned_32;
30570    use ASCII;
30571 begin
30572    Asm ("pushfl"  & LF & HT & -- push flags on stack
30573         "pop %0",             -- save flags in Flags
30574         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30575    Put_Line ("Flags register:" & Flags'Img);
30576 end Get_Flags_3;
30577 @end group
30578 @end smallexample
30579
30580 @c ---------------------------------------------------------------------------
30581 @node Input Variables in Inline Assembler
30582 @section Input Variables in Inline Assembler
30583
30584 @noindent
30585 The example in this section illustrates how to specify the source operands
30586 for assembly language statements.
30587 The program simply increments its input value by 1:
30588
30589 @smallexample @c ada
30590 @group
30591 with Interfaces; use Interfaces;
30592 with Ada.Text_IO; use Ada.Text_IO;
30593 with System.Machine_Code; use System.Machine_Code;
30594 procedure Increment is
30595
30596    function Incr (Value : Unsigned_32) return Unsigned_32 is
30597       Result : Unsigned_32;
30598    begin
30599       Asm ("incl %0",
30600            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30601            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30602       return Result;
30603    end Incr;
30604
30605    Value : Unsigned_32;
30606
30607 begin
30608    Value := 5;
30609    Put_Line ("Value before is" & Value'Img);
30610    Value := Incr (Value);
30611    Put_Line ("Value after is" & Value'Img);
30612 end Increment;
30613 @end group
30614 @end smallexample
30615
30616 The @code{Outputs} parameter to @code{Asm} specifies
30617 that the result will be in the eax register and that it is to be stored
30618 in the @code{Result} variable.
30619
30620 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
30621 but with an @code{Asm_Input} attribute.
30622 The @code{"="} constraint, indicating an output value, is not present.
30623
30624 You can have multiple input variables, in the same way that you can have more
30625 than one output variable.
30626
30627 The parameter count (%0, %1) etc, now starts at the first input
30628 statement, and continues with the output statements.
30629 When both parameters use the same variable, the
30630 compiler will treat them as the same %n operand, which is the case here.
30631
30632 Just as the @code{Outputs} parameter causes the register to be stored into the
30633 target variable after execution of the assembler statements, so does the
30634 @code{Inputs} parameter cause its variable to be loaded into the register
30635 before execution of the assembler statements.
30636
30637 Thus the effect of the @code{Asm} invocation is:
30638 @enumerate
30639 @item load the 32-bit value of @code{Value} into eax
30640 @item execute the @code{incl %eax} instruction
30641 @item store the contents of eax into the @code{Result} variable
30642 @end enumerate
30643
30644 The resulting assembler file (with @option{-O2} optimization) contains:
30645 @smallexample
30646 @group
30647 _increment__incr.1:
30648    subl $4,%esp
30649    movl 8(%esp),%eax
30650 #APP
30651    incl %eax
30652 #NO_APP
30653    movl %eax,%edx
30654    movl %ecx,(%esp)
30655    addl $4,%esp
30656    ret
30657 @end group
30658 @end smallexample
30659
30660 @c ---------------------------------------------------------------------------
30661 @node Inlining Inline Assembler Code
30662 @section Inlining Inline Assembler Code
30663
30664 @noindent
30665 For a short subprogram such as the @code{Incr} function in the previous
30666 section, the overhead of the call and return (creating / deleting the stack
30667 frame) can be significant, compared to the amount of code in the subprogram
30668 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
30669 which directs the compiler to expand invocations of the subprogram at the
30670 point(s) of call, instead of setting up a stack frame for out-of-line calls.
30671 Here is the resulting program:
30672
30673 @smallexample @c ada
30674 @group
30675 with Interfaces; use Interfaces;
30676 with Ada.Text_IO; use Ada.Text_IO;
30677 with System.Machine_Code; use System.Machine_Code;
30678 procedure Increment_2 is
30679
30680    function Incr (Value : Unsigned_32) return Unsigned_32 is
30681       Result : Unsigned_32;
30682    begin
30683       Asm ("incl %0",
30684            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30685            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30686       return Result;
30687    end Incr;
30688    pragma Inline (Increment);
30689
30690    Value : Unsigned_32;
30691
30692 begin
30693    Value := 5;
30694    Put_Line ("Value before is" & Value'Img);
30695    Value := Increment (Value);
30696    Put_Line ("Value after is" & Value'Img);
30697 end Increment_2;
30698 @end group
30699 @end smallexample
30700
30701 Compile the program with both optimization (@option{-O2}) and inlining
30702 (@option{-gnatn}) enabled.
30703
30704 The @code{Incr} function is still compiled as usual, but at the
30705 point in @code{Increment} where our function used to be called:
30706
30707 @smallexample
30708 @group
30709 pushl %edi
30710 call _increment__incr.1
30711 @end group
30712 @end smallexample
30713
30714 @noindent
30715 the code for the function body directly appears:
30716
30717 @smallexample
30718 @group
30719 movl %esi,%eax
30720 #APP
30721    incl %eax
30722 #NO_APP
30723    movl %eax,%edx
30724 @end group
30725 @end smallexample
30726
30727 @noindent
30728 thus saving the overhead of stack frame setup and an out-of-line call.
30729
30730 @c ---------------------------------------------------------------------------
30731 @node Other Asm Functionality
30732 @section Other @code{Asm} Functionality
30733
30734 @noindent
30735 This section describes two important parameters to the @code{Asm}
30736 procedure: @code{Clobber}, which identifies register usage;
30737 and @code{Volatile}, which inhibits unwanted optimizations.
30738
30739 @menu
30740 * The Clobber Parameter::
30741 * The Volatile Parameter::
30742 @end menu
30743
30744 @c ---------------------------------------------------------------------------
30745 @node The Clobber Parameter
30746 @subsection The @code{Clobber} Parameter
30747
30748 @noindent
30749 One of the dangers of intermixing assembly language and a compiled language
30750 such as Ada is that the compiler needs to be aware of which registers are
30751 being used by the assembly code.  In some cases, such as the earlier examples,
30752 the constraint string is sufficient to indicate register usage (e.g.,
30753 @code{"a"} for
30754 the eax register).  But more generally, the compiler needs an explicit
30755 identification of the registers that are used by the Inline Assembly
30756 statements.
30757
30758 Using a register that the compiler doesn't know about
30759 could be a side effect of an instruction (like @code{mull}
30760 storing its result in both eax and edx).
30761 It can also arise from explicit register usage in your
30762 assembly code; for example:
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 @end group
30770 @end smallexample
30771 @noindent
30772 where the compiler (since it does not analyze the @code{Asm} template string)
30773 does not know you are using the ebx register.
30774
30775 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
30776 to identify the registers that will be used by your assembly code:
30777
30778 @smallexample
30779 @group
30780 Asm ("movl %0, %%ebx" & LF & HT &
30781      "movl %%ebx, %1",
30782      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30783      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30784      Clobber => "ebx");
30785 @end group
30786 @end smallexample
30787
30788 The Clobber parameter is a static string expression specifying the
30789 register(s) you are using.  Note that register names are @emph{not} prefixed
30790 by a percent sign. Also, if more than one register is used then their names
30791 are separated by commas; e.g., @code{"eax, ebx"}
30792
30793 The @code{Clobber} parameter has several additional uses:
30794 @enumerate
30795 @item Use ``register'' name @code{cc} to indicate that flags might have changed
30796 @item Use ``register'' name @code{memory} if you changed a memory location
30797 @end enumerate
30798
30799 @c ---------------------------------------------------------------------------
30800 @node The Volatile Parameter
30801 @subsection The @code{Volatile} Parameter
30802 @cindex Volatile parameter
30803
30804 @noindent
30805 Compiler optimizations in the presence of Inline Assembler may sometimes have
30806 unwanted effects.  For example, when an @code{Asm} invocation with an input
30807 variable is inside a loop, the compiler might move the loading of the input
30808 variable outside the loop, regarding it as a one-time initialization.
30809
30810 If this effect is not desired, you can disable such optimizations by setting
30811 the @code{Volatile} parameter to @code{True}; for example:
30812
30813 @smallexample @c ada
30814 @group
30815 Asm ("movl %0, %%ebx" & LF & HT &
30816      "movl %%ebx, %1",
30817      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
30818      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
30819      Clobber  => "ebx",
30820      Volatile => True);
30821 @end group
30822 @end smallexample
30823
30824 By default, @code{Volatile} is set to @code{False} unless there is no
30825 @code{Outputs} parameter.
30826
30827 Although setting @code{Volatile} to @code{True} prevents unwanted
30828 optimizations, it will also disable other optimizations that might be
30829 important for efficiency. In general, you should set @code{Volatile}
30830 to @code{True} only if the compiler's optimizations have created
30831 problems.
30832 @c END OF INLINE ASSEMBLER CHAPTER
30833 @c ===============================
30834
30835 @c ***********************************
30836 @c * Compatibility and Porting Guide *
30837 @c ***********************************
30838 @node Compatibility and Porting Guide
30839 @appendix Compatibility and Porting Guide
30840
30841 @noindent
30842 This chapter describes the compatibility issues that may arise between
30843 GNAT and other Ada compilation systems (including those for Ada 83),
30844 and shows how GNAT can expedite porting
30845 applications developed in other Ada environments.
30846
30847 @menu
30848 * Compatibility with Ada 83::
30849 * Compatibility between Ada 95 and Ada 2005::
30850 * Implementation-dependent characteristics::
30851 * Compatibility with Other Ada Systems::
30852 * Representation Clauses::
30853 @ifclear vms
30854 @c Brief section is only in non-VMS version
30855 @c Full chapter is in VMS version
30856 * Compatibility with HP Ada 83::
30857 @end ifclear
30858 @ifset vms
30859 * Transitioning to 64-Bit GNAT for OpenVMS::
30860 @end ifset
30861 @end menu
30862
30863 @node Compatibility with Ada 83
30864 @section Compatibility with Ada 83
30865 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
30866
30867 @noindent
30868 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
30869 particular, the design intention was that the difficulties associated
30870 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
30871 that occur when moving from one Ada 83 system to another.
30872
30873 However, there are a number of points at which there are minor
30874 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
30875 full details of these issues,
30876 and should be consulted for a complete treatment.
30877 In practice the
30878 following subsections treat the most likely issues to be encountered.
30879
30880 @menu
30881 * Legal Ada 83 programs that are illegal in Ada 95::
30882 * More deterministic semantics::
30883 * Changed semantics::
30884 * Other language compatibility issues::
30885 @end menu
30886
30887 @node Legal Ada 83 programs that are illegal in Ada 95
30888 @subsection Legal Ada 83 programs that are illegal in Ada 95
30889
30890 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
30891 Ada 95 and thus also in Ada 2005:
30892
30893 @table @emph
30894 @item Character literals
30895 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
30896 @code{Wide_Character} as a new predefined character type, some uses of
30897 character literals that were legal in Ada 83 are illegal in Ada 95.
30898 For example:
30899 @smallexample @c ada
30900    for Char in 'A' .. 'Z' loop @dots{} end loop;
30901 @end smallexample
30902
30903 @noindent
30904 The problem is that @code{'A'} and @code{'Z'} could be from either
30905 @code{Character} or @code{Wide_Character}.  The simplest correction
30906 is to make the type explicit; e.g.:
30907 @smallexample @c ada
30908    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
30909 @end smallexample
30910
30911 @item New reserved words
30912 The identifiers @code{abstract}, @code{aliased}, @code{protected},
30913 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
30914 Existing Ada 83 code using any of these identifiers must be edited to
30915 use some alternative name.
30916
30917 @item Freezing rules
30918 The rules in Ada 95 are slightly different with regard to the point at
30919 which entities are frozen, and representation pragmas and clauses are
30920 not permitted past the freeze point.  This shows up most typically in
30921 the form of an error message complaining that a representation item
30922 appears too late, and the appropriate corrective action is to move
30923 the item nearer to the declaration of the entity to which it refers.
30924
30925 A particular case is that representation pragmas
30926 @ifset vms
30927 (including the
30928 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
30929 @end ifset
30930 cannot be applied to a subprogram body.  If necessary, a separate subprogram
30931 declaration must be introduced to which the pragma can be applied.
30932
30933 @item Optional bodies for library packages
30934 In Ada 83, a package that did not require a package body was nevertheless
30935 allowed to have one.  This lead to certain surprises in compiling large
30936 systems (situations in which the body could be unexpectedly ignored by the
30937 binder).  In Ada 95, if a package does not require a body then it is not
30938 permitted to have a body.  To fix this problem, simply remove a redundant
30939 body if it is empty, or, if it is non-empty, introduce a dummy declaration
30940 into the spec that makes the body required.  One approach is to add a private
30941 part to the package declaration (if necessary), and define a parameterless
30942 procedure called @code{Requires_Body}, which must then be given a dummy
30943 procedure body in the package body, which then becomes required.
30944 Another approach (assuming that this does not introduce elaboration
30945 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
30946 since one effect of this pragma is to require the presence of a package body.
30947
30948 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
30949 In Ada 95, the exception @code{Numeric_Error} is a renaming of
30950 @code{Constraint_Error}.
30951 This means that it is illegal to have separate exception handlers for
30952 the two exceptions.  The fix is simply to remove the handler for the
30953 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
30954 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
30955
30956 @item Indefinite subtypes in generics
30957 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
30958 as the actual for a generic formal private type, but then the instantiation
30959 would be illegal if there were any instances of declarations of variables
30960 of this type in the generic body.  In Ada 95, to avoid this clear violation
30961 of the methodological principle known as the ``contract model'',
30962 the generic declaration explicitly indicates whether
30963 or not such instantiations are permitted.  If a generic formal parameter
30964 has explicit unknown discriminants, indicated by using @code{(<>)} after the
30965 type name, then it can be instantiated with indefinite types, but no
30966 stand-alone variables can be declared of this type.  Any attempt to declare
30967 such a variable will result in an illegality at the time the generic is
30968 declared.  If the @code{(<>)} notation is not used, then it is illegal
30969 to instantiate the generic with an indefinite type.
30970 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
30971 It will show up as a compile time error, and
30972 the fix is usually simply to add the @code{(<>)} to the generic declaration.
30973 @end table
30974
30975 @node More deterministic semantics
30976 @subsection More deterministic semantics
30977
30978 @table @emph
30979 @item Conversions
30980 Conversions from real types to integer types round away from 0.  In Ada 83
30981 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
30982 implementation freedom was intended to support unbiased rounding in
30983 statistical applications, but in practice it interfered with portability.
30984 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
30985 is required.  Numeric code may be affected by this change in semantics.
30986 Note, though, that this issue is no worse than already existed in Ada 83
30987 when porting code from one vendor to another.
30988
30989 @item Tasking
30990 The Real-Time Annex introduces a set of policies that define the behavior of
30991 features that were implementation dependent in Ada 83, such as the order in
30992 which open select branches are executed.
30993 @end table
30994
30995 @node Changed semantics
30996 @subsection Changed semantics
30997
30998 @noindent
30999 The worst kind of incompatibility is one where a program that is legal in
31000 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
31001 possible in Ada 83.  Fortunately this is extremely rare, but the one
31002 situation that you should be alert to is the change in the predefined type
31003 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
31004
31005 @table @emph
31006 @item Range of type @code{Character}
31007 The range of @code{Standard.Character} is now the full 256 characters
31008 of Latin-1, whereas in most Ada 83 implementations it was restricted
31009 to 128 characters. Although some of the effects of
31010 this change will be manifest in compile-time rejection of legal
31011 Ada 83 programs it is possible for a working Ada 83 program to have
31012 a different effect in Ada 95, one that was not permitted in Ada 83.
31013 As an example, the expression
31014 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
31015 delivers @code{255} as its value.
31016 In general, you should look at the logic of any
31017 character-processing Ada 83 program and see whether it needs to be adapted
31018 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
31019 character handling package that may be relevant if code needs to be adapted
31020 to account for the additional Latin-1 elements.
31021 The desirable fix is to
31022 modify the program to accommodate the full character set, but in some cases
31023 it may be convenient to define a subtype or derived type of Character that
31024 covers only the restricted range.
31025 @cindex Latin-1
31026 @end table
31027
31028 @node Other language compatibility issues
31029 @subsection Other language compatibility issues
31030
31031 @table @emph
31032 @item @option{-gnat83} switch
31033 All implementations of GNAT provide a switch that causes GNAT to operate
31034 in Ada 83 mode.  In this mode, some but not all compatibility problems
31035 of the type described above are handled automatically.  For example, the
31036 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
31037 as identifiers as in Ada 83.
31038 However,
31039 in practice, it is usually advisable to make the necessary modifications
31040 to the program to remove the need for using this switch.
31041 See @ref{Compiling Different Versions of Ada}.
31042
31043 @item Support for removed Ada 83 pragmas and attributes
31044 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
31045 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
31046 compilers are allowed, but not required, to implement these missing
31047 elements.  In contrast with some other compilers, GNAT implements all
31048 such pragmas and attributes, eliminating this compatibility concern.  These
31049 include @code{pragma Interface} and the floating point type attributes
31050 (@code{Emax}, @code{Mantissa}, etc.), among other items.
31051 @end table
31052
31053
31054 @node Compatibility between Ada 95 and Ada 2005
31055 @section Compatibility between Ada 95 and Ada 2005
31056 @cindex Compatibility between Ada 95 and Ada 2005
31057
31058 @noindent
31059 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
31060 a number of incompatibilities. Several are enumerated below;
31061 for a complete description please see the
31062 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
31063 @cite{Rationale for Ada 2005}.
31064
31065 @table @emph
31066 @item New reserved words.
31067 The words @code{interface}, @code{overriding} and @code{synchronized} are
31068 reserved in Ada 2005.
31069 A pre-Ada 2005 program that uses any of these as an identifier will be
31070 illegal.
31071
31072 @item New declarations in predefined packages.
31073 A number of packages in the predefined environment contain new declarations:
31074 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
31075 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
31076 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
31077 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
31078 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
31079 If an Ada 95 program does a @code{with} and @code{use} of any of these
31080 packages, the new declarations may cause name clashes.
31081
31082 @item Access parameters.
31083 A nondispatching subprogram with an access parameter cannot be renamed
31084 as a dispatching operation.  This was permitted in Ada 95.
31085
31086 @item Access types, discriminants, and constraints.
31087 Rule changes in this area have led to some incompatibilities; for example,
31088 constrained subtypes of some access types are not permitted in Ada 2005.
31089
31090 @item Aggregates for limited types.
31091 The allowance of aggregates for limited types in Ada 2005 raises the
31092 possibility of ambiguities in legal Ada 95 programs, since additional types
31093 now need to be considered in expression resolution.
31094
31095 @item Fixed-point multiplication and division.
31096 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
31097 were legal in Ada 95 and invoked the predefined versions of these operations,
31098 are now ambiguous.
31099 The ambiguity may be resolved either by applying a type conversion to the
31100 expression, or by explicitly invoking the operation from package
31101 @code{Standard}.
31102
31103 @item Return-by-reference types.
31104 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
31105 can declare a function returning a value from an anonymous access type.
31106 @end table
31107
31108
31109 @node Implementation-dependent characteristics
31110 @section Implementation-dependent characteristics
31111 @noindent
31112 Although the Ada language defines the semantics of each construct as
31113 precisely as practical, in some situations (for example for reasons of
31114 efficiency, or where the effect is heavily dependent on the host or target
31115 platform) the implementation is allowed some freedom.  In porting Ada 83
31116 code to GNAT, you need to be aware of whether / how the existing code
31117 exercised such implementation dependencies.  Such characteristics fall into
31118 several categories, and GNAT offers specific support in assisting the
31119 transition from certain Ada 83 compilers.
31120
31121 @menu
31122 * Implementation-defined pragmas::
31123 * Implementation-defined attributes::
31124 * Libraries::
31125 * Elaboration order::
31126 * Target-specific aspects::
31127 @end menu
31128
31129 @node Implementation-defined pragmas
31130 @subsection Implementation-defined pragmas
31131
31132 @noindent
31133 Ada compilers are allowed to supplement the language-defined pragmas, and
31134 these are a potential source of non-portability.  All GNAT-defined pragmas
31135 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
31136 Reference Manual}, and these include several that are specifically
31137 intended to correspond to other vendors' Ada 83 pragmas.
31138 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
31139 For compatibility with HP Ada 83, GNAT supplies the pragmas
31140 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
31141 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
31142 and @code{Volatile}.
31143 Other relevant pragmas include @code{External} and @code{Link_With}.
31144 Some vendor-specific
31145 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
31146 recognized, thus
31147 avoiding compiler rejection of units that contain such pragmas; they are not
31148 relevant in a GNAT context and hence are not otherwise implemented.
31149
31150 @node Implementation-defined attributes
31151 @subsection Implementation-defined attributes
31152
31153 Analogous to pragmas, the set of attributes may be extended by an
31154 implementation.  All GNAT-defined attributes are described in
31155 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
31156 Manual}, and these include several that are specifically intended
31157 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
31158 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
31159 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
31160 @code{Type_Class}.
31161
31162 @node Libraries
31163 @subsection Libraries
31164 @noindent
31165 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
31166 code uses vendor-specific libraries then there are several ways to manage
31167 this in Ada 95 or Ada 2005:
31168 @enumerate
31169 @item
31170 If the source code for the libraries (specs and bodies) are
31171 available, then the libraries can be migrated in the same way as the
31172 application.
31173 @item
31174 If the source code for the specs but not the bodies are
31175 available, then you can reimplement the bodies.
31176 @item
31177 Some features introduced by Ada 95 obviate the need for library support.  For
31178 example most Ada 83 vendors supplied a package for unsigned integers.  The
31179 Ada 95 modular type feature is the preferred way to handle this need, so
31180 instead of migrating or reimplementing the unsigned integer package it may
31181 be preferable to retrofit the application using modular types.
31182 @end enumerate
31183
31184 @node Elaboration order
31185 @subsection Elaboration order
31186 @noindent
31187 The implementation can choose any elaboration order consistent with the unit
31188 dependency relationship.  This freedom means that some orders can result in
31189 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
31190 to invoke a subprogram its body has been elaborated, or to instantiate a
31191 generic before the generic body has been elaborated.  By default GNAT
31192 attempts to choose a safe order (one that will not encounter access before
31193 elaboration problems) by implicitly inserting @code{Elaborate} or
31194 @code{Elaborate_All} pragmas where
31195 needed.  However, this can lead to the creation of elaboration circularities
31196 and a resulting rejection of the program by gnatbind.  This issue is
31197 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
31198 In brief, there are several
31199 ways to deal with this situation:
31200
31201 @itemize @bullet
31202 @item
31203 Modify the program to eliminate the circularities, e.g.@: by moving
31204 elaboration-time code into explicitly-invoked procedures
31205 @item
31206 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
31207 @code{Elaborate} pragmas, and then inhibit the generation of implicit
31208 @code{Elaborate_All}
31209 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
31210 (by selectively suppressing elaboration checks via pragma
31211 @code{Suppress(Elaboration_Check)} when it is safe to do so).
31212 @end itemize
31213
31214 @node Target-specific aspects
31215 @subsection Target-specific aspects
31216 @noindent
31217 Low-level applications need to deal with machine addresses, data
31218 representations, interfacing with assembler code, and similar issues.  If
31219 such an Ada 83 application is being ported to different target hardware (for
31220 example where the byte endianness has changed) then you will need to
31221 carefully examine the program logic; the porting effort will heavily depend
31222 on the robustness of the original design.  Moreover, Ada 95 (and thus
31223 Ada 2005) are sometimes
31224 incompatible with typical Ada 83 compiler practices regarding implicit
31225 packing, the meaning of the Size attribute, and the size of access values.
31226 GNAT's approach to these issues is described in @ref{Representation Clauses}.
31227
31228 @node Compatibility with Other Ada Systems
31229 @section Compatibility with Other Ada Systems
31230
31231 @noindent
31232 If programs avoid the use of implementation dependent and
31233 implementation defined features, as documented in the @cite{Ada
31234 Reference Manual}, there should be a high degree of portability between
31235 GNAT and other Ada systems.  The following are specific items which
31236 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
31237 compilers, but do not affect porting code to GNAT@.
31238 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
31239 the following issues may or may not arise for Ada 2005 programs
31240 when other compilers appear.)
31241
31242 @table @emph
31243 @item Ada 83 Pragmas and Attributes
31244 Ada 95 compilers are allowed, but not required, to implement the missing
31245 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
31246 GNAT implements all such pragmas and attributes, eliminating this as
31247 a compatibility concern, but some other Ada 95 compilers reject these
31248 pragmas and attributes.
31249
31250 @item Specialized Needs Annexes
31251 GNAT implements the full set of special needs annexes.  At the
31252 current time, it is the only Ada 95 compiler to do so.  This means that
31253 programs making use of these features may not be portable to other Ada
31254 95 compilation systems.
31255
31256 @item Representation Clauses
31257 Some other Ada 95 compilers implement only the minimal set of
31258 representation clauses required by the Ada 95 reference manual.  GNAT goes
31259 far beyond this minimal set, as described in the next section.
31260 @end table
31261
31262 @node Representation Clauses
31263 @section Representation Clauses
31264
31265 @noindent
31266 The Ada 83 reference manual was quite vague in describing both the minimal
31267 required implementation of representation clauses, and also their precise
31268 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
31269 minimal set of capabilities required is still quite limited.
31270
31271 GNAT implements the full required set of capabilities in
31272 Ada 95 and Ada 2005, but also goes much further, and in particular
31273 an effort has been made to be compatible with existing Ada 83 usage to the
31274 greatest extent possible.
31275
31276 A few cases exist in which Ada 83 compiler behavior is incompatible with
31277 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
31278 intentional or accidental dependence on specific implementation dependent
31279 characteristics of these Ada 83 compilers.  The following is a list of
31280 the cases most likely to arise in existing Ada 83 code.
31281
31282 @table @emph
31283 @item Implicit Packing
31284 Some Ada 83 compilers allowed a Size specification to cause implicit
31285 packing of an array or record.  This could cause expensive implicit
31286 conversions for change of representation in the presence of derived
31287 types, and the Ada design intends to avoid this possibility.
31288 Subsequent AI's were issued to make it clear that such implicit
31289 change of representation in response to a Size clause is inadvisable,
31290 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
31291 Reference Manuals as implementation advice that is followed by GNAT@.
31292 The problem will show up as an error
31293 message rejecting the size clause.  The fix is simply to provide
31294 the explicit pragma @code{Pack}, or for more fine tuned control, provide
31295 a Component_Size clause.
31296
31297 @item Meaning of Size Attribute
31298 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
31299 the minimal number of bits required to hold values of the type.  For example,
31300 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
31301 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
31302 some 32 in this situation.  This problem will usually show up as a compile
31303 time error, but not always.  It is a good idea to check all uses of the
31304 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
31305 Object_Size can provide a useful way of duplicating the behavior of
31306 some Ada 83 compiler systems.
31307
31308 @item Size of Access Types
31309 A common assumption in Ada 83 code is that an access type is in fact a pointer,
31310 and that therefore it will be the same size as a System.Address value.  This
31311 assumption is true for GNAT in most cases with one exception.  For the case of
31312 a pointer to an unconstrained array type (where the bounds may vary from one
31313 value of the access type to another), the default is to use a ``fat pointer'',
31314 which is represented as two separate pointers, one to the bounds, and one to
31315 the array.  This representation has a number of advantages, including improved
31316 efficiency.  However, it may cause some difficulties in porting existing Ada 83
31317 code which makes the assumption that, for example, pointers fit in 32 bits on
31318 a machine with 32-bit addressing.
31319
31320 To get around this problem, GNAT also permits the use of ``thin pointers'' for
31321 access types in this case (where the designated type is an unconstrained array
31322 type).  These thin pointers are indeed the same size as a System.Address value.
31323 To specify a thin pointer, use a size clause for the type, for example:
31324
31325 @smallexample @c ada
31326 type X is access all String;
31327 for X'Size use Standard'Address_Size;
31328 @end smallexample
31329
31330 @noindent
31331 which will cause the type X to be represented using a single pointer.
31332 When using this representation, the bounds are right behind the array.
31333 This representation is slightly less efficient, and does not allow quite
31334 such flexibility in the use of foreign pointers or in using the
31335 Unrestricted_Access attribute to create pointers to non-aliased objects.
31336 But for any standard portable use of the access type it will work in
31337 a functionally correct manner and allow porting of existing code.
31338 Note that another way of forcing a thin pointer representation
31339 is to use a component size clause for the element size in an array,
31340 or a record representation clause for an access field in a record.
31341 @end table
31342
31343 @ifclear vms
31344 @c This brief section is only in the non-VMS version
31345 @c The complete chapter on HP Ada is in the VMS version
31346 @node Compatibility with HP Ada 83
31347 @section Compatibility with HP Ada 83
31348
31349 @noindent
31350 The VMS version of GNAT fully implements all the pragmas and attributes
31351 provided by HP Ada 83, as well as providing the standard HP Ada 83
31352 libraries, including Starlet.  In addition, data layouts and parameter
31353 passing conventions are highly compatible.  This means that porting
31354 existing HP Ada 83 code to GNAT in VMS systems should be easier than
31355 most other porting efforts.  The following are some of the most
31356 significant differences between GNAT and HP Ada 83.
31357
31358 @table @emph
31359 @item Default floating-point representation
31360 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
31361 it is VMS format.  GNAT does implement the necessary pragmas
31362 (Long_Float, Float_Representation) for changing this default.
31363
31364 @item System
31365 The package System in GNAT exactly corresponds to the definition in the
31366 Ada 95 reference manual, which means that it excludes many of the
31367 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
31368 that contains the additional definitions, and a special pragma,
31369 Extend_System allows this package to be treated transparently as an
31370 extension of package System.
31371
31372 @item To_Address
31373 The definitions provided by Aux_DEC are exactly compatible with those
31374 in the HP Ada 83 version of System, with one exception.
31375 HP Ada provides the following declarations:
31376
31377 @smallexample @c ada
31378 TO_ADDRESS (INTEGER)
31379 TO_ADDRESS (UNSIGNED_LONGWORD)
31380 TO_ADDRESS (@i{universal_integer})
31381 @end smallexample
31382
31383 @noindent
31384 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
31385 an extension to Ada 83 not strictly compatible with the reference manual.
31386 In GNAT, we are constrained to be exactly compatible with the standard,
31387 and this means we cannot provide this capability.  In HP Ada 83, the
31388 point of this definition is to deal with a call like:
31389
31390 @smallexample @c ada
31391 TO_ADDRESS (16#12777#);
31392 @end smallexample
31393
31394 @noindent
31395 Normally, according to the Ada 83 standard, one would expect this to be
31396 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
31397 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
31398 definition using @i{universal_integer} takes precedence.
31399
31400 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
31401 is not possible to be 100% compatible.  Since there are many programs using
31402 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
31403 to change the name of the function in the UNSIGNED_LONGWORD case, so the
31404 declarations provided in the GNAT version of AUX_Dec are:
31405
31406 @smallexample @c ada
31407 function To_Address (X : Integer) return Address;
31408 pragma Pure_Function (To_Address);
31409
31410 function To_Address_Long (X : Unsigned_Longword)
31411  return Address;
31412 pragma Pure_Function (To_Address_Long);
31413 @end smallexample
31414
31415 @noindent
31416 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
31417 change the name to TO_ADDRESS_LONG@.
31418
31419 @item Task_Id values
31420 The Task_Id values assigned will be different in the two systems, and GNAT
31421 does not provide a specified value for the Task_Id of the environment task,
31422 which in GNAT is treated like any other declared task.
31423 @end table
31424
31425 @noindent
31426 For full details on these and other less significant compatibility issues,
31427 see appendix E of the HP publication entitled @cite{HP Ada, Technical
31428 Overview and Comparison on HP Platforms}.
31429
31430 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
31431 attributes are recognized, although only a subset of them can sensibly
31432 be implemented.  The description of pragmas in @ref{Implementation
31433 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
31434 indicates whether or not they are applicable to non-VMS systems.
31435 @end ifclear
31436
31437 @ifset vms
31438 @node Transitioning to 64-Bit GNAT for OpenVMS
31439 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
31440
31441 @noindent
31442 This section is meant to assist users of pre-2006 @value{EDITION}
31443 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
31444 the version of the GNAT technology supplied in 2006 and later for
31445 OpenVMS on both Alpha and I64.
31446
31447 @menu
31448 * Introduction to transitioning::
31449 * Migration of 32 bit code::
31450 * Taking advantage of 64 bit addressing::
31451 * Technical details::
31452 @end menu
31453
31454 @node Introduction to transitioning
31455 @subsection Introduction
31456
31457 @noindent
31458 64-bit @value{EDITION} for Open VMS has been designed to meet
31459 three main goals:
31460
31461 @enumerate
31462 @item
31463 Providing a full conforming implementation of Ada 95 and Ada 2005
31464
31465 @item
31466 Allowing maximum backward compatibility, thus easing migration of existing
31467 Ada source code
31468
31469 @item
31470 Supplying a path for exploiting the full 64-bit address range
31471 @end enumerate
31472
31473 @noindent
31474 Ada's strong typing semantics has made it
31475 impractical to have different 32-bit and 64-bit modes. As soon as
31476 one object could possibly be outside the 32-bit address space, this
31477 would make it necessary for the @code{System.Address} type to be 64 bits.
31478 In particular, this would cause inconsistencies if 32-bit code is
31479 called from 64-bit code that raises an exception.
31480
31481 This issue has been resolved by always using 64-bit addressing
31482 at the system level, but allowing for automatic conversions between
31483 32-bit and 64-bit addresses where required. Thus users who
31484 do not currently require 64-bit addressing capabilities, can
31485 recompile their code with only minimal changes (and indeed
31486 if the code is written in portable Ada, with no assumptions about
31487 the size of the @code{Address} type, then no changes at all are necessary).
31488 At the same time,
31489 this approach provides a simple, gradual upgrade path to future
31490 use of larger memories than available for 32-bit systems.
31491 Also, newly written applications or libraries will by default
31492 be fully compatible with future systems exploiting 64-bit
31493 addressing capabilities.
31494
31495 @ref{Migration of 32 bit code}, will focus on porting applications
31496 that do not require more than 2 GB of
31497 addressable memory. This code will be referred to as
31498 @emph{32-bit code}.
31499 For applications intending to exploit the full 64-bit address space,
31500 @ref{Taking advantage of 64 bit addressing},
31501 will consider further changes that may be required.
31502 Such code will be referred to below as @emph{64-bit code}.
31503
31504 @node Migration of 32 bit code
31505 @subsection Migration of 32-bit code
31506
31507 @menu
31508 * Address types::
31509 * Access types::
31510 * Unchecked conversions::
31511 * Predefined constants::
31512 * Interfacing with C::
31513 * Experience with source compatibility::
31514 @end menu
31515
31516 @node Address types
31517 @subsubsection Address types
31518
31519 @noindent
31520 To solve the problem of mixing 64-bit and 32-bit addressing,
31521 while maintaining maximum backward compatibility, the following
31522 approach has been taken:
31523
31524 @itemize @bullet
31525 @item
31526 @code{System.Address} always has a size of 64 bits
31527
31528 @item
31529 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
31530 @end itemize
31531
31532 @noindent
31533 Since @code{System.Short_Address} is a subtype of @code{System.Address},
31534 a @code{Short_Address}
31535 may be used where an @code{Address} is required, and vice versa, without
31536 needing explicit type conversions.
31537 By virtue of the Open VMS parameter passing conventions,
31538 even imported
31539 and exported subprograms that have 32-bit address parameters are
31540 compatible with those that have 64-bit address parameters.
31541 (See @ref{Making code 64 bit clean} for details.)
31542
31543 The areas that may need attention are those where record types have
31544 been defined that contain components of the type @code{System.Address}, and
31545 where objects of this type are passed to code expecting a record layout with
31546 32-bit addresses.
31547
31548 Different compilers on different platforms cannot be
31549 expected to represent the same type in the same way,
31550 since alignment constraints
31551 and other system-dependent properties affect the compiler's decision.
31552 For that reason, Ada code
31553 generally uses representation clauses to specify the expected
31554 layout where required.
31555
31556 If such a representation clause uses 32 bits for a component having
31557 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
31558 will detect that error and produce a specific diagnostic message.
31559 The developer should then determine whether the representation
31560 should be 64 bits or not and make either of two changes:
31561 change the size to 64 bits and leave the type as @code{System.Address}, or
31562 leave the size as 32 bits and change the type to @code{System.Short_Address}.
31563 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
31564 required in any code setting or accessing the field; the compiler will
31565 automatically perform any needed conversions between address
31566 formats.
31567
31568 @node Access types
31569 @subsubsection Access types
31570
31571 @noindent
31572 By default, objects designated by access values are always
31573 allocated in the 32-bit
31574 address space. Thus legacy code will never contain
31575 any objects that are not addressable with 32-bit addresses, and
31576 the compiler will never raise exceptions as result of mixing
31577 32-bit and 64-bit addresses.
31578
31579 However, the access values themselves are represented in 64 bits, for optimum
31580 performance and future compatibility with 64-bit code. As was
31581 the case with @code{System.Address}, the compiler will give an error message
31582 if an object or record component has a representation clause that
31583 requires the access value to fit in 32 bits. In such a situation,
31584 an explicit size clause for the access type, specifying 32 bits,
31585 will have the desired effect.
31586
31587 General access types (declared with @code{access all}) can never be
31588 32 bits, as values of such types must be able to refer to any object
31589 of the  designated type,
31590 including objects residing outside the 32-bit address range.
31591 Existing Ada 83 code will not contain such type definitions,
31592 however, since general access types were introduced in Ada 95.
31593
31594 @node Unchecked conversions
31595 @subsubsection Unchecked conversions
31596
31597 @noindent
31598 In the case of an @code{Unchecked_Conversion} where the source type is a
31599 64-bit access type or the type @code{System.Address}, and the target
31600 type is a 32-bit type, the compiler will generate a warning.
31601 Even though the generated code will still perform the required
31602 conversions, it is highly recommended in these cases to use
31603 respectively a 32-bit access type or @code{System.Short_Address}
31604 as the source type.
31605
31606 @node Predefined constants
31607 @subsubsection Predefined constants
31608
31609 @noindent
31610 The following table shows the correspondence between pre-2006 versions of
31611 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
31612 (``New''):
31613
31614 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
31615 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
31616 @item   @code{System.Word_Size}          @tab 32      @tab 64
31617 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
31618 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
31619 @item   @code{System.Address_Size}       @tab 32      @tab 64
31620 @end multitable
31621
31622 @noindent
31623 If you need to refer to the specific
31624 memory size of a 32-bit implementation, instead of the
31625 actual memory size, use @code{System.Short_Memory_Size}
31626 rather than @code{System.Memory_Size}.
31627 Similarly, references to @code{System.Address_Size} may need
31628 to be replaced by @code{System.Short_Address'Size}.
31629 The program @command{gnatfind} may be useful for locating
31630 references to the above constants, so that you can verify that they
31631 are still correct.
31632
31633 @node Interfacing with C
31634 @subsubsection Interfacing with C
31635
31636 @noindent
31637 In order to minimize the impact of the transition to 64-bit addresses on
31638 legacy programs, some fundamental types in the @code{Interfaces.C}
31639 package hierarchy continue to be represented in 32 bits.
31640 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
31641 This eases integration with the default HP C layout choices, for example
31642 as found in the system routines in @code{DECC$SHR.EXE}.
31643 Because of this implementation choice, the type fully compatible with
31644 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
31645 Depending on the context the compiler will issue a
31646 warning or an error when type @code{Address} is used, alerting the user to a
31647 potential problem. Otherwise 32-bit programs that use
31648 @code{Interfaces.C} should normally not require code modifications
31649
31650 The other issue arising with C interfacing concerns pragma @code{Convention}.
31651 For VMS 64-bit systems, there is an issue of the appropriate default size
31652 of C convention pointers in the absence of an explicit size clause. The HP
31653 C compiler can choose either 32 or 64 bits depending on compiler options.
31654 GNAT chooses 32-bits rather than 64-bits in the default case where no size
31655 clause is given. This proves a better choice for porting 32-bit legacy
31656 applications. In order to have a 64-bit representation, it is necessary to
31657 specify a size representation clause. For example:
31658
31659 @smallexample @c ada
31660 type int_star is access Interfaces.C.int;
31661 pragma Convention(C, int_star);
31662 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
31663 @end smallexample
31664
31665 @node Experience with source compatibility
31666 @subsubsection Experience with source compatibility
31667
31668 @noindent
31669 The Security Server and STARLET on I64 provide an interesting ``test case''
31670 for source compatibility issues, since it is in such system code
31671 where assumptions about @code{Address} size might be expected to occur.
31672 Indeed, there were a small number of occasions in the Security Server
31673 file @file{jibdef.ads}
31674 where a representation clause for a record type specified
31675 32 bits for a component of type @code{Address}.
31676 All of these errors were detected by the compiler.
31677 The repair was obvious and immediate; to simply replace @code{Address} by
31678 @code{Short_Address}.
31679
31680 In the case of STARLET, there were several record types that should
31681 have had representation clauses but did not.  In these record types
31682 there was an implicit assumption that an @code{Address} value occupied
31683 32 bits.
31684 These compiled without error, but their usage resulted in run-time error
31685 returns from STARLET system calls.
31686 Future GNAT technology enhancements may include a tool that detects and flags
31687 these sorts of potential source code porting problems.
31688
31689 @c ****************************************
31690 @node Taking advantage of 64 bit addressing
31691 @subsection Taking advantage of 64-bit addressing
31692
31693 @menu
31694 * Making code 64 bit clean::
31695 * Allocating memory from the 64 bit storage pool::
31696 * Restrictions on use of 64 bit objects::
31697 * Using 64 bit storage pools by default::
31698 * General access types::
31699 * STARLET and other predefined libraries::
31700 @end menu
31701
31702 @node Making code 64 bit clean
31703 @subsubsection Making code 64-bit clean
31704
31705 @noindent
31706 In order to prevent problems that may occur when (parts of) a
31707 system start using memory outside the 32-bit address range,
31708 we recommend some additional guidelines:
31709
31710 @itemize @bullet
31711 @item
31712 For imported subprograms that take parameters of the
31713 type @code{System.Address}, ensure that these subprograms can
31714 indeed handle 64-bit addresses. If not, or when in doubt,
31715 change the subprogram declaration to specify
31716 @code{System.Short_Address} instead.
31717
31718 @item
31719 Resolve all warnings related to size mismatches in
31720 unchecked conversions. Failing to do so causes
31721 erroneous execution if the source object is outside
31722 the 32-bit address space.
31723
31724 @item
31725 (optional) Explicitly use the 32-bit storage pool
31726 for access types used in a 32-bit context, or use
31727 generic access types where possible
31728 (@pxref{Restrictions on use of 64 bit objects}).
31729 @end itemize
31730
31731 @noindent
31732 If these rules are followed, the compiler will automatically insert
31733 any necessary checks to ensure that no addresses or access values
31734 passed to 32-bit code ever refer to objects outside the 32-bit
31735 address range.
31736 Any attempt to do this will raise @code{Constraint_Error}.
31737
31738 @node Allocating memory from the 64 bit storage pool
31739 @subsubsection Allocating memory from the 64-bit storage pool
31740
31741 @noindent
31742 For any access type @code{T} that potentially requires memory allocations
31743 beyond the 32-bit address space,
31744 use the following representation clause:
31745
31746 @smallexample @c ada
31747    for T'Storage_Pool use System.Pool_64;
31748 @end smallexample
31749
31750 @node Restrictions on use of 64 bit objects
31751 @subsubsection Restrictions on use of 64-bit objects
31752
31753 @noindent
31754 Taking the address of an object allocated from a 64-bit storage pool,
31755 and then passing this address to a subprogram expecting
31756 @code{System.Short_Address},
31757 or assigning it to a variable of type @code{Short_Address}, will cause
31758 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
31759 (@pxref{Making code 64 bit clean}), or checks are suppressed,
31760 no exception is raised and execution
31761 will become erroneous.
31762
31763 @node Using 64 bit storage pools by default
31764 @subsubsection Using 64-bit storage pools by default
31765
31766 @noindent
31767 In some cases it may be desirable to have the compiler allocate
31768 from 64-bit storage pools by default. This may be the case for
31769 libraries that are 64-bit clean, but may be used in both 32-bit
31770 and 64-bit contexts. For these cases the following configuration
31771 pragma may be specified:
31772
31773 @smallexample @c ada
31774   pragma Pool_64_Default;
31775 @end smallexample
31776
31777 @noindent
31778 Any code compiled in the context of this pragma will by default
31779 use the @code{System.Pool_64} storage pool. This default may be overridden
31780 for a specific access type @code{T} by the representation clause:
31781
31782 @smallexample @c ada
31783    for T'Storage_Pool use System.Pool_32;
31784 @end smallexample
31785
31786 @noindent
31787 Any object whose address may be passed to a subprogram with a
31788 @code{Short_Address} argument, or assigned to a variable of type
31789 @code{Short_Address}, needs to be allocated from this pool.
31790
31791 @node General access types
31792 @subsubsection General access types
31793
31794 @noindent
31795 Objects designated by access values from a
31796 general access type (declared with @code{access all}) are never allocated
31797 from a 64-bit storage pool. Code that uses general access types will
31798 accept objects allocated in either 32-bit or 64-bit address spaces,
31799 but never allocate objects outside the 32-bit address space.
31800 Using general access types ensures maximum compatibility with both
31801 32-bit and 64-bit code.
31802
31803 @node STARLET and other predefined libraries
31804 @subsubsection STARLET and other predefined libraries
31805
31806 @noindent
31807 All code that comes as part of GNAT is 64-bit clean, but the
31808 restrictions given in @ref{Restrictions on use of 64 bit objects},
31809 still apply. Look at the package
31810 specs to see in which contexts objects allocated
31811 in 64-bit address space are acceptable.
31812
31813 @node Technical details
31814 @subsection Technical details
31815
31816 @noindent
31817 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
31818 Ada standard with respect to the type of @code{System.Address}. Previous
31819 versions of GNAT Pro have defined this type as private and implemented it as a
31820 modular type.
31821
31822 In order to allow defining @code{System.Short_Address} as a proper subtype,
31823 and to match the implicit sign extension in parameter passing,
31824 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
31825 visible (i.e., non-private) integer type.
31826 Standard operations on the type, such as the binary operators ``+'', ``-'',
31827 etc., that take @code{Address} operands and return an @code{Address} result,
31828 have been hidden by declaring these
31829 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
31830 ambiguities that would otherwise result from overloading.
31831 (Note that, although @code{Address} is a visible integer type,
31832 good programming practice dictates against exploiting the type's
31833 integer properties such as literals, since this will compromise
31834 code portability.)
31835
31836 Defining @code{Address} as a visible integer type helps achieve
31837 maximum compatibility for existing Ada code,
31838 without sacrificing the capabilities of the 64-bit architecture.
31839 @end ifset
31840
31841 @c ************************************************
31842 @ifset unw
31843 @node Microsoft Windows Topics
31844 @appendix Microsoft Windows Topics
31845 @cindex Windows NT
31846 @cindex Windows 95
31847 @cindex Windows 98
31848
31849 @noindent
31850 This chapter describes topics that are specific to the Microsoft Windows
31851 platforms (NT, 2000, and XP Professional).
31852
31853 @menu
31854 * Using GNAT on Windows::
31855 * Using a network installation of GNAT::
31856 * CONSOLE and WINDOWS subsystems::
31857 * Temporary Files::
31858 * Mixed-Language Programming on Windows::
31859 * Windows Calling Conventions::
31860 * Introduction to Dynamic Link Libraries (DLLs)::
31861 * Using DLLs with GNAT::
31862 * Building DLLs with GNAT::
31863 * Building DLLs with GNAT Project files::
31864 * Building DLLs with gnatdll::
31865 * GNAT and Windows Resources::
31866 * Debugging a DLL::
31867 * Setting Stack Size from gnatlink::
31868 * Setting Heap Size from gnatlink::
31869 @end menu
31870
31871 @node Using GNAT on Windows
31872 @section Using GNAT on Windows
31873
31874 @noindent
31875 One of the strengths of the GNAT technology is that its tool set
31876 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
31877 @code{gdb} debugger, etc.) is used in the same way regardless of the
31878 platform.
31879
31880 On Windows this tool set is complemented by a number of Microsoft-specific
31881 tools that have been provided to facilitate interoperability with Windows
31882 when this is required. With these tools:
31883
31884 @itemize @bullet
31885
31886 @item
31887 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
31888 subsystems.
31889
31890 @item
31891 You can use any Dynamically Linked Library (DLL) in your Ada code (both
31892 relocatable and non-relocatable DLLs are supported).
31893
31894 @item
31895 You can build Ada DLLs for use in other applications. These applications
31896 can be written in a language other than Ada (e.g., C, C++, etc). Again both
31897 relocatable and non-relocatable Ada DLLs are supported.
31898
31899 @item
31900 You can include Windows resources in your Ada application.
31901
31902 @item
31903 You can use or create COM/DCOM objects.
31904 @end itemize
31905
31906 @noindent
31907 Immediately below are listed all known general GNAT-for-Windows restrictions.
31908 Other restrictions about specific features like Windows Resources and DLLs
31909 are listed in separate sections below.
31910
31911 @itemize @bullet
31912
31913 @item
31914 It is not possible to use @code{GetLastError} and @code{SetLastError}
31915 when tasking, protected records, or exceptions are used. In these
31916 cases, in order to implement Ada semantics, the GNAT run-time system
31917 calls certain Win32 routines that set the last error variable to 0 upon
31918 success. It should be possible to use @code{GetLastError} and
31919 @code{SetLastError} when tasking, protected record, and exception
31920 features are not used, but it is not guaranteed to work.
31921
31922 @item
31923 It is not possible to link against Microsoft libraries except for
31924 import libraries. The library must be built to be compatible with
31925 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
31926 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
31927 not be compatible with the GNAT runtime. Even if the library is
31928 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
31929
31930 @item
31931 When the compilation environment is located on FAT32 drives, users may
31932 experience recompilations of the source files that have not changed if
31933 Daylight Saving Time (DST) state has changed since the last time files
31934 were compiled. NTFS drives do not have this problem.
31935
31936 @item
31937 No components of the GNAT toolset use any entries in the Windows
31938 registry. The only entries that can be created are file associations and
31939 PATH settings, provided the user has chosen to create them at installation
31940 time, as well as some minimal book-keeping information needed to correctly
31941 uninstall or integrate different GNAT products.
31942 @end itemize
31943
31944 @node Using a network installation of GNAT
31945 @section Using a network installation of GNAT
31946
31947 @noindent
31948 Make sure the system on which GNAT is installed is accessible from the
31949 current machine, i.e., the install location is shared over the network.
31950 Shared resources are accessed on Windows by means of UNC paths, which
31951 have the format @code{\\server\sharename\path}
31952
31953 In order to use such a network installation, simply add the UNC path of the
31954 @file{bin} directory of your GNAT installation in front of your PATH. For
31955 example, if GNAT is installed in @file{\GNAT} directory of a share location
31956 called @file{c-drive} on a machine @file{LOKI}, the following command will
31957 make it available:
31958
31959 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
31960
31961 Be aware that every compilation using the network installation results in the
31962 transfer of large amounts of data across the network and will likely cause
31963 serious performance penalty.
31964
31965 @node CONSOLE and WINDOWS subsystems
31966 @section CONSOLE and WINDOWS subsystems
31967 @cindex CONSOLE Subsystem
31968 @cindex WINDOWS Subsystem
31969 @cindex -mwindows
31970
31971 @noindent
31972 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
31973 (which is the default subsystem) will always create a console when
31974 launching the application. This is not something desirable when the
31975 application has a Windows GUI. To get rid of this console the
31976 application must be using the @code{WINDOWS} subsystem. To do so
31977 the @option{-mwindows} linker option must be specified.
31978
31979 @smallexample
31980 $ gnatmake winprog -largs -mwindows
31981 @end smallexample
31982
31983 @node Temporary Files
31984 @section Temporary Files
31985 @cindex Temporary files
31986
31987 @noindent
31988 It is possible to control where temporary files gets created by setting
31989 the @env{TMP} environment variable. The file will be created:
31990
31991 @itemize
31992 @item Under the directory pointed to by the @env{TMP} environment variable if
31993 this directory exists.
31994
31995 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
31996 set (or not pointing to a directory) and if this directory exists.
31997
31998 @item Under the current working directory otherwise.
31999 @end itemize
32000
32001 @noindent
32002 This allows you to determine exactly where the temporary
32003 file will be created. This is particularly useful in networked
32004 environments where you may not have write access to some
32005 directories.
32006
32007 @node Mixed-Language Programming on Windows
32008 @section Mixed-Language Programming on Windows
32009
32010 @noindent
32011 Developing pure Ada applications on Windows is no different than on
32012 other GNAT-supported platforms. However, when developing or porting an
32013 application that contains a mix of Ada and C/C++, the choice of your
32014 Windows C/C++ development environment conditions your overall
32015 interoperability strategy.
32016
32017 If you use @command{gcc} to compile the non-Ada part of your application,
32018 there are no Windows-specific restrictions that affect the overall
32019 interoperability with your Ada code. If you plan to use
32020 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
32021 the following limitations:
32022
32023 @itemize @bullet
32024 @item
32025 You cannot link your Ada code with an object or library generated with
32026 Microsoft tools if these use the @code{.tls} section (Thread Local
32027 Storage section) since the GNAT linker does not yet support this section.
32028
32029 @item
32030 You cannot link your Ada code with an object or library generated with
32031 Microsoft tools if these use I/O routines other than those provided in
32032 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
32033 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
32034 libraries can cause a conflict with @code{msvcrt.dll} services. For
32035 instance Visual C++ I/O stream routines conflict with those in
32036 @code{msvcrt.dll}.
32037 @end itemize
32038
32039 @noindent
32040 If you do want to use the Microsoft tools for your non-Ada code and hit one
32041 of the above limitations, you have two choices:
32042
32043 @enumerate
32044 @item
32045 Encapsulate your non-Ada code in a DLL to be linked with your Ada
32046 application. In this case, use the Microsoft or whatever environment to
32047 build the DLL and use GNAT to build your executable
32048 (@pxref{Using DLLs with GNAT}).
32049
32050 @item
32051 Or you can encapsulate your Ada code in a DLL to be linked with the
32052 other part of your application. In this case, use GNAT to build the DLL
32053 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
32054 environment to build your executable.
32055 @end enumerate
32056
32057 @node Windows Calling Conventions
32058 @section Windows Calling Conventions
32059 @findex Stdcall
32060 @findex APIENTRY
32061
32062 @menu
32063 * C Calling Convention::
32064 * Stdcall Calling Convention::
32065 * Win32 Calling Convention::
32066 * DLL Calling Convention::
32067 @end menu
32068
32069 @noindent
32070 When a subprogram @code{F} (caller) calls a subprogram @code{G}
32071 (callee), there are several ways to push @code{G}'s parameters on the
32072 stack and there are several possible scenarios to clean up the stack
32073 upon @code{G}'s return. A calling convention is an agreed upon software
32074 protocol whereby the responsibilities between the caller (@code{F}) and
32075 the callee (@code{G}) are clearly defined. Several calling conventions
32076 are available for Windows:
32077
32078 @itemize @bullet
32079 @item
32080 @code{C} (Microsoft defined)
32081
32082 @item
32083 @code{Stdcall} (Microsoft defined)
32084
32085 @item
32086 @code{Win32} (GNAT specific)
32087
32088 @item
32089 @code{DLL} (GNAT specific)
32090 @end itemize
32091
32092 @node C Calling Convention
32093 @subsection @code{C} Calling Convention
32094
32095 @noindent
32096 This is the default calling convention used when interfacing to C/C++
32097 routines compiled with either @command{gcc} or Microsoft Visual C++.
32098
32099 In the @code{C} calling convention subprogram parameters are pushed on the
32100 stack by the caller from right to left. The caller itself is in charge of
32101 cleaning up the stack after the call. In addition, the name of a routine
32102 with @code{C} calling convention is mangled by adding a leading underscore.
32103
32104 The name to use on the Ada side when importing (or exporting) a routine
32105 with @code{C} calling convention is the name of the routine. For
32106 instance the C function:
32107
32108 @smallexample
32109 int get_val (long);
32110 @end smallexample
32111
32112 @noindent
32113 should be imported from Ada as follows:
32114
32115 @smallexample @c ada
32116 @group
32117 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32118 pragma Import (C, Get_Val, External_Name => "get_val");
32119 @end group
32120 @end smallexample
32121
32122 @noindent
32123 Note that in this particular case the @code{External_Name} parameter could
32124 have been omitted since, when missing, this parameter is taken to be the
32125 name of the Ada entity in lower case. When the @code{Link_Name} parameter
32126 is missing, as in the above example, this parameter is set to be the
32127 @code{External_Name} with a leading underscore.
32128
32129 When importing a variable defined in C, you should always use the @code{C}
32130 calling convention unless the object containing the variable is part of a
32131 DLL (in which case you should use the @code{Stdcall} calling
32132 convention, @pxref{Stdcall Calling Convention}).
32133
32134 @node Stdcall Calling Convention
32135 @subsection @code{Stdcall} Calling Convention
32136
32137 @noindent
32138 This convention, which was the calling convention used for Pascal
32139 programs, is used by Microsoft for all the routines in the Win32 API for
32140 efficiency reasons. It must be used to import any routine for which this
32141 convention was specified.
32142
32143 In the @code{Stdcall} calling convention subprogram parameters are pushed
32144 on the stack by the caller from right to left. The callee (and not the
32145 caller) is in charge of cleaning the stack on routine exit. In addition,
32146 the name of a routine with @code{Stdcall} calling convention is mangled by
32147 adding a leading underscore (as for the @code{C} calling convention) and a
32148 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
32149 bytes) of the parameters passed to the routine.
32150
32151 The name to use on the Ada side when importing a C routine with a
32152 @code{Stdcall} calling convention is the name of the C routine. The leading
32153 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
32154 the compiler. For instance the Win32 function:
32155
32156 @smallexample
32157 @b{APIENTRY} int get_val (long);
32158 @end smallexample
32159
32160 @noindent
32161 should be imported from Ada as follows:
32162
32163 @smallexample @c ada
32164 @group
32165 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32166 pragma Import (Stdcall, Get_Val);
32167 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
32168 @end group
32169 @end smallexample
32170
32171 @noindent
32172 As for the @code{C} calling convention, when the @code{External_Name}
32173 parameter is missing, it is taken to be the name of the Ada entity in lower
32174 case. If instead of writing the above import pragma you write:
32175
32176 @smallexample @c ada
32177 @group
32178 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32179 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
32180 @end group
32181 @end smallexample
32182
32183 @noindent
32184 then the imported routine is @code{_retrieve_val@@4}. However, if instead
32185 of specifying the @code{External_Name} parameter you specify the
32186 @code{Link_Name} as in the following example:
32187
32188 @smallexample @c ada
32189 @group
32190 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32191 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
32192 @end group
32193 @end smallexample
32194
32195 @noindent
32196 then the imported routine is @code{retrieve_val}, that is, there is no
32197 decoration at all. No leading underscore and no Stdcall suffix
32198 @code{@@}@code{@var{nn}}.
32199
32200 @noindent
32201 This is especially important as in some special cases a DLL's entry
32202 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
32203 name generated for a call has it.
32204
32205 @noindent
32206 It is also possible to import variables defined in a DLL by using an
32207 import pragma for a variable. As an example, if a DLL contains a
32208 variable defined as:
32209
32210 @smallexample
32211 int my_var;
32212 @end smallexample
32213
32214 @noindent
32215 then, to access this variable from Ada you should write:
32216
32217 @smallexample @c ada
32218 @group
32219 My_Var : Interfaces.C.int;
32220 pragma Import (Stdcall, My_Var);
32221 @end group
32222 @end smallexample
32223
32224 @noindent
32225 Note that to ease building cross-platform bindings this convention
32226 will be handled as a @code{C} calling convention on non-Windows platforms.
32227
32228 @node Win32 Calling Convention
32229 @subsection @code{Win32} Calling Convention
32230
32231 @noindent
32232 This convention, which is GNAT-specific is fully equivalent to the
32233 @code{Stdcall} calling convention described above.
32234
32235 @node DLL Calling Convention
32236 @subsection @code{DLL} Calling Convention
32237
32238 @noindent
32239 This convention, which is GNAT-specific is fully equivalent to the
32240 @code{Stdcall} calling convention described above.
32241
32242 @node Introduction to Dynamic Link Libraries (DLLs)
32243 @section Introduction to Dynamic Link Libraries (DLLs)
32244 @findex DLL
32245
32246 @noindent
32247 A Dynamically Linked Library (DLL) is a library that can be shared by
32248 several applications running under Windows. A DLL can contain any number of
32249 routines and variables.
32250
32251 One advantage of DLLs is that you can change and enhance them without
32252 forcing all the applications that depend on them to be relinked or
32253 recompiled. However, you should be aware than all calls to DLL routines are
32254 slower since, as you will understand below, such calls are indirect.
32255
32256 To illustrate the remainder of this section, suppose that an application
32257 wants to use the services of a DLL @file{API.dll}. To use the services
32258 provided by @file{API.dll} you must statically link against the DLL or
32259 an import library which contains a jump table with an entry for each
32260 routine and variable exported by the DLL. In the Microsoft world this
32261 import library is called @file{API.lib}. When using GNAT this import
32262 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
32263 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
32264
32265 After you have linked your application with the DLL or the import library
32266 and you run your application, here is what happens:
32267
32268 @enumerate
32269 @item
32270 Your application is loaded into memory.
32271
32272 @item
32273 The DLL @file{API.dll} is mapped into the address space of your
32274 application. This means that:
32275
32276 @itemize @bullet
32277 @item
32278 The DLL will use the stack of the calling thread.
32279
32280 @item
32281 The DLL will use the virtual address space of the calling process.
32282
32283 @item
32284 The DLL will allocate memory from the virtual address space of the calling
32285 process.
32286
32287 @item
32288 Handles (pointers) can be safely exchanged between routines in the DLL
32289 routines and routines in the application using the DLL.
32290 @end itemize
32291
32292 @item
32293 The entries in the jump table (from the import library @file{libAPI.dll.a}
32294 or @file{API.lib} or automatically created when linking against a DLL)
32295 which is part of your application are initialized with the addresses
32296 of the routines and variables in @file{API.dll}.
32297
32298 @item
32299 If present in @file{API.dll}, routines @code{DllMain} or
32300 @code{DllMainCRTStartup} are invoked. These routines typically contain
32301 the initialization code needed for the well-being of the routines and
32302 variables exported by the DLL.
32303 @end enumerate
32304
32305 @noindent
32306 There is an additional point which is worth mentioning. In the Windows
32307 world there are two kind of DLLs: relocatable and non-relocatable
32308 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
32309 in the target application address space. If the addresses of two
32310 non-relocatable DLLs overlap and these happen to be used by the same
32311 application, a conflict will occur and the application will run
32312 incorrectly. Hence, when possible, it is always preferable to use and
32313 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
32314 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
32315 User's Guide) removes the debugging symbols from the DLL but the DLL can
32316 still be relocated.
32317
32318 As a side note, an interesting difference between Microsoft DLLs and
32319 Unix shared libraries, is the fact that on most Unix systems all public
32320 routines are exported by default in a Unix shared library, while under
32321 Windows it is possible (but not required) to list exported routines in
32322 a definition file (@pxref{The Definition File}).
32323
32324 @node Using DLLs with GNAT
32325 @section Using DLLs with GNAT
32326
32327 @menu
32328 * Creating an Ada Spec for the DLL Services::
32329 * Creating an Import Library::
32330 @end menu
32331
32332 @noindent
32333 To use the services of a DLL, say @file{API.dll}, in your Ada application
32334 you must have:
32335
32336 @enumerate
32337 @item
32338 The Ada spec for the routines and/or variables you want to access in
32339 @file{API.dll}. If not available this Ada spec must be built from the C/C++
32340 header files provided with the DLL.
32341
32342 @item
32343 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
32344 mentioned an import library is a statically linked library containing the
32345 import table which will be filled at load time to point to the actual
32346 @file{API.dll} routines. Sometimes you don't have an import library for the
32347 DLL you want to use. The following sections will explain how to build
32348 one. Note that this is optional.
32349
32350 @item
32351 The actual DLL, @file{API.dll}.
32352 @end enumerate
32353
32354 @noindent
32355 Once you have all the above, to compile an Ada application that uses the
32356 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
32357 you simply issue the command
32358
32359 @smallexample
32360 $ gnatmake my_ada_app -largs -lAPI
32361 @end smallexample
32362
32363 @noindent
32364 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
32365 tells the GNAT linker to look first for a library named @file{API.lib}
32366 (Microsoft-style name) and if not found for a libraries named
32367 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
32368 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
32369 contains the following pragma
32370
32371 @smallexample @c ada
32372 pragma Linker_Options ("-lAPI");
32373 @end smallexample
32374
32375 @noindent
32376 you do not have to add @option{-largs -lAPI} at the end of the
32377 @command{gnatmake} command.
32378
32379 If any one of the items above is missing you will have to create it
32380 yourself. The following sections explain how to do so using as an
32381 example a fictitious DLL called @file{API.dll}.
32382
32383 @node Creating an Ada Spec for the DLL Services
32384 @subsection Creating an Ada Spec for the DLL Services
32385
32386 @noindent
32387 A DLL typically comes with a C/C++ header file which provides the
32388 definitions of the routines and variables exported by the DLL. The Ada
32389 equivalent of this header file is a package spec that contains definitions
32390 for the imported entities. If the DLL you intend to use does not come with
32391 an Ada spec you have to generate one such spec yourself. For example if
32392 the header file of @file{API.dll} is a file @file{api.h} containing the
32393 following two definitions:
32394
32395 @smallexample
32396 @group
32397 @cartouche
32398 int some_var;
32399 int get (char *);
32400 @end cartouche
32401 @end group
32402 @end smallexample
32403
32404 @noindent
32405 then the equivalent Ada spec could be:
32406
32407 @smallexample @c ada
32408 @group
32409 @cartouche
32410 with Interfaces.C.Strings;
32411 package API is
32412    use Interfaces;
32413
32414    Some_Var : C.int;
32415    function Get (Str : C.Strings.Chars_Ptr) return C.int;
32416
32417 private
32418    pragma Import (C, Get);
32419    pragma Import (DLL, Some_Var);
32420 end API;
32421 @end cartouche
32422 @end group
32423 @end smallexample
32424
32425 @noindent
32426 Note that a variable is
32427 @strong{always imported with a Stdcall convention}. A function
32428 can have @code{C} or @code{Stdcall} convention.
32429 (@pxref{Windows Calling Conventions}).
32430
32431 @node Creating an Import Library
32432 @subsection Creating an Import Library
32433 @cindex Import library
32434
32435 @menu
32436 * The Definition File::
32437 * GNAT-Style Import Library::
32438 * Microsoft-Style Import Library::
32439 @end menu
32440
32441 @noindent
32442 If a Microsoft-style import library @file{API.lib} or a GNAT-style
32443 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
32444 with @file{API.dll} you can skip this section. You can also skip this
32445 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
32446 as in this case it is possible to link directly against the
32447 DLL. Otherwise read on.
32448
32449 @node The Definition File
32450 @subsubsection The Definition File
32451 @cindex Definition file
32452 @findex .def
32453
32454 @noindent
32455 As previously mentioned, and unlike Unix systems, the list of symbols
32456 that are exported from a DLL must be provided explicitly in Windows.
32457 The main goal of a definition file is precisely that: list the symbols
32458 exported by a DLL. A definition file (usually a file with a @code{.def}
32459 suffix) has the following structure:
32460
32461 @smallexample
32462 @group
32463 @cartouche
32464 @r{[}LIBRARY @var{name}@r{]}
32465 @r{[}DESCRIPTION @var{string}@r{]}
32466 EXPORTS
32467    @var{symbol1}
32468    @var{symbol2}
32469    @dots{}
32470 @end cartouche
32471 @end group
32472 @end smallexample
32473
32474 @table @code
32475 @item LIBRARY @var{name}
32476 This section, which is optional, gives the name of the DLL.
32477
32478 @item DESCRIPTION @var{string}
32479 This section, which is optional, gives a description string that will be
32480 embedded in the import library.
32481
32482 @item EXPORTS
32483 This section gives the list of exported symbols (procedures, functions or
32484 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
32485 section of @file{API.def} looks like:
32486
32487 @smallexample
32488 @group
32489 @cartouche
32490 EXPORTS
32491    some_var
32492    get
32493 @end cartouche
32494 @end group
32495 @end smallexample
32496 @end table
32497
32498 @noindent
32499 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
32500 (@pxref{Windows Calling Conventions}) for a Stdcall
32501 calling convention function in the exported symbols list.
32502
32503 @noindent
32504 There can actually be other sections in a definition file, but these
32505 sections are not relevant to the discussion at hand.
32506
32507 @node GNAT-Style Import Library
32508 @subsubsection GNAT-Style Import Library
32509
32510 @noindent
32511 To create a static import library from @file{API.dll} with the GNAT tools
32512 you should proceed as follows:
32513
32514 @enumerate
32515 @item
32516 Create the definition file @file{API.def} (@pxref{The Definition File}).
32517 For that use the @code{dll2def} tool as follows:
32518
32519 @smallexample
32520 $ dll2def API.dll > API.def
32521 @end smallexample
32522
32523 @noindent
32524 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
32525 to standard output the list of entry points in the DLL. Note that if
32526 some routines in the DLL have the @code{Stdcall} convention
32527 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
32528 suffix then you'll have to edit @file{api.def} to add it, and specify
32529 @option{-k} to @command{gnatdll} when creating the import library.
32530
32531 @noindent
32532 Here are some hints to find the right @code{@@}@var{nn} suffix.
32533
32534 @enumerate
32535 @item
32536 If you have the Microsoft import library (.lib), it is possible to get
32537 the right symbols by using Microsoft @code{dumpbin} tool (see the
32538 corresponding Microsoft documentation for further details).
32539
32540 @smallexample
32541 $ dumpbin /exports api.lib
32542 @end smallexample
32543
32544 @item
32545 If you have a message about a missing symbol at link time the compiler
32546 tells you what symbol is expected. You just have to go back to the
32547 definition file and add the right suffix.
32548 @end enumerate
32549
32550 @item
32551 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
32552 (@pxref{Using gnatdll}) as follows:
32553
32554 @smallexample
32555 $ gnatdll -e API.def -d API.dll
32556 @end smallexample
32557
32558 @noindent
32559 @code{gnatdll} takes as input a definition file @file{API.def} and the
32560 name of the DLL containing the services listed in the definition file
32561 @file{API.dll}. The name of the static import library generated is
32562 computed from the name of the definition file as follows: if the
32563 definition file name is @var{xyz}@code{.def}, the import library name will
32564 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
32565 @option{-e} could have been removed because the name of the definition
32566 file (before the ``@code{.def}'' suffix) is the same as the name of the
32567 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
32568 @end enumerate
32569
32570 @node Microsoft-Style Import Library
32571 @subsubsection Microsoft-Style Import Library
32572
32573 @noindent
32574 With GNAT you can either use a GNAT-style or Microsoft-style import
32575 library. A Microsoft import library is needed only if you plan to make an
32576 Ada DLL available to applications developed with Microsoft
32577 tools (@pxref{Mixed-Language Programming on Windows}).
32578
32579 To create a Microsoft-style import library for @file{API.dll} you
32580 should proceed as follows:
32581
32582 @enumerate
32583 @item
32584 Create the definition file @file{API.def} from the DLL. For this use either
32585 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
32586 tool (see the corresponding Microsoft documentation for further details).
32587
32588 @item
32589 Build the actual import library using Microsoft's @code{lib} utility:
32590
32591 @smallexample
32592 $ lib -machine:IX86 -def:API.def -out:API.lib
32593 @end smallexample
32594
32595 @noindent
32596 If you use the above command the definition file @file{API.def} must
32597 contain a line giving the name of the DLL:
32598
32599 @smallexample
32600 LIBRARY      "API"
32601 @end smallexample
32602
32603 @noindent
32604 See the Microsoft documentation for further details about the usage of
32605 @code{lib}.
32606 @end enumerate
32607
32608 @node Building DLLs with GNAT
32609 @section Building DLLs with GNAT
32610 @cindex DLLs, building
32611
32612 @noindent
32613 This section explain how to build DLLs using the GNAT built-in DLL
32614 support. With the following procedure it is straight forward to build
32615 and use DLLs with GNAT.
32616
32617 @enumerate
32618
32619 @item building object files
32620
32621 The first step is to build all objects files that are to be included
32622 into the DLL. This is done by using the standard @command{gnatmake} tool.
32623
32624 @item building the DLL
32625
32626 To build the DLL you must use @command{gcc}'s @option{-shared}
32627 option. It is quite simple to use this method:
32628
32629 @smallexample
32630 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
32631 @end smallexample
32632
32633 It is important to note that in this case all symbols found in the
32634 object files are automatically exported. It is possible to restrict
32635 the set of symbols to export by passing to @command{gcc} a definition
32636 file, @pxref{The Definition File}. For example:
32637
32638 @smallexample
32639 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
32640 @end smallexample
32641
32642 If you use a definition file you must export the elaboration procedures
32643 for every package that required one. Elaboration procedures are named
32644 using the package name followed by "_E".
32645
32646 @item preparing DLL to be used
32647
32648 For the DLL to be used by client programs the bodies must be hidden
32649 from it and the .ali set with read-only attribute. This is very important
32650 otherwise GNAT will recompile all packages and will not actually use
32651 the code in the DLL. For example:
32652
32653 @smallexample
32654 $ mkdir apilib
32655 $ copy *.ads *.ali api.dll apilib
32656 $ attrib +R apilib\*.ali
32657 @end smallexample
32658
32659 @end enumerate
32660
32661 At this point it is possible to use the DLL by directly linking
32662 against it. Note that you must use the GNAT shared runtime when using
32663 GNAT shared libraries. This is achieved by using @option{-shared} binder's
32664 option.
32665
32666 @smallexample
32667 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
32668 @end smallexample
32669
32670 @node Building DLLs with GNAT Project files
32671 @section Building DLLs with GNAT Project files
32672 @cindex DLLs, building
32673
32674 @noindent
32675 There is nothing specific to Windows in the build process.
32676 @pxref{Library Projects}.
32677
32678 @noindent
32679 Due to a system limitation, it is not possible under Windows to create threads
32680 when inside the @code{DllMain} routine which is used for auto-initialization
32681 of shared libraries, so it is not possible to have library level tasks in SALs.
32682
32683 @node Building DLLs with gnatdll
32684 @section Building DLLs with gnatdll
32685 @cindex DLLs, building
32686
32687 @menu
32688 * Limitations When Using Ada DLLs from Ada::
32689 * Exporting Ada Entities::
32690 * Ada DLLs and Elaboration::
32691 * Ada DLLs and Finalization::
32692 * Creating a Spec for Ada DLLs::
32693 * Creating the Definition File::
32694 * Using gnatdll::
32695 @end menu
32696
32697 @noindent
32698 Note that it is preferred to use the built-in GNAT DLL support
32699 (@pxref{Building DLLs with GNAT}) or GNAT Project files
32700 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
32701
32702 This section explains how to build DLLs containing Ada code using
32703 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
32704 remainder of this section.
32705
32706 The steps required to build an Ada DLL that is to be used by Ada as well as
32707 non-Ada applications are as follows:
32708
32709 @enumerate
32710 @item
32711 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
32712 @code{Stdcall} calling convention to avoid any Ada name mangling for the
32713 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
32714 skip this step if you plan to use the Ada DLL only from Ada applications.
32715
32716 @item
32717 Your Ada code must export an initialization routine which calls the routine
32718 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
32719 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
32720 routine exported by the Ada DLL must be invoked by the clients of the DLL
32721 to initialize the DLL.
32722
32723 @item
32724 When useful, the DLL should also export a finalization routine which calls
32725 routine @code{adafinal} generated by @command{gnatbind} to perform the
32726 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
32727 The finalization routine exported by the Ada DLL must be invoked by the
32728 clients of the DLL when the DLL services are no further needed.
32729
32730 @item
32731 You must provide a spec for the services exported by the Ada DLL in each
32732 of the programming languages to which you plan to make the DLL available.
32733
32734 @item
32735 You must provide a definition file listing the exported entities
32736 (@pxref{The Definition File}).
32737
32738 @item
32739 Finally you must use @code{gnatdll} to produce the DLL and the import
32740 library (@pxref{Using gnatdll}).
32741 @end enumerate
32742
32743 @noindent
32744 Note that a relocatable DLL stripped using the @code{strip}
32745 binutils tool will not be relocatable anymore. To build a DLL without
32746 debug information pass @code{-largs -s} to @code{gnatdll}. This
32747 restriction does not apply to a DLL built using a Library Project.
32748 @pxref{Library Projects}.
32749
32750 @node Limitations When Using Ada DLLs from Ada
32751 @subsection Limitations When Using Ada DLLs from Ada
32752
32753 @noindent
32754 When using Ada DLLs from Ada applications there is a limitation users
32755 should be aware of. Because on Windows the GNAT run time is not in a DLL of
32756 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
32757 each Ada DLL includes the services of the GNAT run time that are necessary
32758 to the Ada code inside the DLL. As a result, when an Ada program uses an
32759 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
32760 one in the main program.
32761
32762 It is therefore not possible to exchange GNAT run-time objects between the
32763 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
32764 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
32765 types, etc.
32766
32767 It is completely safe to exchange plain elementary, array or record types,
32768 Windows object handles, etc.
32769
32770 @node Exporting Ada Entities
32771 @subsection Exporting Ada Entities
32772 @cindex Export table
32773
32774 @noindent
32775 Building a DLL is a way to encapsulate a set of services usable from any
32776 application. As a result, the Ada entities exported by a DLL should be
32777 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
32778 any Ada name mangling. As an example here is an Ada package
32779 @code{API}, spec and body, exporting two procedures, a function, and a
32780 variable:
32781
32782 @smallexample @c ada
32783 @group
32784 @cartouche
32785 with Interfaces.C; use Interfaces;
32786 package API is
32787    Count : C.int := 0;
32788    function Factorial (Val : C.int) return C.int;
32789
32790    procedure Initialize_API;
32791    procedure Finalize_API;
32792    --  Initialization & Finalization routines. More in the next section.
32793 private
32794    pragma Export (C, Initialize_API);
32795    pragma Export (C, Finalize_API);
32796    pragma Export (C, Count);
32797    pragma Export (C, Factorial);
32798 end API;
32799 @end cartouche
32800 @end group
32801 @end smallexample
32802
32803 @smallexample @c ada
32804 @group
32805 @cartouche
32806 package body API is
32807    function Factorial (Val : C.int) return C.int is
32808       Fact : C.int := 1;
32809    begin
32810       Count := Count + 1;
32811       for K in 1 .. Val loop
32812          Fact := Fact * K;
32813       end loop;
32814       return Fact;
32815    end Factorial;
32816
32817    procedure Initialize_API is
32818       procedure Adainit;
32819       pragma Import (C, Adainit);
32820    begin
32821       Adainit;
32822    end Initialize_API;
32823
32824    procedure Finalize_API is
32825       procedure Adafinal;
32826       pragma Import (C, Adafinal);
32827    begin
32828       Adafinal;
32829    end Finalize_API;
32830 end API;
32831 @end cartouche
32832 @end group
32833 @end smallexample
32834
32835 @noindent
32836 If the Ada DLL you are building will only be used by Ada applications
32837 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
32838 convention. As an example, the previous package could be written as
32839 follows:
32840
32841 @smallexample @c ada
32842 @group
32843 @cartouche
32844 package API is
32845    Count : Integer := 0;
32846    function Factorial (Val : Integer) return Integer;
32847
32848    procedure Initialize_API;
32849    procedure Finalize_API;
32850    --  Initialization and Finalization routines.
32851 end API;
32852 @end cartouche
32853 @end group
32854 @end smallexample
32855
32856 @smallexample @c ada
32857 @group
32858 @cartouche
32859 package body API is
32860    function Factorial (Val : Integer) return Integer is
32861       Fact : Integer := 1;
32862    begin
32863       Count := Count + 1;
32864       for K in 1 .. Val loop
32865          Fact := Fact * K;
32866       end loop;
32867       return Fact;
32868    end Factorial;
32869
32870    @dots{}
32871    --  The remainder of this package body is unchanged.
32872 end API;
32873 @end cartouche
32874 @end group
32875 @end smallexample
32876
32877 @noindent
32878 Note that if you do not export the Ada entities with a @code{C} or
32879 @code{Stdcall} convention you will have to provide the mangled Ada names
32880 in the definition file of the Ada DLL
32881 (@pxref{Creating the Definition File}).
32882
32883 @node Ada DLLs and Elaboration
32884 @subsection Ada DLLs and Elaboration
32885 @cindex DLLs and elaboration
32886
32887 @noindent
32888 The DLL that you are building contains your Ada code as well as all the
32889 routines in the Ada library that are needed by it. The first thing a
32890 user of your DLL must do is elaborate the Ada code
32891 (@pxref{Elaboration Order Handling in GNAT}).
32892
32893 To achieve this you must export an initialization routine
32894 (@code{Initialize_API} in the previous example), which must be invoked
32895 before using any of the DLL services. This elaboration routine must call
32896 the Ada elaboration routine @code{adainit} generated by the GNAT binder
32897 (@pxref{Binding with Non-Ada Main Programs}). See the body of
32898 @code{Initialize_Api} for an example. Note that the GNAT binder is
32899 automatically invoked during the DLL build process by the @code{gnatdll}
32900 tool (@pxref{Using gnatdll}).
32901
32902 When a DLL is loaded, Windows systematically invokes a routine called
32903 @code{DllMain}. It would therefore be possible to call @code{adainit}
32904 directly from @code{DllMain} without having to provide an explicit
32905 initialization routine. Unfortunately, it is not possible to call
32906 @code{adainit} from the @code{DllMain} if your program has library level
32907 tasks because access to the @code{DllMain} entry point is serialized by
32908 the system (that is, only a single thread can execute ``through'' it at a
32909 time), which means that the GNAT run time will deadlock waiting for the
32910 newly created task to complete its initialization.
32911
32912 @node Ada DLLs and Finalization
32913 @subsection Ada DLLs and Finalization
32914 @cindex DLLs and finalization
32915
32916 @noindent
32917 When the services of an Ada DLL are no longer needed, the client code should
32918 invoke the DLL finalization routine, if available. The DLL finalization
32919 routine is in charge of releasing all resources acquired by the DLL. In the
32920 case of the Ada code contained in the DLL, this is achieved by calling
32921 routine @code{adafinal} generated by the GNAT binder
32922 (@pxref{Binding with Non-Ada Main Programs}).
32923 See the body of @code{Finalize_Api} for an
32924 example. As already pointed out the GNAT binder is automatically invoked
32925 during the DLL build process by the @code{gnatdll} tool
32926 (@pxref{Using gnatdll}).
32927
32928 @node Creating a Spec for Ada DLLs
32929 @subsection Creating a Spec for Ada DLLs
32930
32931 @noindent
32932 To use the services exported by the Ada DLL from another programming
32933 language (e.g.@: C), you have to translate the specs of the exported Ada
32934 entities in that language. For instance in the case of @code{API.dll},
32935 the corresponding C header file could look like:
32936
32937 @smallexample
32938 @group
32939 @cartouche
32940 extern int *_imp__count;
32941 #define count (*_imp__count)
32942 int factorial (int);
32943 @end cartouche
32944 @end group
32945 @end smallexample
32946
32947 @noindent
32948 It is important to understand that when building an Ada DLL to be used by
32949 other Ada applications, you need two different specs for the packages
32950 contained in the DLL: one for building the DLL and the other for using
32951 the DLL. This is because the @code{DLL} calling convention is needed to
32952 use a variable defined in a DLL, but when building the DLL, the variable
32953 must have either the @code{Ada} or @code{C} calling convention. As an
32954 example consider a DLL comprising the following package @code{API}:
32955
32956 @smallexample @c ada
32957 @group
32958 @cartouche
32959 package API is
32960    Count : Integer := 0;
32961    @dots{}
32962    --  Remainder of the package omitted.
32963 end API;
32964 @end cartouche
32965 @end group
32966 @end smallexample
32967
32968 @noindent
32969 After producing a DLL containing package @code{API}, the spec that
32970 must be used to import @code{API.Count} from Ada code outside of the
32971 DLL is:
32972
32973 @smallexample @c ada
32974 @group
32975 @cartouche
32976 package API is
32977    Count : Integer;
32978    pragma Import (DLL, Count);
32979 end API;
32980 @end cartouche
32981 @end group
32982 @end smallexample
32983
32984 @node Creating the Definition File
32985 @subsection Creating the Definition File
32986
32987 @noindent
32988 The definition file is the last file needed to build the DLL. It lists
32989 the exported symbols. As an example, the definition file for a DLL
32990 containing only package @code{API} (where all the entities are exported
32991 with a @code{C} calling convention) is:
32992
32993 @smallexample
32994 @group
32995 @cartouche
32996 EXPORTS
32997     count
32998     factorial
32999     finalize_api
33000     initialize_api
33001 @end cartouche
33002 @end group
33003 @end smallexample
33004
33005 @noindent
33006 If the @code{C} calling convention is missing from package @code{API},
33007 then the definition file contains the mangled Ada names of the above
33008 entities, which in this case are:
33009
33010 @smallexample
33011 @group
33012 @cartouche
33013 EXPORTS
33014     api__count
33015     api__factorial
33016     api__finalize_api
33017     api__initialize_api
33018 @end cartouche
33019 @end group
33020 @end smallexample
33021
33022 @node Using gnatdll
33023 @subsection Using @code{gnatdll}
33024 @findex gnatdll
33025
33026 @menu
33027 * gnatdll Example::
33028 * gnatdll behind the Scenes::
33029 * Using dlltool::
33030 @end menu
33031
33032 @noindent
33033 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
33034 and non-Ada sources that make up your DLL have been compiled.
33035 @code{gnatdll} is actually in charge of two distinct tasks: build the
33036 static import library for the DLL and the actual DLL. The form of the
33037 @code{gnatdll} command is
33038
33039 @smallexample
33040 @cartouche
33041 $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
33042 @end cartouche
33043 @end smallexample
33044
33045 @noindent
33046 where @var{list-of-files} is a list of ALI and object files. The object
33047 file list must be the exact list of objects corresponding to the non-Ada
33048 sources whose services are to be included in the DLL. The ALI file list
33049 must be the exact list of ALI files for the corresponding Ada sources
33050 whose services are to be included in the DLL. If @var{list-of-files} is
33051 missing, only the static import library is generated.
33052
33053 @noindent
33054 You may specify any of the following switches to @code{gnatdll}:
33055
33056 @table @code
33057 @item -a@ovar{address}
33058 @cindex @option{-a} (@code{gnatdll})
33059 Build a non-relocatable DLL at @var{address}. If @var{address} is not
33060 specified the default address @var{0x11000000} will be used. By default,
33061 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
33062 advise the reader to build relocatable DLL.
33063
33064 @item -b @var{address}
33065 @cindex @option{-b} (@code{gnatdll})
33066 Set the relocatable DLL base address. By default the address is
33067 @code{0x11000000}.
33068
33069 @item -bargs @var{opts}
33070 @cindex @option{-bargs} (@code{gnatdll})
33071 Binder options. Pass @var{opts} to the binder.
33072
33073 @item -d @var{dllfile}
33074 @cindex @option{-d} (@code{gnatdll})
33075 @var{dllfile} is the name of the DLL. This switch must be present for
33076 @code{gnatdll} to do anything. The name of the generated import library is
33077 obtained algorithmically from @var{dllfile} as shown in the following
33078 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
33079 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
33080 by option @option{-e}) is obtained algorithmically from @var{dllfile}
33081 as shown in the following example:
33082 if @var{dllfile} is @code{xyz.dll}, the definition
33083 file used is @code{xyz.def}.
33084
33085 @item -e @var{deffile}
33086 @cindex @option{-e} (@code{gnatdll})
33087 @var{deffile} is the name of the definition file.
33088
33089 @item -g
33090 @cindex @option{-g} (@code{gnatdll})
33091 Generate debugging information. This information is stored in the object
33092 file and copied from there to the final DLL file by the linker,
33093 where it can be read by the debugger. You must use the
33094 @option{-g} switch if you plan on using the debugger or the symbolic
33095 stack traceback.
33096
33097 @item -h
33098 @cindex @option{-h} (@code{gnatdll})
33099 Help mode. Displays @code{gnatdll} switch usage information.
33100
33101 @item -Idir
33102 @cindex @option{-I} (@code{gnatdll})
33103 Direct @code{gnatdll} to search the @var{dir} directory for source and
33104 object files needed to build the DLL.
33105 (@pxref{Search Paths and the Run-Time Library (RTL)}).
33106
33107 @item -k
33108 @cindex @option{-k} (@code{gnatdll})
33109 Removes the @code{@@}@var{nn} suffix from the import library's exported
33110 names, but keeps them for the link names. You must specify this
33111 option if you want to use a @code{Stdcall} function in a DLL for which
33112 the @code{@@}@var{nn} suffix has been removed. This is the case for most
33113 of the Windows NT DLL for example. This option has no effect when
33114 @option{-n} option is specified.
33115
33116 @item -l @var{file}
33117 @cindex @option{-l} (@code{gnatdll})
33118 The list of ALI and object files used to build the DLL are listed in
33119 @var{file}, instead of being given in the command line. Each line in
33120 @var{file} contains the name of an ALI or object file.
33121
33122 @item -n
33123 @cindex @option{-n} (@code{gnatdll})
33124 No Import. Do not create the import library.
33125
33126 @item -q
33127 @cindex @option{-q} (@code{gnatdll})
33128 Quiet mode. Do not display unnecessary messages.
33129
33130 @item -v
33131 @cindex @option{-v} (@code{gnatdll})
33132 Verbose mode. Display extra information.
33133
33134 @item -largs @var{opts}
33135 @cindex @option{-largs} (@code{gnatdll})
33136 Linker options. Pass @var{opts} to the linker.
33137 @end table
33138
33139 @node gnatdll Example
33140 @subsubsection @code{gnatdll} Example
33141
33142 @noindent
33143 As an example the command to build a relocatable DLL from @file{api.adb}
33144 once @file{api.adb} has been compiled and @file{api.def} created is
33145
33146 @smallexample
33147 $ gnatdll -d api.dll api.ali
33148 @end smallexample
33149
33150 @noindent
33151 The above command creates two files: @file{libapi.dll.a} (the import
33152 library) and @file{api.dll} (the actual DLL). If you want to create
33153 only the DLL, just type:
33154
33155 @smallexample
33156 $ gnatdll -d api.dll -n api.ali
33157 @end smallexample
33158
33159 @noindent
33160 Alternatively if you want to create just the import library, type:
33161
33162 @smallexample
33163 $ gnatdll -d api.dll
33164 @end smallexample
33165
33166 @node gnatdll behind the Scenes
33167 @subsubsection @code{gnatdll} behind the Scenes
33168
33169 @noindent
33170 This section details the steps involved in creating a DLL. @code{gnatdll}
33171 does these steps for you. Unless you are interested in understanding what
33172 goes on behind the scenes, you should skip this section.
33173
33174 We use the previous example of a DLL containing the Ada package @code{API},
33175 to illustrate the steps necessary to build a DLL. The starting point is a
33176 set of objects that will make up the DLL and the corresponding ALI
33177 files. In the case of this example this means that @file{api.o} and
33178 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
33179 the following:
33180
33181 @enumerate
33182 @item
33183 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
33184 the information necessary to generate relocation information for the
33185 DLL.
33186
33187 @smallexample
33188 @group
33189 $ gnatbind -n api
33190 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
33191 @end group
33192 @end smallexample
33193
33194 @noindent
33195 In addition to the base file, the @command{gnatlink} command generates an
33196 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
33197 asks @command{gnatlink} to generate the routines @code{DllMain} and
33198 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
33199 is loaded into memory.
33200
33201 @item
33202 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
33203 export table (@file{api.exp}). The export table contains the relocation
33204 information in a form which can be used during the final link to ensure
33205 that the Windows loader is able to place the DLL anywhere in memory.
33206
33207 @smallexample
33208 @group
33209 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33210           --output-exp api.exp
33211 @end group
33212 @end smallexample
33213
33214 @item
33215 @code{gnatdll} builds the base file using the new export table. Note that
33216 @command{gnatbind} must be called once again since the binder generated file
33217 has been deleted during the previous call to @command{gnatlink}.
33218
33219 @smallexample
33220 @group
33221 $ gnatbind -n api
33222 $ gnatlink api -o api.jnk api.exp -mdll
33223       -Wl,--base-file,api.base
33224 @end group
33225 @end smallexample
33226
33227 @item
33228 @code{gnatdll} builds the new export table using the new base file and
33229 generates the DLL import library @file{libAPI.dll.a}.
33230
33231 @smallexample
33232 @group
33233 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33234           --output-exp api.exp --output-lib libAPI.a
33235 @end group
33236 @end smallexample
33237
33238 @item
33239 Finally @code{gnatdll} builds the relocatable DLL using the final export
33240 table.
33241
33242 @smallexample
33243 @group
33244 $ gnatbind -n api
33245 $ gnatlink api api.exp -o api.dll -mdll
33246 @end group
33247 @end smallexample
33248 @end enumerate
33249
33250 @node Using dlltool
33251 @subsubsection Using @code{dlltool}
33252
33253 @noindent
33254 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
33255 DLLs and static import libraries. This section summarizes the most
33256 common @code{dlltool} switches. The form of the @code{dlltool} command
33257 is
33258
33259 @smallexample
33260 $ dlltool @ovar{switches}
33261 @end smallexample
33262
33263 @noindent
33264 @code{dlltool} switches include:
33265
33266 @table @option
33267 @item --base-file @var{basefile}
33268 @cindex @option{--base-file} (@command{dlltool})
33269 Read the base file @var{basefile} generated by the linker. This switch
33270 is used to create a relocatable DLL.
33271
33272 @item --def @var{deffile}
33273 @cindex @option{--def} (@command{dlltool})
33274 Read the definition file.
33275
33276 @item --dllname @var{name}
33277 @cindex @option{--dllname} (@command{dlltool})
33278 Gives the name of the DLL. This switch is used to embed the name of the
33279 DLL in the static import library generated by @code{dlltool} with switch
33280 @option{--output-lib}.
33281
33282 @item -k
33283 @cindex @option{-k} (@command{dlltool})
33284 Kill @code{@@}@var{nn} from exported names
33285 (@pxref{Windows Calling Conventions}
33286 for a discussion about @code{Stdcall}-style symbols.
33287
33288 @item --help
33289 @cindex @option{--help} (@command{dlltool})
33290 Prints the @code{dlltool} switches with a concise description.
33291
33292 @item --output-exp @var{exportfile}
33293 @cindex @option{--output-exp} (@command{dlltool})
33294 Generate an export file @var{exportfile}. The export file contains the
33295 export table (list of symbols in the DLL) and is used to create the DLL.
33296
33297 @item --output-lib @var{libfile}
33298 @cindex @option{--output-lib} (@command{dlltool})
33299 Generate a static import library @var{libfile}.
33300
33301 @item -v
33302 @cindex @option{-v} (@command{dlltool})
33303 Verbose mode.
33304
33305 @item --as @var{assembler-name}
33306 @cindex @option{--as} (@command{dlltool})
33307 Use @var{assembler-name} as the assembler. The default is @code{as}.
33308 @end table
33309
33310 @node GNAT and Windows Resources
33311 @section GNAT and Windows Resources
33312 @cindex Resources, windows
33313
33314 @menu
33315 * Building Resources::
33316 * Compiling Resources::
33317 * Using Resources::
33318 @end menu
33319
33320 @noindent
33321 Resources are an easy way to add Windows specific objects to your
33322 application. The objects that can be added as resources include:
33323
33324 @itemize @bullet
33325 @item
33326 menus
33327
33328 @item
33329 accelerators
33330
33331 @item
33332 dialog boxes
33333
33334 @item
33335 string tables
33336
33337 @item
33338 bitmaps
33339
33340 @item
33341 cursors
33342
33343 @item
33344 icons
33345
33346 @item
33347 fonts
33348 @end itemize
33349
33350 @noindent
33351 This section explains how to build, compile and use resources.
33352
33353 @node Building Resources
33354 @subsection Building Resources
33355 @cindex Resources, building
33356
33357 @noindent
33358 A resource file is an ASCII file. By convention resource files have an
33359 @file{.rc} extension.
33360 The easiest way to build a resource file is to use Microsoft tools
33361 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
33362 @code{dlgedit.exe} to build dialogs.
33363 It is always possible to build an @file{.rc} file yourself by writing a
33364 resource script.
33365
33366 It is not our objective to explain how to write a resource file. A
33367 complete description of the resource script language can be found in the
33368 Microsoft documentation.
33369
33370 @node Compiling Resources
33371 @subsection Compiling Resources
33372 @findex rc
33373 @findex windres
33374 @cindex Resources, compiling
33375
33376 @noindent
33377 This section describes how to build a GNAT-compatible (COFF) object file
33378 containing the resources. This is done using the Resource Compiler
33379 @code{windres} as follows:
33380
33381 @smallexample
33382 $ windres -i myres.rc -o myres.o
33383 @end smallexample
33384
33385 @noindent
33386 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
33387 file. You can specify an alternate preprocessor (usually named
33388 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
33389 parameter. A list of all possible options may be obtained by entering
33390 the command @code{windres} @option{--help}.
33391
33392 It is also possible to use the Microsoft resource compiler @code{rc.exe}
33393 to produce a @file{.res} file (binary resource file). See the
33394 corresponding Microsoft documentation for further details. In this case
33395 you need to use @code{windres} to translate the @file{.res} file to a
33396 GNAT-compatible object file as follows:
33397
33398 @smallexample
33399 $ windres -i myres.res -o myres.o
33400 @end smallexample
33401
33402 @node Using Resources
33403 @subsection Using Resources
33404 @cindex Resources, using
33405
33406 @noindent
33407 To include the resource file in your program just add the
33408 GNAT-compatible object file for the resource(s) to the linker
33409 arguments. With @command{gnatmake} this is done by using the @option{-largs}
33410 option:
33411
33412 @smallexample
33413 $ gnatmake myprog -largs myres.o
33414 @end smallexample
33415
33416 @node Debugging a DLL
33417 @section Debugging a DLL
33418 @cindex DLL debugging
33419
33420 @menu
33421 * Program and DLL Both Built with GCC/GNAT::
33422 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
33423 @end menu
33424
33425 @noindent
33426 Debugging a DLL is similar to debugging a standard program. But
33427 we have to deal with two different executable parts: the DLL and the
33428 program that uses it. We have the following four possibilities:
33429
33430 @enumerate 1
33431 @item
33432 The program and the DLL are built with @code{GCC/GNAT}.
33433 @item
33434 The program is built with foreign tools and the DLL is built with
33435 @code{GCC/GNAT}.
33436 @item
33437 The program is built with @code{GCC/GNAT} and the DLL is built with
33438 foreign tools.
33439 @item
33440 @end enumerate
33441
33442 @noindent
33443 In this section we address only cases one and two above.
33444 There is no point in trying to debug
33445 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
33446 information in it. To do so you must use a debugger compatible with the
33447 tools suite used to build the DLL.
33448
33449 @node Program and DLL Both Built with GCC/GNAT
33450 @subsection Program and DLL Both Built with GCC/GNAT
33451
33452 @noindent
33453 This is the simplest case. Both the DLL and the program have @code{GDB}
33454 compatible debugging information. It is then possible to break anywhere in
33455 the process. Let's suppose here that the main procedure is named
33456 @code{ada_main} and that in the DLL there is an entry point named
33457 @code{ada_dll}.
33458
33459 @noindent
33460 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
33461 program must have been built with the debugging information (see GNAT -g
33462 switch). Here are the step-by-step instructions for debugging it:
33463
33464 @enumerate 1
33465 @item Launch @code{GDB} on the main program.
33466
33467 @smallexample
33468 $ gdb -nw ada_main
33469 @end smallexample
33470
33471 @item Start the program and stop at the beginning of the main procedure
33472
33473 @smallexample
33474 (gdb) start
33475 @end smallexample
33476
33477 @noindent
33478 This step is required to be able to set a breakpoint inside the DLL. As long
33479 as the program is not run, the DLL is not loaded. This has the
33480 consequence that the DLL debugging information is also not loaded, so it is not
33481 possible to set a breakpoint in the DLL.
33482
33483 @item Set a breakpoint inside the DLL
33484
33485 @smallexample
33486 (gdb) break ada_dll
33487 (gdb) cont
33488 @end smallexample
33489
33490 @end enumerate
33491
33492 @noindent
33493 At this stage a breakpoint is set inside the DLL. From there on
33494 you can use the standard approach to debug the whole program
33495 (@pxref{Running and Debugging Ada Programs}).
33496
33497 @ignore
33498 @c This used to work, probably because the DLLs were non-relocatable
33499 @c keep this section around until the problem is sorted out.
33500
33501 To break on the @code{DllMain} routine it is not possible to follow
33502 the procedure above. At the time the program stop on @code{ada_main}
33503 the @code{DllMain} routine as already been called. Either you can use
33504 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
33505
33506 @enumerate 1
33507 @item Launch @code{GDB} on the main program.
33508
33509 @smallexample
33510 $ gdb ada_main
33511 @end smallexample
33512
33513 @item Load DLL symbols
33514
33515 @smallexample
33516 (gdb) add-sym api.dll
33517 @end smallexample
33518
33519 @item Set a breakpoint inside the DLL
33520
33521 @smallexample
33522 (gdb) break ada_dll.adb:45
33523 @end smallexample
33524
33525 Note that at this point it is not possible to break using the routine symbol
33526 directly as the program is not yet running. The solution is to break
33527 on the proper line (break in @file{ada_dll.adb} line 45).
33528
33529 @item Start the program
33530
33531 @smallexample
33532 (gdb) run
33533 @end smallexample
33534
33535 @end enumerate
33536 @end ignore
33537
33538 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
33539 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
33540
33541 @menu
33542 * Debugging the DLL Directly::
33543 * Attaching to a Running Process::
33544 @end menu
33545
33546 @noindent
33547 In this case things are slightly more complex because it is not possible to
33548 start the main program and then break at the beginning to load the DLL and the
33549 associated DLL debugging information. It is not possible to break at the
33550 beginning of the program because there is no @code{GDB} debugging information,
33551 and therefore there is no direct way of getting initial control. This
33552 section addresses this issue by describing some methods that can be used
33553 to break somewhere in the DLL to debug it.
33554
33555 @noindent
33556 First suppose that the main procedure is named @code{main} (this is for
33557 example some C code built with Microsoft Visual C) and that there is a
33558 DLL named @code{test.dll} containing an Ada entry point named
33559 @code{ada_dll}.
33560
33561 @noindent
33562 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
33563 been built with debugging information (see GNAT -g option).
33564
33565 @node Debugging the DLL Directly
33566 @subsubsection Debugging the DLL Directly
33567
33568 @enumerate 1
33569 @item
33570 Find out the executable starting address
33571
33572 @smallexample
33573 $ objdump --file-header main.exe
33574 @end smallexample
33575
33576 The starting address is reported on the last line. For example:
33577
33578 @smallexample
33579 main.exe:     file format pei-i386
33580 architecture: i386, flags 0x0000010a:
33581 EXEC_P, HAS_DEBUG, D_PAGED
33582 start address 0x00401010
33583 @end smallexample
33584
33585 @item
33586 Launch the debugger on the executable.
33587
33588 @smallexample
33589 $ gdb main.exe
33590 @end smallexample
33591
33592 @item
33593 Set a breakpoint at the starting address, and launch the program.
33594
33595 @smallexample
33596 $ (gdb) break *0x00401010
33597 $ (gdb) run
33598 @end smallexample
33599
33600 The program will stop at the given address.
33601
33602 @item
33603 Set a breakpoint on a DLL subroutine.
33604
33605 @smallexample
33606 (gdb) break ada_dll.adb:45
33607 @end smallexample
33608
33609 Or if you want to break using a symbol on the DLL, you need first to
33610 select the Ada language (language used by the DLL).
33611
33612 @smallexample
33613 (gdb) set language ada
33614 (gdb) break ada_dll
33615 @end smallexample
33616
33617 @item
33618 Continue the program.
33619
33620 @smallexample
33621 (gdb) cont
33622 @end smallexample
33623
33624 @noindent
33625 This will run the program until it reaches the breakpoint that has been
33626 set. From that point you can use the standard way to debug a program
33627 as described in (@pxref{Running and Debugging Ada Programs}).
33628
33629 @end enumerate
33630
33631 @noindent
33632 It is also possible to debug the DLL by attaching to a running process.
33633
33634 @node Attaching to a Running Process
33635 @subsubsection Attaching to a Running Process
33636 @cindex DLL debugging, attach to process
33637
33638 @noindent
33639 With @code{GDB} it is always possible to debug a running process by
33640 attaching to it. It is possible to debug a DLL this way. The limitation
33641 of this approach is that the DLL must run long enough to perform the
33642 attach operation. It may be useful for instance to insert a time wasting
33643 loop in the code of the DLL to meet this criterion.
33644
33645 @enumerate 1
33646
33647 @item Launch the main program @file{main.exe}.
33648
33649 @smallexample
33650 $ main
33651 @end smallexample
33652
33653 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
33654 that the process PID for @file{main.exe} is 208.
33655
33656 @item Launch gdb.
33657
33658 @smallexample
33659 $ gdb
33660 @end smallexample
33661
33662 @item Attach to the running process to be debugged.
33663
33664 @smallexample
33665 (gdb) attach 208
33666 @end smallexample
33667
33668 @item Load the process debugging information.
33669
33670 @smallexample
33671 (gdb) symbol-file main.exe
33672 @end smallexample
33673
33674 @item Break somewhere in the DLL.
33675
33676 @smallexample
33677 (gdb) break ada_dll
33678 @end smallexample
33679
33680 @item Continue process execution.
33681
33682 @smallexample
33683 (gdb) cont
33684 @end smallexample
33685
33686 @end enumerate
33687
33688 @noindent
33689 This last step will resume the process execution, and stop at
33690 the breakpoint we have set. From there you can use the standard
33691 approach to debug a program as described in
33692 (@pxref{Running and Debugging Ada Programs}).
33693
33694 @node Setting Stack Size from gnatlink
33695 @section Setting Stack Size from @command{gnatlink}
33696
33697 @noindent
33698 It is possible to specify the program stack size at link time. On modern
33699 versions of Windows, starting with XP, this is mostly useful to set the size of
33700 the main stack (environment task). The other task stacks are set with pragma
33701 Storage_Size or with the @command{gnatbind -d} command.
33702
33703 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
33704 reserve size of individual tasks, the link-time stack size applies to all
33705 tasks, and pragma Storage_Size has no effect.
33706 In particular, Stack Overflow checks are made against this
33707 link-time specified size.
33708
33709 This setting can be done with
33710 @command{gnatlink} using either:
33711
33712 @itemize @bullet
33713
33714 @item using @option{-Xlinker} linker option
33715
33716 @smallexample
33717 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
33718 @end smallexample
33719
33720 This sets the stack reserve size to 0x10000 bytes and the stack commit
33721 size to 0x1000 bytes.
33722
33723 @item using @option{-Wl} linker option
33724
33725 @smallexample
33726 $ gnatlink hello -Wl,--stack=0x1000000
33727 @end smallexample
33728
33729 This sets the stack reserve size to 0x1000000 bytes. Note that with
33730 @option{-Wl} option it is not possible to set the stack commit size
33731 because the coma is a separator for this option.
33732
33733 @end itemize
33734
33735 @node Setting Heap Size from gnatlink
33736 @section Setting Heap Size from @command{gnatlink}
33737
33738 @noindent
33739 Under Windows systems, it is possible to specify the program heap size from
33740 @command{gnatlink} using either:
33741
33742 @itemize @bullet
33743
33744 @item using @option{-Xlinker} linker option
33745
33746 @smallexample
33747 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
33748 @end smallexample
33749
33750 This sets the heap reserve size to 0x10000 bytes and the heap commit
33751 size to 0x1000 bytes.
33752
33753 @item using @option{-Wl} linker option
33754
33755 @smallexample
33756 $ gnatlink hello -Wl,--heap=0x1000000
33757 @end smallexample
33758
33759 This sets the heap reserve size to 0x1000000 bytes. Note that with
33760 @option{-Wl} option it is not possible to set the heap commit size
33761 because the coma is a separator for this option.
33762
33763 @end itemize
33764
33765 @end ifset
33766
33767 @c **********************************
33768 @c * GNU Free Documentation License *
33769 @c **********************************
33770 @include fdl.texi
33771 @c GNU Free Documentation License
33772
33773 @node Index,,GNU Free Documentation License, Top
33774 @unnumbered Index
33775
33776 @printindex cp
33777
33778 @contents
33779 @c Put table of contents at end, otherwise it precedes the "title page" in
33780 @c the .txt version
33781 @c Edit the pdf file to move the contents to the beginning, after the title
33782 @c page
33783
33784 @bye